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())
|
||||
Reference in new issue
Block a user