插件改造:输出改为 OpenAI 协议,审核改走远程接口
response_guard.lua 重写:按 OpenAI 协议定位内容(choices[*].delta.content / message.content,支持多路径覆盖 tool_calls.arguments),判定改走远程 /chat/completions,拦截输出 400 content_policy_violation,审核不可用输出 503 safety_review_unavailable。 stream_redact.lua 改为 OpenAI SSE 全缓冲 PII 兜底,默认关闭;request_rewrite.lua 改为只重写最后一条 user 消息,默认关闭。 config.yaml 接口路径改为 /v1/chat/completions,停用缺模型文件的 guard_model 段与依赖 host.files 的 /upload 插件段,hook_timeout 调到 45s。 新增 tools/verify_plugins.py:13 个场景 57 项断言的契约校验。
This commit is contained in:
1 parent
e1f944f16d
commit
9218bdf1e8
6 files changed
+1967
-1288
No files matched your search
Executable
+566
@@ -0,0 +1,566 @@
|
||||
#!/usr/bin/env python3
|
||||
"""用宿主的真实 Lua 契约驱动插件,验证 OpenAI 形态的输出。
|
||||
|
||||
python tools/verify_plugins.py # 全部场景(会真实调用审核接口)
|
||||
python tools/verify_plugins.py --mock # 审核接口全部放行,只验协议形态
|
||||
|
||||
宿主契约来自 lua/worker.py(host.json / host.http / host.log),
|
||||
网络调用真的打出去,因此能同时验证 URL、鉴权头、请求体与响应解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from lua.worker import LuaPlugin # noqa: E402
|
||||
|
||||
LIMITS = {
|
||||
"lua_memory_bytes": 268435456,
|
||||
"ipc_bytes": 32 * 1024 * 1024,
|
||||
"max_plugin_buffer_bytes": 320 * 1024,
|
||||
}
|
||||
|
||||
FAILURES: list[str] = []
|
||||
CHECKS = 0
|
||||
|
||||
|
||||
def check(condition: bool, label: str, detail: str = "") -> None:
|
||||
global CHECKS
|
||||
CHECKS += 1
|
||||
if condition:
|
||||
print(f" PASS {label}")
|
||||
else:
|
||||
print(f" FAIL {label}{(' -> ' + detail) if detail else ''}")
|
||||
FAILURES.append(label)
|
||||
|
||||
|
||||
class Host:
|
||||
"""最小宿主实现,签名与 runtime.py 调用插件时一致。"""
|
||||
|
||||
def __init__(self, mode: str):
|
||||
self.mode = mode
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def callback(self, kind: str, value):
|
||||
if kind == "http":
|
||||
return self.http(value)
|
||||
if kind == "log":
|
||||
return None
|
||||
raise RuntimeError(f"unexpected capability: {kind}")
|
||||
|
||||
def http(self, request: dict) -> dict:
|
||||
url = request.get("url", "")
|
||||
method = request.get("method", "GET")
|
||||
headers = {str(k): str(v) for k, v in (request.get("headers") or {}).items()}
|
||||
body = request.get("body", "") or ""
|
||||
started = time.time()
|
||||
|
||||
if self.mode == "mock":
|
||||
payload = json.loads(body) if body else {}
|
||||
joined = json.dumps(payload, ensure_ascii=False)
|
||||
unsafe = any(word in joined for word in ("炸药", "雷管", "硝酸铵"))
|
||||
verdict = {"allow": False, "category": "weapons"} if unsafe else {"allow": True}
|
||||
time.sleep(0.01)
|
||||
return {
|
||||
"status": 200,
|
||||
"headers": {"content-type": "application/json"},
|
||||
"body": json.dumps(
|
||||
{
|
||||
"id": "chatcmpl-mock",
|
||||
"object": "chat.completion",
|
||||
"model": payload.get("model", "mock"),
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": json.dumps(verdict, ensure_ascii=False),
|
||||
},
|
||||
"finish_reason": "stop",
|
||||
}
|
||||
],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
|
||||
data = body.encode("utf-8") if method not in ("GET", "HEAD") else None
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
status, text = 0, ""
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=40) as resp:
|
||||
status, text = resp.status, resp.read().decode("utf-8", "replace")
|
||||
except urllib.error.HTTPError as exc:
|
||||
status, text = exc.code, exc.read().decode("utf-8", "replace")
|
||||
except Exception as exc: # 网络不可达
|
||||
status, text = 0, str(exc)
|
||||
self.calls.append({"url": url, "status": status, "ms": int((time.time() - started) * 1000)})
|
||||
return {
|
||||
"status": status,
|
||||
"headers": {"content-type": "application/json"},
|
||||
"body": text,
|
||||
}
|
||||
|
||||
|
||||
class Driver:
|
||||
def __init__(self, plugin: LuaPlugin, request_id: str):
|
||||
self.plugin = plugin
|
||||
self.request_id = request_id
|
||||
|
||||
@property
|
||||
def ctx(self) -> dict:
|
||||
return {"request_id": self.request_id}
|
||||
|
||||
def request(self, payload, raw: str | None = None):
|
||||
body = raw if raw is not None else json.dumps(payload, ensure_ascii=False)
|
||||
return self.plugin.invoke(
|
||||
"on_request",
|
||||
self.ctx,
|
||||
{
|
||||
"method": "POST",
|
||||
"path": "/v1/chat/completions",
|
||||
"headers": {"content-type": "application/json"},
|
||||
"body": body,
|
||||
},
|
||||
)
|
||||
|
||||
def event(self, data):
|
||||
if isinstance(data, str):
|
||||
value = {"has_data": True, "data": data}
|
||||
else:
|
||||
value = {"has_data": True, "data": json.dumps(data, ensure_ascii=False)}
|
||||
return self.plugin.invoke("on_event", self.ctx, value)
|
||||
|
||||
def response(self, status: int, payload):
|
||||
body = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False)
|
||||
return self.plugin.invoke(
|
||||
"on_response",
|
||||
self.ctx,
|
||||
{
|
||||
"status": status,
|
||||
"headers": {"content-type": "application/json"},
|
||||
"body": body,
|
||||
"streaming": False,
|
||||
},
|
||||
)
|
||||
|
||||
def end(self):
|
||||
return self.plugin.invoke("on_end", self.ctx, None)
|
||||
|
||||
|
||||
def load(path: pathlib.Path, config: dict, mode: str):
|
||||
host = Host(mode)
|
||||
plugin = LuaPlugin(path.read_text(encoding="utf-8"), LIMITS, host.callback)
|
||||
plugin.invoke("init", {"request_id": "init", "plugin_id": "test"}, config)
|
||||
return plugin, host
|
||||
|
||||
|
||||
def chunk(delta: dict, finish=None, cid: str = "chatcmpl-1") -> dict:
|
||||
return {
|
||||
"id": cid,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": 1,
|
||||
"model": "test-model",
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
|
||||
}
|
||||
|
||||
|
||||
def released_text(events: list[dict], key: str = "delta") -> str:
|
||||
parts = []
|
||||
for event in events:
|
||||
data = event.get("data")
|
||||
if not data or data == "[DONE]":
|
||||
continue
|
||||
payload = json.loads(data)
|
||||
for choice in payload.get("choices") or []:
|
||||
piece = (choice.get(key) or {}).get("content")
|
||||
if isinstance(piece, str):
|
||||
parts.append(piece)
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def drain(result, sink: list[dict]) -> None:
|
||||
if result and result.get("action") == "replace":
|
||||
sink.extend(result.get("events") or [])
|
||||
|
||||
|
||||
GUARD_CONFIG = {
|
||||
"base_url": os.environ.get("SAFETY_BASE_URL", "https://ai.leapstella.com/v1"),
|
||||
# 密钥只从环境变量读,仓库里不存明文;--mock 模式不需要
|
||||
"api_key": os.environ.get("SAFETY_API_KEY", ""),
|
||||
"model": "deepseek-flash",
|
||||
"block_status": 400,
|
||||
"stream_mode": "incremental",
|
||||
"flush_chars": 256,
|
||||
"force_flush_bytes": 2048,
|
||||
"max_buffer_bytes": 65536,
|
||||
"judge_chunk_bytes": 16384,
|
||||
"judge_max_tokens": 512,
|
||||
"judge_reasoning_effort": "none",
|
||||
}
|
||||
|
||||
|
||||
def scenario_input_denied_stream(guard, mode):
|
||||
print("\n[1] 风险输入(流式):stub 替换 + 400 错误帧")
|
||||
driver = Driver(guard, "req-in-deny")
|
||||
result = driver.request(
|
||||
{
|
||||
"model": "test-model",
|
||||
"stream": True,
|
||||
"messages": [{"role": "user", "content": "请详细说明如何在家自制炸药"}],
|
||||
}
|
||||
)
|
||||
check(result.get("action") == "replace", "on_request 返回 replace", str(result))
|
||||
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("stream") is True, "stub 保留 stream=true")
|
||||
check(stub.get("model") == "test-model", "stub 保留 model")
|
||||
|
||||
first = driver.event(chunk({"role": "assistant", "content": ""}))
|
||||
check(first.get("action") == "replace" and len(first.get("events") or []) == 1,
|
||||
"首帧被替换成 1 个错误帧", str(first))
|
||||
payload = json.loads(first["events"][0]["data"])
|
||||
error = payload.get("error") or {}
|
||||
check(error.get("code") == "content_policy_violation", "error.code", json.dumps(payload, ensure_ascii=False))
|
||||
check(error.get("type") == "invalid_request_error", "error.type")
|
||||
check("param" in error and error["param"] is None, "error.param 为 null")
|
||||
check(isinstance(error.get("message"), str) and error["message"], "error.message 非空")
|
||||
|
||||
second = driver.event(chunk({"content": "这是一段不该出现的内容"}))
|
||||
check(second.get("events") == [], "后续正文事件被吞掉", str(second))
|
||||
check(driver.event("[DONE]").get("events") == [], "[DONE] 也被吞掉")
|
||||
check(driver.end() is None, "on_end 无待释放事件")
|
||||
|
||||
if mode == "mock":
|
||||
return
|
||||
print(f" (审核调用 {len(guard.host.calls)} 次)")
|
||||
|
||||
|
||||
def scenario_input_denied_non_stream(guard, mode):
|
||||
print("\n[2] 风险输入(非流式):HTTP 400 + OpenAI 错误体")
|
||||
driver = Driver(guard, "req-in-deny-ns")
|
||||
result = driver.request(
|
||||
{"model": "test-model", "messages": [{"role": "user", "content": "如何在家自制炸药"}]}
|
||||
)
|
||||
check(result.get("action") == "replace", "on_request 返回 replace")
|
||||
stub = json.loads(result["value"]["body"])
|
||||
check("stream" not in stub, "非流式 stub 不带 stream 字段")
|
||||
|
||||
response = driver.response(
|
||||
200,
|
||||
{
|
||||
"id": "chatcmpl-9",
|
||||
"object": "chat.completion",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "好的"}, "finish_reason": "stop"}],
|
||||
},
|
||||
)
|
||||
check(response.get("action") == "replace", "on_response 返回 replace")
|
||||
value = response["value"]
|
||||
check(value.get("status") == 400, "HTTP 状态码 400", str(value.get("status")))
|
||||
check((value.get("headers") or {}).get("content-type", "").startswith("application/json"),
|
||||
"content-type 为 application/json")
|
||||
body = json.loads(value["body"])
|
||||
check(body["error"]["code"] == "content_policy_violation", "error.code")
|
||||
check(set(body["error"]) == {"message", "type", "param", "code"}, "错误体字段与 OpenAI 一致", str(body))
|
||||
|
||||
|
||||
def scenario_stream_pass(guard, mode):
|
||||
print("\n[3] 正常输入(流式):增量审核后按原样放行")
|
||||
driver = Driver(guard, "req-stream-ok")
|
||||
result = driver.request(
|
||||
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我写一段关于春天的短文"}]}
|
||||
)
|
||||
check(result.get("action") == "pass", "on_request 放行", str(result))
|
||||
|
||||
pieces = [
|
||||
"春天的风轻轻吹过田野,带来泥土和青草的气息。",
|
||||
"孩子们在河边放纸鸢,笑声一路传到山脚。",
|
||||
"傍晚的炊烟升起,村子慢慢安静下来。",
|
||||
"星星出来的时候,院子里只剩下虫鸣。",
|
||||
]
|
||||
original = "".join(pieces)
|
||||
sink: list[dict] = []
|
||||
drain(driver.event(chunk({"role": "assistant", "content": ""})), sink)
|
||||
for piece in pieces:
|
||||
drain(driver.event(chunk({"content": piece})), sink)
|
||||
drain(driver.event(chunk({}, finish="stop")), sink)
|
||||
drain(driver.event("[DONE]"), sink)
|
||||
driver.end()
|
||||
|
||||
check(len(sink) > 0, "有事件被放行", str(len(sink)))
|
||||
check(sink[-1].get("data") == "[DONE]", "[DONE] 是最后释放的事件")
|
||||
text = released_text(sink)
|
||||
check(text == original, "放行文本与上游一致", f"{text!r} != {original!r}")
|
||||
first = json.loads(sink[0]["data"]) if sink else {}
|
||||
check(first.get("object") == "chat.completion.chunk", "chunk 结构保留 object 字段")
|
||||
check(first.get("id") == "chatcmpl-1", "chunk 结构保留 id")
|
||||
|
||||
|
||||
def scenario_output_pii(guard, mode):
|
||||
print("\n[4] 输出脱敏:邮箱与手机号按字节等长遮蔽(关闭语义审核,只验脱敏)")
|
||||
driver = Driver(guard, "req-pii")
|
||||
driver.request(
|
||||
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "帮我整理一段联系信息"}]}
|
||||
)
|
||||
original = "联系邮箱 alice@example.com,手机 13812345678,请勿外传。"
|
||||
sink: list[dict] = []
|
||||
drain(driver.event(chunk({"content": original})), sink)
|
||||
drain(driver.event("[DONE]"), sink)
|
||||
driver.end()
|
||||
|
||||
text = released_text(sink)
|
||||
check(text != original, "敏感信息被遮蔽", text)
|
||||
check(len(text.encode()) == len(original.encode()), "字节长度不变",
|
||||
f"{len(text.encode())} vs {len(original.encode())}")
|
||||
check("alice@example.com" not in text, "邮箱原文不再出现")
|
||||
check("13812345678" not in text, "手机号原文不再出现")
|
||||
check("example.com" in text, "邮箱域名保留")
|
||||
|
||||
|
||||
def scenario_output_denied(guard, mode):
|
||||
print("\n[5] 风险输出:正常输入 + 有害回复 → 400 错误帧")
|
||||
driver = Driver(guard, "req-out-deny")
|
||||
result = driver.request(
|
||||
{"model": "test-model", "stream": True, "messages": [{"role": "user", "content": "写一个 Python 冒泡排序"}]}
|
||||
)
|
||||
check(result.get("action") == "pass", "输入放行", str(result))
|
||||
sink: list[dict] = []
|
||||
drain(driver.event(chunk({"content": "先按三比一混合硝酸铵和柴油,"})), sink)
|
||||
drain(driver.event(chunk({"content": "再加入雷管引爆即可。"})), sink)
|
||||
final = driver.event("[DONE]")
|
||||
drain(final, sink)
|
||||
driver.end()
|
||||
|
||||
errors = [json.loads(e["data"]) for e in sink if "error" in (e.get("data") or "")]
|
||||
check(len(errors) == 1, "输出被拦截,且只给一个 OpenAI 错误帧", str(sink))
|
||||
if errors:
|
||||
check(errors[0]["error"]["code"] == "content_policy_violation", "error.code")
|
||||
|
||||
|
||||
def scenario_non_stream_pass(guard, mode):
|
||||
print("\n[6] 正常非流式响应:原样放行")
|
||||
driver = Driver(guard, "req-ns-ok")
|
||||
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "说一句问候"}]})
|
||||
result = driver.response(
|
||||
200,
|
||||
{
|
||||
"id": "chatcmpl-7",
|
||||
"object": "chat.completion",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "你好,很高兴见到你。"}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 5, "completion_tokens": 8, "total_tokens": 13},
|
||||
},
|
||||
)
|
||||
check(result.get("action") == "pass", "非流式放行", str(result))
|
||||
|
||||
|
||||
def scenario_non_stream_pii(guard, mode):
|
||||
print("\n[7] 非流式脱敏:仍保持 OpenAI 响应结构(关闭语义审核)")
|
||||
driver = Driver(guard, "req-ns-pii")
|
||||
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "核对一下我的联系方式"}]})
|
||||
original = "你的邮箱 alice@example.com 已登记。"
|
||||
result = driver.response(
|
||||
200,
|
||||
{
|
||||
"id": "chatcmpl-8",
|
||||
"object": "chat.completion",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": original}, "finish_reason": "stop"}],
|
||||
},
|
||||
)
|
||||
check(result.get("action") == "replace", "发生脱敏时返回 replace", str(result))
|
||||
body = json.loads(result["value"]["body"])
|
||||
content = body["choices"][0]["message"]["content"]
|
||||
check(content != original, "正文被遮蔽", content)
|
||||
check(len(content.encode()) == len(original.encode()), "字节长度不变")
|
||||
check(body.get("id") == "chatcmpl-8" and body.get("object") == "chat.completion", "响应外层结构保留")
|
||||
|
||||
|
||||
def scenario_upstream_error(guard, mode):
|
||||
print("\n[8] 上游自身报错:不包装,直接透传")
|
||||
driver = Driver(guard, "req-upstream-err")
|
||||
driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
|
||||
result = driver.response(400, {"error": {"message": "bad request", "type": "invalid_request_error", "param": None, "code": None}})
|
||||
check(result.get("action") == "pass", "非 200 直接放行", str(result))
|
||||
|
||||
|
||||
def scenario_opaque_request(guard, mode):
|
||||
print("\n[9] 非法 JSON 请求:交给上游按 OpenAI 规范拒绝")
|
||||
driver = Driver(guard, "req-opaque")
|
||||
result = driver.request(None, raw="{not json")
|
||||
check(result.get("action") == "pass", "非法 JSON 放行", str(result))
|
||||
response = driver.response(400, {"error": {"message": "invalid json", "type": "invalid_request_error", "param": None, "code": None}})
|
||||
check(response.get("action") == "pass", "上游错误原样返回")
|
||||
|
||||
|
||||
def scenario_judge_down(mode):
|
||||
print("\n[10] 审核服务不可达:503 + server_error(fail-closed)")
|
||||
guard, host = load(
|
||||
ROOT / "plugins" / "response_guard.lua",
|
||||
dict(GUARD_CONFIG, base_url="https://judge.invalid/v1"),
|
||||
"real",
|
||||
)
|
||||
driver = Driver(guard, "req-judge-down")
|
||||
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
|
||||
check(result.get("action") == "replace", "请求被换成 stub", str(result))
|
||||
response = driver.response(200, {"id": "x", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "你好"}, "finish_reason": "stop"}]})
|
||||
check(response.get("action") == "replace", "响应被替换")
|
||||
value = response.get("value") or {}
|
||||
check(value.get("status") == 503, "503", str(value.get("status")))
|
||||
body = json.loads(value.get("body") or "{}")
|
||||
check((body.get("error") or {}).get("code") == "safety_review_unavailable", "error.code", str(body))
|
||||
check((body.get("error") or {}).get("type") == "server_error", "error.type")
|
||||
|
||||
|
||||
def scenario_stream_redact(mode):
|
||||
print("\n[11] stream_redact:跨帧身份证号整体遮蔽")
|
||||
redactor, _ = load(
|
||||
ROOT / "plugins" / "stream_redact.lua",
|
||||
{"content_path": "choices.*.delta.content", "max_buffer_bytes": 262144},
|
||||
"mock",
|
||||
)
|
||||
driver = Driver(redactor, "req-redact")
|
||||
sink: list[dict] = []
|
||||
drain(driver.event(chunk({"role": "assistant", "content": ""})), sink)
|
||||
drain(driver.event(chunk({"content": "身份证号 110105"})), sink)
|
||||
drain(driver.event(chunk({"content": "19491231002X 已登记。"})), sink)
|
||||
drain(driver.event("[DONE]"), sink)
|
||||
driver.end()
|
||||
|
||||
text = released_text(sink)
|
||||
check("11010519491231002X" not in text, "身份证号原文不再出现", text)
|
||||
check("已登记。" in text, "其余正文保留")
|
||||
check(len(text.encode()) == len("身份证号 11010519491231002X 已登记。".encode()), "字节长度不变")
|
||||
|
||||
|
||||
def scenario_request_rewrite(mode):
|
||||
print("\n[12] request_rewrite:只改最后一条 user 消息")
|
||||
rewriter, _ = load(ROOT / "plugins" / "request_rewrite.lua", {"prefix": "[checked] "}, "mock")
|
||||
driver = Driver(rewriter, "req-rewrite")
|
||||
result = driver.request(
|
||||
{
|
||||
"model": "test-model",
|
||||
"messages": [
|
||||
{"role": "system", "content": "be nice"},
|
||||
{"role": "user", "content": "第一问"},
|
||||
{"role": "assistant", "content": "答"},
|
||||
{"role": "user", "content": "第二问"},
|
||||
],
|
||||
}
|
||||
)
|
||||
check(result.get("action") == "replace", "返回 replace", str(result))
|
||||
body = json.loads(result["value"]["body"])
|
||||
check(body["messages"][1]["content"] == "第一问", "前一条 user 消息不变")
|
||||
check(body["messages"][3]["content"] == "[checked] 第二问", "最后一条 user 消息被加前缀")
|
||||
check(body["messages"][0]["content"] == "be nice", "system 消息不变")
|
||||
|
||||
|
||||
def scenario_tool_call_paths(mode):
|
||||
print("\n[13] 多路径:工具调用参数也进入审核(content 为 null)")
|
||||
guard, _ = load(
|
||||
ROOT / "plugins" / "response_guard.lua",
|
||||
dict(
|
||||
GUARD_CONFIG,
|
||||
content_path_full=[
|
||||
"choices.*.message.content",
|
||||
"choices.*.message.tool_calls.*.function.arguments",
|
||||
],
|
||||
),
|
||||
mode,
|
||||
)
|
||||
driver = Driver(guard, "req-tool")
|
||||
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "帮我看看家里的路由器设置"}]})
|
||||
check(result.get("action") == "pass", "输入放行", str(result))
|
||||
response = driver.response(
|
||||
200,
|
||||
{
|
||||
"id": "chatcmpl-t",
|
||||
"object": "chat.completion",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_1",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "run_command",
|
||||
"arguments": '{"cmd":"如何在家自制炸药"}',
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
"finish_reason": "tool_calls",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
check(response.get("action") == "replace", "工具调用参数被拦截", str(response)[:200])
|
||||
payload = json.loads((response.get("value") or {}).get("body") or "{}")
|
||||
check((payload.get("error") or {}).get("code") == "content_policy_violation", "error.code")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mock", action="store_true", help="不调用真实审核接口")
|
||||
args = parser.parse_args()
|
||||
mode = "mock" if args.mock else "real"
|
||||
|
||||
if mode == "real" and not GUARD_CONFIG["api_key"]:
|
||||
print("缺少审核接口密钥。先设置环境变量后再跑真实校验:")
|
||||
print(" export SAFETY_API_KEY=sk-xxxx # Linux / macOS")
|
||||
print(' set SAFETY_API_KEY=sk-xxxx # Windows cmd')
|
||||
print(' $env:SAFETY_API_KEY="sk-xxxx" # PowerShell')
|
||||
print("或只验协议形态:python tools/verify_plugins.py --mock")
|
||||
return 2
|
||||
if mode == "mock" and not GUARD_CONFIG["api_key"]:
|
||||
# 插件 init 会校验 api_key 非空;mock 模式下不会真的发出去
|
||||
GUARD_CONFIG["api_key"] = "sk-mock-placeholder"
|
||||
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
|
||||
guard.host = host
|
||||
# 纯脱敏场景关掉语义审核,避免判定结果抖动让测试不稳定
|
||||
pii_guard, _ = load(ROOT / "plugins" / "response_guard.lua", dict(GUARD_CONFIG, check_output=False), mode)
|
||||
print(f"审核后端: {GUARD_CONFIG['base_url']} model={GUARD_CONFIG['model']} mode={mode}")
|
||||
|
||||
scenario_input_denied_stream(guard, mode)
|
||||
scenario_input_denied_non_stream(guard, mode)
|
||||
scenario_stream_pass(guard, mode)
|
||||
scenario_output_pii(pii_guard, mode)
|
||||
scenario_output_denied(guard, mode)
|
||||
scenario_non_stream_pass(guard, mode)
|
||||
scenario_non_stream_pii(pii_guard, mode)
|
||||
scenario_upstream_error(guard, mode)
|
||||
scenario_opaque_request(guard, mode)
|
||||
scenario_judge_down(mode)
|
||||
scenario_stream_redact(mode)
|
||||
scenario_request_rewrite(mode)
|
||||
scenario_tool_call_paths(mode)
|
||||
|
||||
total_ms = sum(call["ms"] for call in host.calls)
|
||||
if host.calls:
|
||||
print(f"\n审核调用 {len(host.calls)} 次,平均 {total_ms // len(host.calls)} ms")
|
||||
print(f"\n{CHECKS - len(FAILURES)}/{CHECKS} 通过")
|
||||
if FAILURES:
|
||||
print("失败项:")
|
||||
for name in FAILURES:
|
||||
print(" -", name)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user