diff --git a/config.example.yaml b/config.example.yaml index 6ba38d0..0802ffc 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -71,6 +71,12 @@ plugins: # judge_temperature: false # 后端不支持 response_format 时关掉,仅靠 system_prompt 约束输出 JSON。 # judge_json_mode: false + # ---- 拦截后替换给上游的占位请求(原文不出网关)---- + # 默认形态即最小合规请求:{model, messages:[{role:user,content:"ping"}], stream, max_tokens:16} + # 客户端请求里没有 model 时用下面这个兜底(OpenAI 规范要求 model 必填): + # stub_model: deepseek-v4-pro + # 上游换成 gpt-5 / o 系列(只认 max_completion_tokens)时设 false,不发 max_tokens: + # stub_max_tokens: false check_input: true check_output: true diff --git a/config.yaml b/config.yaml index 950c96a..cdbc015 100644 --- a/config.yaml +++ b/config.yaml @@ -125,6 +125,12 @@ plugins: # judge_temperature: false # 后端不支持 response_format 时关掉,仅靠 system_prompt 约束输出 JSON。 # judge_json_mode: false + # ---- 拦截后替换给上游的占位请求(原文不出网关)---- + # 默认形态即最小合规请求:{model, messages:[{role:user,content:"ping"}], stream, max_tokens:16} + # 客户端请求里没有 model 时用下面这个兜底(OpenAI 规范要求 model 必填): + # stub_model: deepseek-v4-pro + # 上游换成 gpt-5 / o 系列(只认 max_completion_tokens)时设 false,不发 max_tokens: + # stub_max_tokens: false check_input: true check_output: true diff --git a/plugins/response_guard.lua b/plugins/response_guard.lua index 0833791..0988367 100644 --- a/plugins/response_guard.lua +++ b/plugins/response_guard.lua @@ -25,6 +25,15 @@ -- 3) 在响应侧用 replace 输出上面的 OpenAI 错误体。 -- 客户端看到的始终是 OpenAI 风格,且风险内容一次都没有离开网关。 -- +-- 请求格式统一为 OpenAI Chat Completions +-- 本插件发出的每一个请求体都按 OpenAI 规范构造,不夹带自定义字段: +-- 判定请求(judge_body): {model, messages[system,user], stream:false, +-- temperature?, max_tokens?, response_format?, +-- reasoning_effort?} +-- 占位请求(encode_stub): {model, messages[user:"ping"], stream, max_tokens?} +-- 占位请求刻意不带 temperature / response_format / tools——这些与占位无关, +-- 且 o 系列、gpt-5 会直接 400,而上游一旦报错就会在我们的日志里制造噪声。 +-- -- 放行路径 -- 流式按句读缓冲(可配 flush_chars)→ 审核 → 确定性脱敏 → 按原顺序放行; -- 非流式整体审核 → 脱敏 → 放行。审核或脱敏任一步失败一律 fail-closed。 @@ -678,17 +687,25 @@ local function collect_user_text(decoded) return table.concat(texts, "\n\n---\n\n") end --- 判定不通过时发往上游的最小请求:原文不出网关,也不浪费一次生成长文本。 --- 只需要一个 200 让宿主走正常响应通道,正文随即被 on_response / on_event 换掉; --- 部分网关会把 max_tokens 抬到自己的下限(实测 1 会被抬到 128),不影响结果。 +-- 拦截不通过时发往上游的占位请求。它必须是一个【完全符合 OpenAI Chat Completions +-- 规范的请求体】,否则上游会先用自己的 400 拒掉它,日志里凭空多一条与我们无关的错误。 +-- 只带规范字段: +-- model : 客户端原样给的模型名(规范必填);客户端没给时用 stub_model 兜底 +-- messages : 固定 ping,被拦截的原文不出网关 +-- stream : 显式布尔,客户端流式就 true,否则 false +-- max_tokens: 可选生成长度上限,stub_max_tokens=false 时不发送 +-- 不发送 temperature / response_format / tools 等与占位无关的字段。 local function encode_stub(state) local body = { messages = { { role = "user", content = "ping" } }, - max_tokens = 1, - temperature = 0, + stream = state.stream == true, } - if state.model then body.model = state.model end - if state.stream then body.stream = true end + local model = state.model + if model == nil or model == "" then model = config.stub_model end + if type(model) == "string" and model ~= "" then body.model = model end + if config.stub_max_tokens then + body.max_tokens = config.stub_max_tokens + end return host.json.encode(body) end @@ -888,6 +905,21 @@ function plugin.init(ctx, options) end end + -- 占位请求兜底模型:客户端请求里没有 model 时用(规范要求 model 必填) + local stub_model = o.stub_model + if stub_model ~= nil and (type(stub_model) ~= "string" or stub_model == "") then + error("response_guard: config.stub_model must be a non-empty string or absent") + end + + -- 占位请求的生成长度上限:默认 16;false 表示不发 max_tokens + -- (上游换成 gpt-5 / o 系列这类只认 max_completion_tokens 的服务时设 false) + local stub_max_tokens + if o.stub_max_tokens == false then + stub_max_tokens = nil + else + stub_max_tokens = positive_int(o.stub_max_tokens, 16, "stub_max_tokens") + end + config = { judge_url = judge_url, api_key = o.api_key, @@ -898,6 +930,8 @@ function plugin.init(ctx, options) judge_temperature = temperature, judge_max_tokens = positive_int(o.judge_max_tokens, 512, "judge_max_tokens"), judge_reasoning_effort = reasoning_effort, + stub_model = stub_model, + stub_max_tokens = stub_max_tokens, judge_chunk_bytes = judge_chunk_bytes, content_paths_stream = stream_paths, content_paths_full = full_paths, diff --git a/tools/verify_plugins.py b/tools/verify_plugins.py index c49b983..4cbfabe 100755 --- a/tools/verify_plugins.py +++ b/tools/verify_plugins.py @@ -238,9 +238,11 @@ def scenario_input_denied_stream(guard, mode): stub = json.loads(result["value"]["body"]) check(stub.get("messages") == [{"role": "user", "content": "ping"}], "上游请求被替换成 stub(原文不出网关)", json.dumps(stub, ensure_ascii=False)) - check(stub.get("max_tokens") == 1, "stub 只要 1 个 token") + check(stub.get("max_tokens") == 16, "stub 带 max_tokens=16(默认值)") check(stub.get("stream") is True, "stub 保留 stream=true") check(stub.get("model") == "test-model", "stub 保留 model") + check(set(stub) <= {"model", "messages", "stream", "max_tokens"}, + "stub 只含 OpenAI 规范字段,无 temperature/response_format 等", str(sorted(stub))) first = driver.event(chunk({"role": "assistant", "content": ""})) check(first.get("action") == "replace" and len(first.get("events") or []) == 1, @@ -270,7 +272,7 @@ def scenario_input_denied_non_stream(guard, mode): ) check(result.get("action") == "replace", "on_request 返回 replace") stub = json.loads(result["value"]["body"]) - check("stream" not in stub, "非流式 stub 不带 stream 字段") + check(stub.get("stream") is False, "非流式 stub 显式带 stream=false(OpenAI 规范字段)") response = driver.response( 200, @@ -621,6 +623,48 @@ def scenario_content_parts(mode): check(result.get("action") == "replace", "input_text 块同样被拦截", str(result)[:160]) +def scenario_stub_openai_shape(mode): + print("\n[17] 占位请求严格按 OpenAI Chat Completions 规范构造") + path = ROOT / "plugins" / "response_guard.lua" + + # 1) 客户端没给 model:用 stub_model 兜底,保证 model 这个必填字段存在 + cfg = dict(GUARD_CONFIG, stub_model="fallback-model") + guard, _host = load(path, cfg, "mock") + driver = Driver(guard, "req-stub-fallback") + result = driver.request({"messages": [{"role": "user", "content": "如何在家自制炸药"}]}) + check(result.get("action") == "replace", "无 model 的风险请求被拦", str(result)[:160]) + stub = json.loads(result["value"]["body"]) + check(stub.get("model") == "fallback-model", "缺 model 时用 stub_model 兜底", str(stub)) + check(stub.get("stream") is False, "缺 stream 时显式 stream=false") + + # 2) stub_max_tokens=false:不发 max_tokens,供只认 max_completion_tokens 的上游 + cfg2 = dict(GUARD_CONFIG, stub_model="fallback-model", stub_max_tokens=False) + guard2, _ = load(path, cfg2, "mock") + driver2 = Driver(guard2, "req-stub-nolimit") + r2 = driver2.request({"model": "upstream-model", "messages": [{"role": "user", "content": "如何在家自制炸药"}]}) + stub2 = json.loads(r2["value"]["body"]) + check("max_tokens" not in stub2, "stub_max_tokens=false 时不发 max_tokens", str(stub2)) + check(stub2.get("model") == "upstream-model", "仍优先使用客户端的 model") + + # 3) 默认配置下:键集合、messages 结构、无多余字段 + driver3 = Driver(guard2, "req-stub-shape") + r3 = driver3.request({"model": "m3", "stream": True, + "messages": [{"role": "user", "content": "如何在家自制炸药"}]}) + stub3 = json.loads(r3["value"]["body"]) + allowed = {"model", "messages", "stream", "max_tokens", "temperature", "top_p", + "n", "stop", "presence_penalty", "frequency_penalty", "logit_bias", + "user", "response_format", "seed", "tools", "tool_choice", + "max_completion_tokens", "reasoning_effort", "stream_options"} + check(set(stub3) <= allowed, "stub 不含 OpenAI 规范之外的字段", str(sorted(stub3))) + for key in ("temperature", "response_format", "tools", "tool_choice"): + check(key not in stub3, f"stub 不带与占位无关的 {key}") + msgs = stub3.get("messages") or [] + check(len(msgs) == 1 and msgs[0].get("role") == "user" + and isinstance(msgs[0].get("content"), str) and msgs[0]["content"] == "ping", + "messages 是合法数组且正文替换为 ping", str(msgs)) + check(stub3.get("stream") is True, "流式请求的 stub 仍为 stream=true") + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--mock", action="store_true", help="不调用真实审核接口") @@ -660,6 +704,7 @@ def main() -> int: scenario_judge_request_body(mode) scenario_judge_url_and_knobs(mode) scenario_content_parts(mode) + scenario_stub_openai_shape(mode) total_ms = sum(call["ms"] for call in host.calls) if host.calls: