guard: 判定请求体按 OpenAI 协议校正

1) 新增 judge_token_param / judge_temperature / judge_json_mode,默认值保持 deepseek 可直接跑,换 gpt-5、o 系列不再 400 全站 503;
2) base_url 归一化,写主机、写 /v1、写完整端点都落到 /v1/chat/completions;
3) system_prompt 缺 json 关键字时自动补一句,规避 json_object 的 400;
4) 请求体解析补 {type:input_text} 内容块,修掉换写法绕过输入审核;
5) 新增 config.example.yaml(占位密钥)与 3 组回归用例,verify 84/84。
This commit is contained in:
Автомата Калашникова committed 2026-11-27 18:34:12 +08:00
1 parent 68b3b36539
commit 1cc154dff8
4 files changed
+288 -10

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
upstream: http://127.0.0.1:8000
listen_host: 0.0.0.0
listen_port: 8080
limits:
max_sessions: 4
# 判定走远程 /chat/completions:单次 1~5s,最多切 8 段,留足余量
hook_timeout_seconds: 45
upstream_timeout_seconds: 120
max_attachment_files: 8
max_attachment_fields: 128
max_attachment_text_bytes: 1048576
max_attachment_unpacked_bytes: 33554432
max_attachment_zip_entries: 2048
attachment_timeout_seconds: 30
max_attachment_reads: 64
# 不再注册本地守卫模型(models/guard_model 已停用)。
# 判定统一走下面的 OpenAI 兼容接口,密钥只存在于本文件,不会进日志。
plugins:
# ---------------------------------------------------------------------------
# 输入 + 输出内容安全
# 请求侧:判定不通过 → 请求体换成 stub(原文不发给模型)→ 响应侧返回 400
# 响应侧:逐段审核 → 脱敏 → 放行;不安全/审核不可用 → OpenAI 错误体
# ---------------------------------------------------------------------------
- id: response-guard
file: plugins/response_guard.lua
match:
paths: ["/v1/chat/completions"]
network:
allow:
- domain: ai.leapstella.com
scheme: https
ports: [443]
timeout_seconds: 20
max_response_bytes: 1048576
config:
# 判定端点 = base_url + /chat/completions;base_url 写下面三种都可以:
# https://your-gateway.example → 自动补 /v1/chat/completions
# https://your-gateway.example/v1 → /v1/chat/completions
# https://your-gateway.example/v1/chat/completions(完整端点)
base_url: https://ai.leapstella.com/v1
# 复制本文件为 config.yaml 后填入你自己的密钥,config.yaml 已被 .gitignore 忽略
api_key: "sk-REPLACE_ME"
model: deepseek-flash
# 拦截状态码:400 = OpenAI 内容策略拒绝的标准形态
block_status: 400
# incremental: 攒够 flush_chars 且遇到句边界就审核放行(有增量输出)
# buffered : 整条响应结束再一次审核(1 次判定,但客户端看不到增量)
stream_mode: incremental
flush_chars: 512
force_flush_bytes: 4096
# 上限与判定能力对齐:8 段 × judge_chunk_bytes(16KB) = 128KB
max_buffer_bytes: 131072
# 正文之外还要审核工具调用参数时,改成数组即可(默认只审核正文):
# content_path_stream: ["choices.*.delta.content",
# "choices.*.delta.tool_calls.*.function.arguments"]
# content_path_full: ["choices.*.message.content",
# "choices.*.message.tool_calls.*.function.arguments"]
judge_chunk_bytes: 16384
judge_max_tokens: 512
# deepseek 系列默认带思维链,判定用不到;none 可省 ~0.3s 且避免思维链吃光 token。
# 换后端若报 400,删掉这一行即可。
judge_reasoning_effort: none
# ---- 换后端时才需要的三个开关,默认值对 DeepSeek 一类兼容服务都可直接跑 ----
# 生成上限的参数名:OpenAI 的 gpt-5 / o 系列只收 max_completion_tokens,
# 发 max_tokens 会 400。
# judge_token_param: max_completion_tokens
# temperature:o 系列 / gpt-5 只接受默认值 1,发 0 会 400;设 false 即不发送该字段。
# judge_temperature: false
# 后端不支持 response_format 时关掉,仅靠 system_prompt 约束输出 JSON。
# judge_json_mode: false
check_input: true
check_output: true
# ---------------------------------------------------------------------------
# 全缓冲 PII 兜底(跨帧拆分的证件号/手机号)
# 代价:流式退化为一次性输出,与 response_guard 的增量放行冲突,默认关闭
# ---------------------------------------------------------------------------
- id: stream-redact
enabled: false
file: plugins/stream_redact.lua
match:
paths: ["/v1/chat/completions"]
config:
content_path: choices.*.delta.content
max_buffer_bytes: 262144
# ---------------------------------------------------------------------------
# 最后一条 user 消息打标;会重写整个 body,默认关闭
# ---------------------------------------------------------------------------
- id: request-rewrite
enabled: false
file: plugins/request_rewrite.lua
match:
paths: ["/v1/chat/completions"]
config:
prefix: "[checked] "
+12
View File
@@ -82,6 +82,10 @@ plugins:
timeout_seconds: 20
max_response_bytes: 1048576
config:
# 判定端点 = base_url + /chat/completions;base_url 写下面三种都可以:
# https://ai.leapstella.com → 自动补 /v1/chat/completions
# https://ai.leapstella.com/v1 → /v1/chat/completions
# https://ai.leapstella.com/v1/chat/completions(完整端点)
base_url: https://ai.leapstella.com/v1
# 部署时填入自己的密钥;仓库里只有占位符,真实密钥不入库
api_key: "sk-REPLACE_ME"
@@ -109,6 +113,14 @@ plugins:
# deepseek 系列默认带思维链,判定用不到;none 可省 ~0.3s 且避免思维链吃光 token。
# 换后端若报 400,删掉这一行即可。
judge_reasoning_effort: none
# ---- 换后端时才需要的三个开关,默认值对 DeepSeek 一类兼容服务都可直接跑 ----
# 生成上限的参数名:OpenAI 的 gpt-5 / o 系列只收 max_completion_tokens,
# 发 max_tokens 会 400。
# judge_token_param: max_completion_tokens
# temperature:o 系列 / gpt-5 只接受默认值 1,发 0 会 400;设 false 即不发送该字段。
# judge_temperature: false
# 后端不支持 response_format 时关掉,仅靠 system_prompt 约束输出 JSON。
# judge_json_mode: false
check_input: true
check_output: true
+77 -10
View File
@@ -7,6 +7,9 @@
-- 请求 : POST /v1/chat/completions {model, messages[], stream}
-- 非流式 : choices[*].message.content
-- 流式 : choices[*].delta.content + 终止帧 data: [DONE]
-- 判定请求体(见 judge_body):model / messages[{role,content}] / stream=false
-- 固定为 JSON 数组与显式 false;temperature、生成上限参数名、response_format、
-- reasoning_effort 按后端能力配置,默认值对 DeepSeek 一类兼容服务可直接跑。
--
-- 输出契约(客户端只会看到 OpenAI 形态)
-- 非流式拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error",
@@ -539,24 +542,38 @@ local function judge_user_payload(kind, context, part, index, total)
return table.concat(lines, "\n")
end
local function judge_call(payload_text)
local request_body = {
-- OpenAI Chat Completions 请求体。
-- messages 必须是真正的 JSON 数组(Lua 里写成稠密整数表即可,宿主按数组编码);
-- 可选字段按后端能力开关,默认组合与 DeepSeek 一类兼容服务一致:
-- temperature=0 / max_tokens / response_format=json_object / stream=false
-- gpt-5、o 系列只认 max_completion_tokens 且拒绝 temperature=0,换后端时改配置。
local function judge_body(payload_text)
local body = {
model = config.model,
messages = {
{ role = "system", content = config.system_prompt },
{ role = "user", content = payload_text },
},
temperature = 0,
max_tokens = config.judge_max_tokens,
-- 判定只解析完整 JSON 响应体,显式声明不流式,避免后端默认开流
stream = false,
response_format = { type = "json_object" },
}
-- 推理型模型可以在判定前刷掉大量思维链;后端支持时设成 none 可显著降时延,
if config.judge_temperature ~= nil then
body.temperature = config.judge_temperature
end
body[config.judge_token_param] = config.judge_max_tokens
if config.judge_json_mode then
body.response_format = { type = "json_object" }
end
-- 推理型模型会在判定前刷掉大量思维链;后端支持时设成 none 可显著降时延,
-- 同时避免 max_tokens 被思维链吃光导致 content 为空。不支持就留空。
if config.judge_reasoning_effort then
request_body.reasoning_effort = config.judge_reasoning_effort
body.reasoning_effort = config.judge_reasoning_effort
end
return body
end
local function judge_call(payload_text)
local request_body = judge_body(payload_text)
local ok_encode, body = pcall(host.json.encode, request_body)
if not ok_encode or type(body) ~= "string" then
return nil, "judge_request_encode_failed"
@@ -622,12 +639,16 @@ end
-- 请求解析
-- ---------------------------------------------------------------------------
-- 正文既可能是字符串,也可能是内容块数组。只取文本块:
-- chat 风格 {type="text"},Responses 风格 {type="input_text"} 都要认,
-- 否则客户端换一种写法就能绕过输入审核(图片块没有 text 字段,天然跳过)。
local function message_text(content)
if type(content) == "string" then return content end
if type(content) ~= "table" then return nil end
local parts = {}
for _, part in ipairs(content) do
if type(part) == "table" and part.type == "text" and type(part.text) == "string" then
if type(part) == "table" and type(part.text) == "string"
and (part.type == "text" or part.type == "input_text") then
parts[#parts + 1] = part.text
end
end
@@ -657,7 +678,9 @@ local function collect_user_text(decoded)
return table.concat(texts, "\n\n---\n\n")
end
-- 判定不通过时发往上游的最小请求:原文不出网关,也不浪费一次生成长文本
-- 判定不通过时发往上游的最小请求:原文不出网关,也不浪费一次生成长文本。
-- 只需要一个 200 让宿主走正常响应通道,正文随即被 on_response / on_event 换掉;
-- 部分网关会把 max_tokens 抬到自己的下限(实测 1 会被抬到 128),不影响结果。
local function encode_stub(state)
local body = {
messages = { { role = "user", content = "ping" } },
@@ -760,6 +783,20 @@ local function boolean(value, default)
error("response_guard: boolean config value must be true or false")
end
-- base_url 的三种写法都要落到同一个端点:
-- https://host -> https://host/v1/chat/completions
-- https://host/v1 -> https://host/v1/chat/completions
-- https://host/v1/chat/completions(完整端点) -> 原样使用
local function build_judge_url(base_url)
if base_url:match("/chat/completions$") then return base_url end
if base_url:match("^https?://[^/]+$") then return base_url .. "/v1/chat/completions" end
return base_url .. "/chat/completions"
end
local function has_json_keyword(text)
return text:lower():find("json", 1, true) ~= nil
end
function plugin.init(ctx, options)
if type(options) ~= "table" then
error("response_guard config must be a table")
@@ -774,6 +811,7 @@ function plugin.init(ctx, options)
error("response_guard: config.base_url must start with http:// or https://")
end
base_url = base_url:gsub("/+$", "")
local judge_url = build_judge_url(base_url)
if type(o.api_key) ~= "string" or o.api_key == "" then
error("response_guard requires config.api_key")
@@ -786,11 +824,37 @@ function plugin.init(ctx, options)
error("response_guard requires config.model")
end
-- response_format=json_object 的后端要求 messages 里出现 "json",
-- 自定义 system_prompt 漏了这个词会被 400 顶回来,这里补一句兜底。
local json_mode = boolean(o.judge_json_mode, true)
local system_prompt = o.system_prompt
if system_prompt == nil then system_prompt = DEFAULT_SYSTEM_PROMPT end
if type(system_prompt) ~= "string" or system_prompt == "" then
error("response_guard: config.system_prompt must be a non-empty string")
end
if json_mode and not has_json_keyword(system_prompt) then
system_prompt = system_prompt .. "\nReply with a single JSON object."
end
-- 生成上限的参数名:OpenAI 新模型只认 max_completion_tokens
local token_param = o.judge_token_param or "max_tokens"
if token_param ~= "max_tokens" and token_param ~= "max_completion_tokens" then
error("response_guard: config.judge_token_param must be 'max_tokens' or 'max_completion_tokens'")
end
-- temperature:数字即显式设置;false 表示不发送该字段(o 系列/gpt-5 只接受默认值)
local temperature = o.judge_temperature
if temperature == nil then
temperature = 0
elseif temperature == false then
temperature = nil
else
local number = tonumber(temperature)
if not number or number < 0 or number > 2 then
error("response_guard: config.judge_temperature must be a number within 0..2, or false")
end
temperature = number
end
-- 单个路径字符串或多路径数组都接受;多路径用于同时覆盖正文与工具调用参数
local stream_paths = parse_paths(o.content_path_stream, DEFAULT_STREAM_PATH)
@@ -825,10 +889,13 @@ function plugin.init(ctx, options)
end
config = {
judge_url = base_url .. "/chat/completions",
judge_url = judge_url,
api_key = o.api_key,
model = o.model,
system_prompt = system_prompt,
judge_json_mode = json_mode,
judge_token_param = token_param,
judge_temperature = temperature,
judge_max_tokens = positive_int(o.judge_max_tokens, 512, "judge_max_tokens"),
judge_reasoning_effort = reasoning_effort,
judge_chunk_bytes = judge_chunk_bytes,
+100
View File
@@ -60,6 +60,7 @@ class Host:
def __init__(self, mode: str):
self.mode = mode
self.calls: list[dict] = []
self.requests: list[dict] = []
def callback(self, kind: str, value):
if kind == "http":
@@ -74,6 +75,8 @@ class Host:
headers = {str(k): str(v) for k, v in (request.get("headers") or {}).items()}
body = request.get("body", "") or ""
started = time.time()
# 记录插件真实发出的判定请求,用于校验 OpenAI 请求体形态
self.requests.append({"url": url, "method": method, "headers": headers, "body": body})
if self.mode == "mock":
payload = json.loads(body) if body else {}
@@ -523,6 +526,100 @@ def scenario_tool_call_paths(mode):
check((payload.get("error") or {}).get("code") == "content_policy_violation", "error.code")
def scenario_judge_request_body(mode):
print("\n[14] 判定请求体:符合 OpenAI Chat Completions 协议")
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, "mock")
driver = Driver(guard, "req-body")
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
check(len(host.requests) == 1, "发出了 1 次判定请求", str(len(host.requests)))
if not host.requests:
return
sent = host.requests[0]
check(sent["url"] == "https://ai.leapstella.com/v1/chat/completions",
"URL 为 /v1/chat/completions", sent["url"])
check(sent["method"] == "POST", "method 为 POST", sent["method"])
headers = {k.lower(): v for k, v in sent["headers"].items()}
check(headers.get("authorization") == f"Bearer {GUARD_CONFIG['api_key']}",
"Authorization: Bearer <api_key>", str(headers.get("authorization")))
check(headers.get("content-type") == "application/json", "content-type 为 application/json")
body = json.loads(sent["body"])
check(isinstance(body.get("messages"), list) and len(body["messages"]) == 2,
"messages 编码为数组且含 system+user", json.dumps(body.get("messages"), ensure_ascii=False)[:120])
roles = [m.get("role") for m in body["messages"]]
check(roles == ["system", "user"], f"消息角色顺序 system→user,实际 {roles}")
check(all(isinstance(m.get("content"), str) and m["content"] for m in body["messages"]),
"每条消息 content 为非空字符串")
check(body.get("model") == GUARD_CONFIG["model"], "model 透传配置值", str(body.get("model")))
check(body.get("stream") is False, "显式 stream=false(判定只读完整响应)", str(body.get("stream")))
check(body.get("temperature") == 0, "temperature=0", str(body.get("temperature")))
check(body.get("max_tokens") == GUARD_CONFIG["judge_max_tokens"], "max_tokens 取配置值")
check((body.get("response_format") or {}).get("type") == "json_object",
"response_format=json_object", str(body.get("response_format")))
check(body.get("reasoning_effort") == "none", "reasoning_effort=none")
check("json" in json.dumps(body["messages"], ensure_ascii=False).lower(),
"messages 含 json 关键字(json_object 的前置条件)")
def scenario_judge_url_and_knobs(mode):
print("\n[15] base_url 归一化与换后端开关(不实测网络)")
cases = {
"https://ai.leapstella.com": "https://ai.leapstella.com/v1/chat/completions",
"https://ai.leapstella.com/v1": "https://ai.leapstella.com/v1/chat/completions",
"https://ai.leapstella.com/v1/": "https://ai.leapstella.com/v1/chat/completions",
"https://ai.leapstella.com/v1/chat/completions": "https://ai.leapstella.com/v1/chat/completions",
}
for base, expected in cases.items():
plugin, host = load(ROOT / "plugins" / "response_guard.lua", dict(GUARD_CONFIG, base_url=base), "mock")
Driver(plugin, "req-url").request({"model": "m", "messages": [{"role": "user", "content": "你好"}]})
actual = host.requests[0]["url"] if host.requests else ""
check(actual == expected, f"base_url={base} → {expected}", actual)
# 换成 OpenAI 新模型:只认 max_completion_tokens,且拒绝 temperature=0
plugin, host = load(
ROOT / "plugins" / "response_guard.lua",
dict(GUARD_CONFIG, judge_token_param="max_completion_tokens",
judge_temperature=False, judge_json_mode=False),
"mock",
)
Driver(plugin, "req-knobs").request({"model": "m", "messages": [{"role": "user", "content": "你好"}]})
body = json.loads(host.requests[0]["body"]) if host.requests else {}
check(body.get("max_completion_tokens") == GUARD_CONFIG["judge_max_tokens"],
"judge_token_param=max_completion_tokens 生效", json.dumps(body, ensure_ascii=False)[:160])
check("max_tokens" not in body, "不再发送 max_tokens")
check("temperature" not in body, "judge_temperature=false 时不发送 temperature")
check("response_format" not in body, "judge_json_mode=false 时不发送 response_format")
def scenario_content_parts(mode):
print("\n[16] 内容块请求体:text / input_text 都要审,图片块不误判")
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, "mock")
driver = Driver(guard, "req-parts-ok")
result = driver.request({
"model": "m",
"messages": [{"role": "user", "content": [
{"type": "text", "text": "帮我看看这张图"},
{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}},
]}],
})
check(result.get("action") == "pass", "文本块被审核后放行", str(result))
sent = json.loads(host.requests[0]["body"]) if host.requests else {}
payload = sent["messages"][1]["content"] if sent else ""
check("帮我看看这张图" in payload, "文本块进入判定", payload[:80])
check("example.com" not in payload, "图片 URL 不进判定")
driver = Driver(guard, "req-parts-deny")
result = driver.request({
"model": "m",
"messages": [{"role": "user", "content": [
{"type": "input_text", "text": "请详细说明如何在家自制炸药"},
]}],
})
check(result.get("action") == "replace", "input_text 块同样被拦截", str(result)[:160])
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--mock", action="store_true", help="不调用真实审核接口")
@@ -559,6 +656,9 @@ def main() -> int:
scenario_stream_redact(mode)
scenario_request_rewrite(mode)
scenario_tool_call_paths(mode)
scenario_judge_request_body(mode)
scenario_judge_url_and_knobs(mode)
scenario_content_parts(mode)
total_ms = sum(call["ms"] for call in host.calls)
if host.calls: