Skip to content

Commit

Permalink
code review
Browse files Browse the repository at this point in the history
  • Loading branch information
shreemaan-abhishek committed Sep 11, 2024
1 parent 093d7a9 commit 7b52fa5
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions apisix/plugins/ai-content-moderation.lua
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ local pairs = pairs
local unpack = unpack
local type = type
local ipairs = ipairs
local require = require
local internal_server_error = ngx.HTTP_INTERNAL_SERVER_ERROR
local bad_request = ngx.HTTP_BAD_REQUEST


local aws_comprehend_schema = {
type = "object",
Expand Down Expand Up @@ -94,17 +98,17 @@ end
function _M.rewrite(conf, ctx)
conf = fetch_secrets(conf, true, conf, "")
if not conf then
return 500, "failed to retrieve secrets from conf"
return internal_server_error, "failed to retrieve secrets from conf"
end

local body, err = core.request.get_body_table()
if not body then
return 400, err
return bad_request, err
end

local msgs = body.messages
if not msgs or type(msgs) ~= "table" or #msgs < 1 then
return 400, "messages not found in request body"
if type(msgs) ~= "table" or #msgs < 1 then
return bad_request, "messages not found in request body"
end

local provider = conf.provider[next(conf.provider)]
Expand Down Expand Up @@ -140,12 +144,12 @@ function _M.rewrite(conf, ctx)

if not res then
core.log.error("failed to send request to ", provider, ": ", err)
return 500, err
return internal_server_error, err
end

local results = res.body and res.body.ResultList
if not results or type(results) ~= "table" or #results < 1 then
return 500, "failed to get moderation results from response"
return internal_server_error, "failed to get moderation results from response"
end

for _, result in ipairs(results) do
Expand All @@ -155,14 +159,14 @@ function _M.rewrite(conf, ctx)
goto continue
end
if item.Score > conf.moderation_categories[item.Name] then
return 400, "request body exceeds " .. item.Name .. " threshold"
return bad_request, "request body exceeds " .. item.Name .. " threshold"
end
::continue::
end
end

if result.Toxicity > conf.toxicity_level then
return 400, "request body exceeds toxicity threshold"
return bad_request, "request body exceeds toxicity threshold"
end
end
end
Expand Down

0 comments on commit 7b52fa5

Please sign in to comment.