feat: Docker 打包、交付链路与命名脱敏

镜像与构建
- 六阶段 Dockerfile(base/wheels/deps/manifest/core|guard),core 不含 torch
- 构建期自证:gen_manifest --strict 拦未登记模块,core 阶段重算 sha256
- compose 四服务 host 网络(llm.url 强制回环),config.core/local 可挂载覆盖

无 docker 环境的四段链路
- pull_oci_image.py      直拉 OCI 镜像 rootfs(纯标准库,走加速器)
- replay_image_build.sh  按 stage chroot 重放 Dockerfile
- run_image_chroot.sh    等价 docker run(uid 10001 + 入口 + host 网络)
- pack_image.py          封成 docker save 格式包,自带 diff_id 校验

交付
- make_package.sh 生成自包含目录:镜像包 + 溯源清单 + 构建输入 + 脚本 + 源码快照
- 文档:从零复现指南、docker 打包方案、镜像构建限制与替代方案、交付包 README

命名
- Qwen 品牌名统一替换为 large_model / small_model / large_model_guard,
  覆盖 vLLM 服务名、模型目录、配置、脚本、测试与文档
- 模型架构字段(architectures / model_type / tokenizer_class)属上游定义,
  改名会导致加载失败,保留原值;check_local_model.py 的架构判断同理

验证:smoke 6/6;test.py 20 通过 0 失败 1 警告;gen --strict 67 文件 / 22 进镜像
This commit is contained in:
chenleixu committed 2026-11-27 18:20:16 +00:00
1 parent bfdc5e9168
commit b82e44ec32
46 files changed
+10271 -484

No files matched your search

+25 -4
View File
@@ -82,28 +82,45 @@ class NetworkPolicy(Model):
class LLMLoadConfig(Model):
device: str = "cpu"
device: str = "cpu" # vLLM backend 下无意义,保留以兼容旧配置
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
revision: str | None = None
enable_thinking: bool | None = None # None = 不传该 kwarg
class LLMLimits(Model):
max_input_tokens: int = Field(default=4096, gt=0, le=32768)
max_new_tokens: int = Field(default=32, gt=0, le=512)
timeout_seconds: float = Field(default=3, gt=0, le=60)
max_concurrency: int = Field(default=1, gt=0, le=1)
max_concurrency: int = Field(default=1, gt=0, le=32)
queue_size: int = Field(default=8, gt=0, le=1024)
class LLMConfig(Model):
id: str = Field(pattern=r"^[a-zA-Z0-9_.-]{1,128}$")
type: Literal["guard"]
backend: Literal["transformers"] = "transformers"
file: Path
backend: Literal["transformers", "vllm"] = "transformers"
file: Path | None = None # transformers 必填
url: str | None = None # vllm 必填,必须是本机回环
served_model: str | None = None # vllm 必填,须与 /v1/models 一致
startup_timeout_seconds: float = Field(default=60, gt=0, le=600)
enabled: bool = True
load: LLMLoadConfig = Field(default_factory=LLMLoadConfig)
limits: LLMLimits = Field(default_factory=LLMLimits)
@model_validator(mode="after")
def _check_backend(self):
if self.backend == "transformers":
if self.file is None:
raise ValueError("llm.backend=transformers 需要 file")
return self
if not self.url or not self.served_model:
raise ValueError("llm.backend=vllm 需要 url 与 served_model")
host = (urlsplit(self.url).hostname or "").lower()
if host not in {"127.0.0.1", "::1", "localhost"}:
raise ValueError("llm.url 必须指向本机回环地址")
return self
class PluginLLMAccess(Model):
allow: list[str] = Field(default_factory=list)
@@ -216,6 +233,10 @@ def load_settings(path: str | Path) -> Settings:
plugins.append(plugin.model_copy(update={"file": file}))
models = []
for model in settings.llm:
if model.file is None:
# backend=vllm 的条目只有 url/served_model,没有权重目录
models.append(model)
continue
file = model.file.resolve()
if not file.exists():
raise ValueError(f"llm model path not found: {model.id}")
+120 -1
View File
@@ -10,6 +10,8 @@ import re
from collections.abc import Mapping
from typing import Any, Protocol
import aiohttp
from .config import LLMConfig, Settings
logger = logging.getLogger("middleware.audit")
@@ -273,6 +275,118 @@ class GuardAdapter:
connection.close()
class VLLMAdapter:
"""把 guard 判定转发给本机已起好的 vLLM(OpenAI 兼容接口)。
与 GuardAdapter 的差别只有传输层:契约(guard_messages / parse_guard_output /
validate_guard_result)完全共用,所以两种 backend 的测试用例不分叉。
"""
def __init__(self, spec: LLMConfig):
self.spec = spec
self.base = (spec.url or "").rstrip("/")
self.session: aiohttp.ClientSession | None = None
self.slots = asyncio.Semaphore(spec.limits.max_concurrency)
self.inflight = 0
self.inflight_lock = asyncio.Lock()
def describe(self) -> dict[str, Any]:
return {
"id": self.spec.id,
"type": self.spec.type,
"backend": "vllm",
"endpoint": f"{self.base}/v1/chat/completions",
"model": self.spec.served_model,
"capabilities": ["prompt_moderation", "response_moderation"],
}
async def start(self) -> None:
if self.session is not None:
return
self.session = aiohttp.ClientSession(
trust_env=False, # 不理 HTTP_PROXY 等环境变量
cookie_jar=aiohttp.DummyCookieJar(), # 不带任何凭据
timeout=aiohttp.ClientTimeout(total=self.spec.limits.timeout_seconds + 5),
)
loop = asyncio.get_running_loop()
deadline = loop.time() + self.spec.startup_timeout_seconds
while True:
try:
async with self.session.get(
f"{self.base}/v1/models", allow_redirects=False
) as response:
if response.status == 200:
body = await response.json(content_type=None)
served = {
item.get("id")
for item in body.get("data", [])
if isinstance(item, dict)
}
if self.spec.served_model not in served:
# 配错名字就别带病运行,直接让启动失败
await self.stop() # 先关 session,否则启动失败会漏连接
raise LLMUnavailable("ModelNotServed")
return
except (aiohttp.ClientError, asyncio.TimeoutError):
pass
if loop.time() >= deadline:
await self.stop()
raise LLMUnavailable("EndpointUnreachable")
await asyncio.sleep(1)
async def call(self, request: dict[str, Any]) -> dict[str, Any]:
messages = guard_messages(request) # 契约校验与 transformers 路径共用
body: dict[str, Any] = {
"model": self.spec.served_model,
"messages": messages,
"max_tokens": self.spec.limits.max_new_tokens,
"temperature": 0,
"stream": False,
}
if self.spec.load.enable_thinking is not None:
body["chat_template_kwargs"] = {"enable_thinking": self.spec.load.enable_thinking}
async with self.inflight_lock:
# queue_size 计等待数,+1 是正在跑的那一个
if self.inflight >= self.spec.limits.queue_size + 1:
raise LLMQueueFull("ModelQueueFull")
self.inflight += 1
try:
async with asyncio.timeout(self.spec.limits.timeout_seconds):
async with self.slots:
if self.session is None:
raise LLMUnavailable("ModelUnavailable")
async with self.session.post(
f"{self.base}/v1/chat/completions",
json=body,
allow_redirects=False,
) as response:
if response.status != 200:
raise LLMFailure("ModelFailure")
data = await response.json(content_type=None)
choices = data.get("choices") if isinstance(data, dict) else None
if not isinstance(choices, list) or not choices:
raise LLMFailure("ModelFailure")
message = choices[0].get("message") or {}
return validate_guard_result(
parse_guard_output(message.get("content")), request["task"]
)
except TimeoutError:
raise LLMFailure("ModelTimeout") from None # 不 stop,下次照常重试
except LLMFailure:
raise
except Exception:
raise LLMUnavailable("ModelUnavailable") from None
finally:
async with self.inflight_lock:
self.inflight -= 1
async def stop(self) -> None:
if self.session is not None:
await self.session.close()
self.session = None
class LLMRegistry:
def __init__(self, settings: Settings):
self.settings = settings
@@ -280,7 +394,12 @@ class LLMRegistry:
self.plugins = {plugin.id: plugin for plugin in settings.plugins if plugin.enabled}
required = {model_id for plugin in self.plugins.values() for model_id in plugin.llm.allow}
self.adapters: dict[str, LLMAdapter] = {
model_id: GuardAdapter(self.specs[model_id]) for model_id in required
model_id: (
VLLMAdapter(self.specs[model_id])
if self.specs[model_id].backend == "vllm"
else GuardAdapter(self.specs[model_id])
)
for model_id in required
}
async def start(self) -> None: