diff --git a/plugins/response_guard.lua b/plugins/response_guard.lua index 03d3d6b..0a4a547 100644 --- a/plugins/response_guard.lua +++ b/plugins/response_guard.lua @@ -31,6 +31,33 @@ local CONTEXT_CHUNK_BYTES = 8192 local MAX_CONTEXT_BYTES = 8192 local CONTEXT_LABELS = { user = "User: ", assistant = "Assistant: " } +-- 判定类别 → 中文短理由(≤5 字)。键必须与 middleware/llm.py 的 CATEGORY_LABELS +-- 逐字一致(含大小写与空格),否则查表落空、退到按 kind 兜底。 +-- 两个隐私条目指向同一理由:上游模型对同一含义有长短两种写法。 +local CATEGORY_REASON = { + ["Violent"] = "暴力", + ["Non-violent Illegal Acts"] = "违法", + ["Sexual Content or Sexual Acts"] = "色情", + ["PII"] = "隐私", + ["Personally Identifiable Information"] = "隐私", + ["Suicide & Self-Harm"] = "自残", + ["Unethical Acts"] = "失德", + ["Politically Sensitive Topics"] = "涉政", + ["Copyright Violation"] = "侵权", + ["Jailbreak"] = "越狱", +} + +-- 守卫模型只报 Safety、不报类别(Categories: None)时拿不到类别,按拦截位置兜底, +-- 保证每条拦截都有理由,前端不必处理空值。 +local function reason_for(kind, category) + if type(category) == "string" then + local label = CATEGORY_REASON[category] + if label then return label end + end + return (kind == "output") and "输出违规" or "输入违规" +end + + local DEFAULT_STREAM_PATH = "choices.*.delta.content" local DEFAULT_FULL_PATH = "choices.*.message.content" @@ -393,12 +420,14 @@ local function has_sentence_boundary(s) end local function policy_denied(verdict, kind) + local category = (verdict and verdict.category) or "other" return { status = config.block_status, type = "invalid_request_error", code = "content_policy_violation", message = (kind == "output") and config.block_message_output or config.block_message_input, - category = (verdict and verdict.category) or "other", + category = category, + reason = reason_for(kind, category), } end @@ -409,16 +438,24 @@ local function policy_unavailable(reason) code = "safety_review_unavailable", message = "The content safety review could not complete. Please retry.", category = reason or "unavailable", + reason = "复核失败", } end +-- reason 是 OpenAI 规范外的扩展字段,客户端忽略即可互不影响; +-- 同时把理由缀进 message,让人直接看响应也能知道为什么被拦。 local function error_body(policy) + local message = policy.message + if type(policy.reason) == "string" and policy.reason ~= "" then + message = message .. " [" .. policy.reason .. "]" + end return host.json.encode({ error = { - message = policy.message, + message = message, type = policy.type, param = host.json.null, code = policy.code, + reason = policy.reason, }, }) end