guard: 判定改回宿主本地守卫模型,数据不出机器
原先判定走远程 /v1/chat/completions,用户原文会出境,且 2s 级延迟、抖动大。改为 host.llm.call:
- 输入 {task=prompt_moderation, prompt=指令+正文}
- 输出 {task=response_moderation, prompt=指令, response=模型输出}
宿主契约只接受这两个键集合,多一个键即 InvalidModelRequest;返回 {safety,categories,refusal},safety 仅 Safe/Unsafe/Controversial。本地判定套不了 OpenAI messages 结构——OpenAI 格式只保留在对外接口。
配置:启用 llm 段(models/guard_model),插件声明 llm.allow: [guard_model],
移除 network 白名单与 judge_* 远程参数;新增 block_controversial。
按本地推理重设资源:hook_timeout 45→120、judge_chunk_bytes 16384→8192、
max_buffer_bytes 131072→65536、max_new_tokens=64、模型 timeout=60。
新增 tools/check_local_model.py 做部署前自检(模型目录完整性、llm.allow 与
llm.id 一致、torch/transformers 依赖、设备)。模型目录缺失时 load_settings
直接抛错,不会降级放行。
verify_plugins.py 的假宿主改为复刻 middleware/llm.py 的严格契约,并断言全程
零出网;用例扩到 103 项,全部通过。已用假模型目录验证 load_settings 与
LLMRegistry 能正确建立 guard_model adapter。
This commit is contained in:
1 parent
ec6f5fc811
commit
d239cf584c
5 files changed
+436
-456
No files matched your search
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env python3
|
||||
"""部署前自检:本地守卫模型与 config.yaml 是否对得上。
|
||||
|
||||
python tools/check_local_model.py [--config config.yaml]
|
||||
|
||||
只读检查,不加载模型、不发请求。覆盖三类会让宿主启动失败的问题:
|
||||
1. llm 段的 file 不是完整的 HuggingFace 目录(宿主直接 LLMUnavailable)
|
||||
2. 插件的 llm.allow 与 llm 段 id 不一致(LLMRegistry 构造时 KeyError)
|
||||
3. torch / transformers 缺失(llm_worker 导入即失败)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
WEIGHT_SUFFIXES = (".safetensors", ".bin", ".pt")
|
||||
TOKENIZER_FILES = ("tokenizer.json", "tokenizer.model", "vocab.json", "spiece.model")
|
||||
|
||||
|
||||
def fail(label: str, detail: str = "") -> bool:
|
||||
print(f" FAIL {label}{(' -> ' + detail) if detail else ''}")
|
||||
return False
|
||||
|
||||
|
||||
def ok(label: str, detail: str = "") -> bool:
|
||||
print(f" PASS {label}{(' -> ' + detail) if detail else ''}")
|
||||
return True
|
||||
|
||||
|
||||
def check_model_dir(path: pathlib.Path) -> bool:
|
||||
if not path.is_dir():
|
||||
return fail(f"模型目录 {path}", "不存在")
|
||||
passed = ok(f"模型目录 {path}")
|
||||
|
||||
config_json = path / "config.json"
|
||||
passed &= ok("config.json 存在") if config_json.is_file() else fail("config.json 缺失")
|
||||
|
||||
weights = [p for p in path.iterdir() if p.suffix in WEIGHT_SUFFIXES]
|
||||
if weights:
|
||||
total = sum(p.stat().st_size for p in weights)
|
||||
passed &= ok("权重文件", f"{len(weights)} 个,共 {total / 2**30:.1f} GiB")
|
||||
else:
|
||||
passed &= fail("权重文件缺失", "需要 " + " / ".join(WEIGHT_SUFFIXES))
|
||||
|
||||
tokenizer = [name for name in TOKENIZER_FILES if (path / name).is_file()]
|
||||
if tokenizer:
|
||||
passed &= ok("tokenizer 文件", ", ".join(tokenizer))
|
||||
else:
|
||||
passed &= fail("tokenizer 文件缺失", "需要 " + " / ".join(TOKENIZER_FILES))
|
||||
|
||||
# chat template 决定 prompt 怎么包进模型;缺失时 apply_chat_template 会失败
|
||||
if (path / "tokenizer_config.json").is_file():
|
||||
passed &= ok("tokenizer_config.json 存在")
|
||||
else:
|
||||
passed &= fail("tokenizer_config.json 缺失", "apply_chat_template 需要它")
|
||||
return passed
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--config", default=str(ROOT / "config.yaml"))
|
||||
args = parser.parse_args()
|
||||
|
||||
config_path = pathlib.Path(args.config)
|
||||
print(f"配置文件: {config_path}")
|
||||
if not config_path.is_file():
|
||||
fail("config.yaml 存在")
|
||||
return 1
|
||||
|
||||
settings = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
||||
print("\n[1] llm 段")
|
||||
models = settings.get("llm") or []
|
||||
if not models:
|
||||
print(" FAIL 没有 llm 段:插件调 host.llm 会必然失败")
|
||||
return 1
|
||||
passed = True
|
||||
model_ids = set()
|
||||
for model in models:
|
||||
model_id = model.get("id", "")
|
||||
model_ids.add(model_id)
|
||||
print(f" - id={model_id} type={model.get('type')} file={model.get('file')}")
|
||||
if model.get("type") != "guard":
|
||||
passed &= fail(f"{model_id} type 必须是 guard", str(model.get("type")))
|
||||
target = pathlib.Path(model.get("file", ""))
|
||||
if not target.is_absolute():
|
||||
target = (config_path.parent / target).resolve()
|
||||
passed &= check_model_dir(target)
|
||||
|
||||
print("\n[2] 插件 llm.allow 与 llm 段一致性")
|
||||
plugins = settings.get("plugins") or []
|
||||
if not plugins:
|
||||
fail("plugins 段非空")
|
||||
return 1
|
||||
enabled = [p for p in plugins if p.get("enabled", True)]
|
||||
print(f" 启用插件: {[p.get('id') for p in enabled] or '(无)'}")
|
||||
for plugin in enabled:
|
||||
allowed = ((plugin.get("llm") or {}).get("allow")) or []
|
||||
if not allowed:
|
||||
continue
|
||||
for model_id in allowed:
|
||||
if model_id in model_ids:
|
||||
passed &= ok(f"{plugin.get('id')} → {model_id}")
|
||||
else:
|
||||
passed &= fail(f"{plugin.get('id')} 引用了未定义的模型 {model_id}")
|
||||
|
||||
print("\n[3] 推理依赖")
|
||||
for module in ("torch", "transformers", "tokenizers", "safetensors"):
|
||||
try:
|
||||
__import__(module)
|
||||
passed &= ok(f"import {module}")
|
||||
except ImportError:
|
||||
passed &= fail(f"import {module}", "缺失,llm_worker 会 ModelLoadFailed")
|
||||
|
||||
print("\n[4] 设备")
|
||||
try:
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
print(f" PASS cuda 可用,{torch.cuda.device_count()} 张卡")
|
||||
else:
|
||||
print(" WARN cuda 不可用;load.device=cpu 可用但慢,cuda 需改配置")
|
||||
except ImportError:
|
||||
print(" WARN 无法判断(torch 未安装)")
|
||||
|
||||
print("\n结论:", "可以启动" if passed else "存在阻塞项,宿主会起不来")
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+173
-168
@@ -1,23 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""用宿主的真实 Lua 契约驱动插件,验证 OpenAI 形态的输出。
|
||||
"""用宿主的真实 Lua 契约驱动插件,验证 OpenAI 形态的对外输出。
|
||||
|
||||
python tools/verify_plugins.py # 全部场景(会真实调用审核接口)
|
||||
python tools/verify_plugins.py --mock # 审核接口全部放行,只验协议形态
|
||||
python tools/verify_plugins.py
|
||||
|
||||
宿主契约来自 lua/worker.py(host.json / host.http / host.log),
|
||||
网络调用真的打出去,因此能同时验证 URL、鉴权头、请求体与响应解析。
|
||||
判定走宿主机本地守卫模型,脚本用一个按 middleware/llm.py 严格契约实现的
|
||||
假 host 代替它:请求键集合、返回值枚举都会被校验,且断言插件全程不出网。
|
||||
"""
|
||||
|
||||
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))
|
||||
@@ -32,7 +27,11 @@ except ImportError as exc: # pragma: no cover - 依赖缺失时的友好提示
|
||||
"(宿主运行时自带 lupa,这里缺的是开发机上的校验环境)\n"
|
||||
)
|
||||
raise SystemExit(2)
|
||||
raise
|
||||
try:
|
||||
# 交付仓库里同一个文件叫 middleware/worker.py,接口一致
|
||||
from middleware.worker import LuaPlugin # noqa: E402
|
||||
except ImportError:
|
||||
raise
|
||||
|
||||
LIMITS = {
|
||||
"lua_memory_bytes": 268435456,
|
||||
@@ -55,74 +54,79 @@ def check(condition: bool, label: str, detail: str = "") -> None:
|
||||
|
||||
|
||||
class Host:
|
||||
"""最小宿主实现,签名与 runtime.py 调用插件时一致。"""
|
||||
"""最小宿主实现,签名与 runtime.py 调用插件时一致。
|
||||
|
||||
def __init__(self, mode: str):
|
||||
llm 一侧复刻 middleware/llm.py 的严格契约:请求键集合必须精确等于
|
||||
{task, prompt} 或 {task, prompt, response},返回值必须落在 safety 枚举内。
|
||||
"""
|
||||
|
||||
SAFETY = ("Safe", "Unsafe", "Controversial")
|
||||
CATEGORIES = (
|
||||
"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",
|
||||
)
|
||||
RISK_WORDS = ("炸药", "雷管", "硝酸铵")
|
||||
|
||||
def __init__(self, mode: str, safety: str = "auto", fail: bool = False):
|
||||
self.mode = mode
|
||||
self.calls: list[dict] = []
|
||||
self.requests: list[dict] = []
|
||||
self.safety = safety
|
||||
self.fail = fail
|
||||
self.calls: list[dict] = [] # 判定调用(llm)
|
||||
self.requests: list[dict] = [] # 任何出网请求,正常应为空
|
||||
self.contract_errors: list[str] = []
|
||||
|
||||
def callback(self, kind: str, value):
|
||||
if kind == "http":
|
||||
return self.http(value)
|
||||
if kind == "llm":
|
||||
return self.llm(value)
|
||||
if kind == "log":
|
||||
return None
|
||||
if kind == "http":
|
||||
self.requests.append(value)
|
||||
raise RuntimeError("plugin must not use host.http")
|
||||
raise RuntimeError(f"unexpected capability: {kind}")
|
||||
|
||||
def llm(self, payload: dict) -> dict:
|
||||
model = payload.get("model")
|
||||
request = payload.get("request") or {}
|
||||
self.calls.append({"model": model, "request": request})
|
||||
|
||||
task = request.get("task")
|
||||
if task not in ("prompt_moderation", "response_moderation"):
|
||||
self.contract_errors.append(f"bad task: {task!r}")
|
||||
raise RuntimeError("InvalidModelRequest")
|
||||
expected = {"task", "prompt"} | ({"response"} if task == "response_moderation" else set())
|
||||
if set(request) != expected:
|
||||
self.contract_errors.append(f"key set {sorted(request)} != {sorted(expected)}")
|
||||
raise RuntimeError("InvalidModelRequest")
|
||||
if not isinstance(request.get("prompt"), str) or not request["prompt"]:
|
||||
self.contract_errors.append("prompt must be a non-empty string")
|
||||
raise RuntimeError("InvalidModelRequest")
|
||||
if task == "response_moderation" and not request.get("response"):
|
||||
self.contract_errors.append("response must be a non-empty string")
|
||||
raise RuntimeError("InvalidModelRequest")
|
||||
|
||||
if self.fail:
|
||||
raise RuntimeError("ModelFailure")
|
||||
|
||||
text = request["prompt"] + "\n" + str(request.get("response") or "")
|
||||
if self.safety != "auto":
|
||||
safety = self.safety
|
||||
else:
|
||||
safety = "Unsafe" if any(word in text for word in self.RISK_WORDS) else "Safe"
|
||||
categories = ["Violent"] if safety == "Unsafe" else []
|
||||
return {"safety": safety, "categories": categories, "refusal": None}
|
||||
|
||||
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()
|
||||
# 记录插件真实发出的判定请求,用于校验 OpenAI 请求体形态
|
||||
self.requests.append({"url": url, "method": method, "headers": headers, "body": body})
|
||||
|
||||
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,
|
||||
}
|
||||
self.requests.append(request)
|
||||
raise RuntimeError("plugin must not use host.http")
|
||||
|
||||
|
||||
class Driver:
|
||||
@@ -171,8 +175,8 @@ class Driver:
|
||||
return self.plugin.invoke("on_end", self.ctx, None)
|
||||
|
||||
|
||||
def load(path: pathlib.Path, config: dict, mode: str):
|
||||
host = Host(mode)
|
||||
def load(path: pathlib.Path, config: dict, mode: str, **host_kwargs):
|
||||
host = Host(mode, **host_kwargs)
|
||||
plugin = LuaPlugin(path.read_text(encoding="utf-8"), LIMITS, host.callback)
|
||||
plugin.invoke("init", {"request_id": "init", "plugin_id": "test"}, config)
|
||||
return plugin, host
|
||||
@@ -208,19 +212,14 @@ def drain(result, sink: list[dict]) -> None:
|
||||
|
||||
|
||||
GUARD_CONFIG = {
|
||||
"base_url": os.environ.get("SAFETY_BASE_URL", "https://ai.leapstella.com/v1"),
|
||||
# 密钥只从环境变量读,仓库里不存明文;--mock 模式不需要
|
||||
"api_key": os.environ.get("SAFETY_API_KEY", ""),
|
||||
# 与 config.yaml 保持一致的默认判定模型;可用 SAFETY_MODEL 覆盖
|
||||
"model": os.environ.get("SAFETY_MODEL", "deepseek-v4-pro"),
|
||||
# 与 config.yaml 的 llm 段 id 一致;插件只传 id,模型由宿主加载
|
||||
"model": "guard_model",
|
||||
"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",
|
||||
"judge_chunk_bytes": 8192,
|
||||
}
|
||||
|
||||
|
||||
@@ -258,10 +257,7 @@ def scenario_input_denied_stream(guard, mode):
|
||||
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)} 次)")
|
||||
check(guard.host.requests == [], "判定全程没有出网请求")
|
||||
|
||||
|
||||
def scenario_input_denied_non_stream(guard, mode):
|
||||
@@ -420,15 +416,12 @@ def scenario_opaque_request(guard, mode):
|
||||
|
||||
|
||||
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",
|
||||
)
|
||||
print("\n[10] 本地模型调用失败:503 + server_error(fail-closed)")
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, "mock", fail=True)
|
||||
driver = Driver(guard, "req-judge-down")
|
||||
result = driver.request({"model": "test-model", "messages": [{"role": "user", "content": "你好"}]})
|
||||
check(result.get("action") == "replace", "请求被换成 stub", str(result))
|
||||
check(host.contract_errors == [], "请求仍符合宿主契约", str(host.contract_errors))
|
||||
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 {}
|
||||
@@ -529,70 +522,67 @@ 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 协议")
|
||||
def scenario_judge_contract(mode):
|
||||
print("\n[14] 本地模型请求体:严格符合 host.llm 契约(不多键也不少键)")
|
||||
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": "你好"}]})
|
||||
driver = Driver(guard, "req-contract")
|
||||
driver.request({"model": "gpt-4o", "stream": True, "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")
|
||||
check(len(host.calls) == 1, "输入审核调用 1 次", str(len(host.calls)))
|
||||
check(host.contract_errors == [], "没有契约违规", str(host.contract_errors))
|
||||
check(host.requests == [], "没有走 host.http")
|
||||
if host.calls:
|
||||
sent = host.calls[0]
|
||||
check(sent["model"] == GUARD_CONFIG["model"], "model 用配置的守卫模型 id", str(sent["model"]))
|
||||
check(sorted(sent["request"]) == ["prompt", "task"], "输入判定只有 task+prompt",
|
||||
str(sorted(sent["request"])))
|
||||
check(sent["request"]["task"] == "prompt_moderation", "task=prompt_moderation",
|
||||
sent["request"]["task"])
|
||||
check("帮我写个冒泡排序" in sent["request"]["prompt"], "正文进入 prompt")
|
||||
|
||||
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 的前置条件)")
|
||||
# 输出侧必须用 response_moderation,且正文放 response 字段而不是塞进 prompt
|
||||
driver = Driver(guard, "req-contract-out")
|
||||
driver.request({"model": "gpt-4o", "messages": [{"role": "user", "content": "写个排序"}]})
|
||||
driver.response(200, {
|
||||
"id": "chatcmpl-c", "object": "chat.completion",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "先比较相邻元素。"}, "finish_reason": "stop"}],
|
||||
})
|
||||
out = [c for c in host.calls if c["request"].get("task") == "response_moderation"]
|
||||
check(len(out) == 1, "输出审核调用 1 次", str(len(out)))
|
||||
if out:
|
||||
request = out[0]["request"]
|
||||
check(sorted(request) == ["prompt", "response", "task"], "输出判定是 task+prompt+response",
|
||||
str(sorted(request)))
|
||||
check(request["response"] == "先比较相邻元素。", "模型输出放在 response", str(request.get("response")))
|
||||
check("先比较相邻元素" not in request["prompt"], "正文没有被塞进 prompt")
|
||||
|
||||
|
||||
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)
|
||||
def scenario_verdict_policy(mode):
|
||||
print("\n[15] 判定结果映射:Unsafe / Controversial / 超长分段")
|
||||
path = ROOT / "plugins" / "response_guard.lua"
|
||||
|
||||
# 换成 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",
|
||||
for safety, blocked, label in (
|
||||
("Unsafe", True, "Unsafe 拦截"),
|
||||
("Controversial", True, "Controversial 默认拦截"),
|
||||
):
|
||||
guard, _ = load(path, GUARD_CONFIG, "mock", safety=safety)
|
||||
result = Driver(guard, f"req-{safety}").request(
|
||||
{"model": "m", "messages": [{"role": "user", "content": "普通文本"}]}
|
||||
)
|
||||
check((result.get("action") == "replace") is blocked, label, str(result)[:120])
|
||||
|
||||
guard, _ = load(path, dict(GUARD_CONFIG, block_controversial=False), "mock", safety="Controversial")
|
||||
result = Driver(guard, "req-contro-off").request(
|
||||
{"model": "m", "messages": [{"role": "user", "content": "普通文本"}]}
|
||||
)
|
||||
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")
|
||||
check(result.get("action") == "pass", "block_controversial=false 时 Controversial 放行", str(result)[:120])
|
||||
|
||||
# 超长输入按 judge_chunk_bytes 分段,每段一次调用
|
||||
guard, host = load(path, dict(GUARD_CONFIG, judge_chunk_bytes=1024), "mock")
|
||||
long_text = "这是一段普通的中文说明文字。" * 60
|
||||
Driver(guard, "req-chunks").request({"model": "m", "messages": [{"role": "user", "content": long_text}]})
|
||||
check(len(host.calls) > 1, "超长输入被分成多段判定", str(len(host.calls)))
|
||||
check(all(c["request"].get("task") == "prompt_moderation" for c in host.calls), "每段都是 prompt_moderation")
|
||||
|
||||
|
||||
def scenario_content_parts(mode):
|
||||
@@ -608,10 +598,9 @@ def scenario_content_parts(mode):
|
||||
]}],
|
||||
})
|
||||
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 不进判定")
|
||||
prompt = host.calls[0]["request"]["prompt"] if host.calls else ""
|
||||
check("帮我看看这张图" in prompt, "文本块进入判定", prompt[:80])
|
||||
check("example.com" not in prompt, "图片 URL 不进判定")
|
||||
|
||||
driver = Driver(guard, "req-parts-deny")
|
||||
result = driver.request({
|
||||
@@ -665,28 +654,44 @@ def scenario_stub_openai_shape(mode):
|
||||
check(stub3.get("stream") is True, "流式请求的 stub 仍为 stream=true")
|
||||
|
||||
|
||||
def scenario_config_init(mode):
|
||||
print("\n[18] 仓库里的 config.yaml 能直接 init 插件")
|
||||
import yaml
|
||||
|
||||
for name in ("config.yaml", "config.example.yaml"):
|
||||
path = ROOT / name
|
||||
if not path.is_file():
|
||||
check(False, f"{name} 存在")
|
||||
continue
|
||||
settings = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
||||
guard_cfg = next((p for p in settings.get("plugins") or [] if p.get("id") == "response-guard"), None)
|
||||
check(guard_cfg is not None, f"{name} 有 response-guard 插件")
|
||||
if not guard_cfg:
|
||||
continue
|
||||
model_ids = {m.get("id") for m in settings.get("llm") or []}
|
||||
check(guard_cfg.get("llm", {}).get("allow") == [guard_cfg["config"]["model"]],
|
||||
f"{name} 的 llm.allow 与 config.model 一致", str(guard_cfg.get("llm")))
|
||||
check(guard_cfg["config"]["model"] in model_ids,
|
||||
f"{name} 的 model 在 llm 段里定义", str(sorted(model_ids)))
|
||||
try:
|
||||
load(ROOT / "plugins" / "response_guard.lua", guard_cfg["config"], "mock")
|
||||
check(True, f"{name} 的 config 段 init 成功")
|
||||
except Exception as exc: # noqa: BLE001 - 报告给使用者即可
|
||||
check(False, f"{name} 的 config 段 init 成功", str(exc))
|
||||
check("network" not in guard_cfg, f"{name} 不再需要 network 白名单")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mock", action="store_true", help="不调用真实审核接口")
|
||||
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}")
|
||||
print(f"判定后端: 宿主机本地模型 model={GUARD_CONFIG['model']}(无出网请求)")
|
||||
|
||||
scenario_input_denied_stream(guard, mode)
|
||||
scenario_input_denied_non_stream(guard, mode)
|
||||
@@ -701,14 +706,14 @@ 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_judge_contract(mode)
|
||||
scenario_verdict_policy(mode)
|
||||
scenario_content_parts(mode)
|
||||
scenario_stub_openai_shape(mode)
|
||||
scenario_config_init(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")
|
||||
check(host.requests == [], "全部场景零出网请求", str(len(host.requests)))
|
||||
print(f"\n判定调用 {len(host.calls)} 次")
|
||||
print(f"\n{CHECKS - len(FAILURES)}/{CHECKS} 通过")
|
||||
if FAILURES:
|
||||
print("失败项:")
|
||||
|
||||
Reference in new issue
Block a user