feat(LLM): 增加可扩展模型插件能力

新增顶层 LLM 注册配置、插件授权列表和 guard 类型适配器。\n模型由独立 Python 进程加载,通过受限 IPC 为 Lua 提供 host.llm.list、host.llm.call 和可调用接口。\n增加 Qwen3Guard 结果解析、流式审核示例、可选依赖、Docker 构建文件和协议测试。
This commit is contained in:
starrrLight committed 2026-10-11 17:39:03 +08:00
1 parent 8c1d243b51
commit b331927773
11 files changed
+693 -4

No files matched your search

+49 -1
View File
@@ -1,5 +1,6 @@
import ipaddress
from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
import yaml
@@ -80,12 +81,41 @@ class NetworkPolicy(Model):
max_response_bytes: int = Field(default=1024 * 1024, gt=0)
class LLMLoadConfig(Model):
device: str = "cpu"
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
revision: str | None = None
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)
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
enabled: bool = True
load: LLMLoadConfig = Field(default_factory=LLMLoadConfig)
limits: LLMLimits = Field(default_factory=LLMLimits)
class PluginLLMAccess(Model):
allow: list[str] = Field(default_factory=list)
class PluginConfig(Model):
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
file: Path
enabled: bool = True
config: dict = Field(default_factory=dict)
network: NetworkPolicy = Field(default_factory=NetworkPolicy)
llm: PluginLLMAccess = Field(default_factory=PluginLLMAccess)
class Limits(Model):
@@ -105,6 +135,7 @@ class Settings(Model):
listen_host: str = "0.0.0.0"
listen_port: int = Field(default=8080, ge=1, le=65535)
limits: Limits = Field(default_factory=Limits)
llm: list[LLMConfig] = Field(default_factory=list)
plugins: list[PluginConfig] = Field(default_factory=list)
@field_validator("upstream")
@@ -123,6 +154,17 @@ class Settings(Model):
ids = [p.id for p in self.plugins]
if len(ids) != len(set(ids)):
raise ValueError("duplicate plugin IDs")
model_ids = [model.id for model in self.llm]
if len(model_ids) != len(set(model_ids)):
raise ValueError("duplicate llm IDs")
models = {model.id: model for model in self.llm}
for plugin in self.plugins:
for model_id in plugin.llm.allow:
model = models.get(model_id)
if model is None:
raise ValueError(f"unknown llm model: {model_id}")
if not model.enabled:
raise ValueError(f"disabled llm model: {model_id}")
return self
@@ -137,4 +179,10 @@ def load_settings(path: str | Path) -> Settings:
if not file.is_file():
raise ValueError(f"plugin file not found: {plugin.id}")
plugins.append(plugin.model_copy(update={"file": file}))
return settings.model_copy(update={"plugins": plugins})
models = []
for model in settings.llm:
file = (path.parent / model.file).resolve()
if not file.exists():
raise ValueError(f"llm model path not found: {model.id}")
models.append(model.model_copy(update={"file": file}))
return settings.model_copy(update={"plugins": plugins, "llm": models})
+288
View File
@@ -0,0 +1,288 @@
"""Python-side LLM registry and isolated local guard model workers."""
from __future__ import annotations
import asyncio
import json
import logging
import multiprocessing
import re
from collections.abc import Mapping
from typing import Any, Protocol
from .config import LLMConfig, Settings
logger = logging.getLogger("middleware.audit")
class LLMFailure(Exception):
"""A deliberately non-sensitive LLM capability failure."""
class LLMUnavailable(LLMFailure):
pass
class LLMQueueFull(LLMFailure):
pass
class LLMAdapter(Protocol):
async def start(self) -> None: ...
async def call(self, request: dict[str, Any]) -> dict[str, Any]: ...
async def stop(self) -> None: ...
def describe(self) -> dict[str, Any]: ...
SAFE_LABELS = {"Safe", "Unsafe", "Controversial"}
CATEGORY_LABELS = (
"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",
)
def parse_guard_output(content: str) -> dict[str, Any]:
"""Convert the model's free-form generation into a fixed JSON contract."""
if not isinstance(content, str):
raise LLMFailure()
safety_match = re.search(r"Safety:\s*(Safe|Unsafe|Controversial)\b", content)
categories_match = re.search(r"Categories:\s*([^\r\n]*)", content)
if safety_match is None or categories_match is None:
raise LLMFailure()
safety = safety_match.group(1)
if safety not in SAFE_LABELS:
raise LLMFailure()
category_text = categories_match.group(1).strip()
categories: list[str] = []
if category_text.lower() != "none":
for category in CATEGORY_LABELS:
if re.search(rf"(?<!\w){re.escape(category)}(?!\w)", category_text):
if category not in categories:
categories.append(category)
if not categories:
raise LLMFailure()
refusal_match = re.search(r"Refusal:\s*(Yes|No)\b", content)
return {
"safety": safety,
"categories": categories,
"refusal": refusal_match.group(1) if refusal_match else None,
}
def guard_messages(request: Mapping[str, Any]) -> list[dict[str, str]]:
if not isinstance(request, Mapping):
raise LLMFailure("InvalidModelRequest")
task = request.get("task")
prompt = request.get("prompt")
if task not in {"prompt_moderation", "response_moderation"}:
raise LLMFailure("InvalidModelRequest")
if not isinstance(prompt, str) or not prompt:
raise LLMFailure("InvalidModelRequest")
expected = {"task", "prompt"}
messages = [{"role": "user", "content": prompt}]
if task == "response_moderation":
response = request.get("response")
if not isinstance(response, str) or not response:
raise LLMFailure("InvalidModelRequest")
expected.add("response")
messages.append({"role": "assistant", "content": response})
if set(request) != expected:
raise LLMFailure("InvalidModelRequest")
return messages
def validate_guard_result(value: Any, task: str) -> dict[str, Any]:
if not isinstance(value, dict) or set(value) != {"safety", "categories", "refusal"}:
raise LLMFailure("InvalidModelOutput")
if value["safety"] not in SAFE_LABELS:
raise LLMFailure("InvalidModelOutput")
if not isinstance(value["categories"], list) or any(
category not in CATEGORY_LABELS for category in value["categories"]
):
raise LLMFailure("InvalidModelOutput")
if value["refusal"] not in {None, "Yes", "No"}:
raise LLMFailure("InvalidModelOutput")
if task == "prompt_moderation" and value["refusal"] is not None:
return {**value, "refusal": None}
return value
def _json_bytes(value: Any) -> bytes:
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode()
def _send(connection, value: dict[str, Any]) -> None:
connection.send_bytes(_json_bytes(value))
class GuardAdapter:
def __init__(self, spec: LLMConfig):
self.spec = spec
self.context = multiprocessing.get_context("spawn")
self.connection = None
self.process = None
self.rpc_lock = asyncio.Lock()
self.pending_lock = asyncio.Lock()
self.pending = 0
def describe(self) -> dict[str, Any]:
return {
"id": self.spec.id,
"type": self.spec.type,
"capabilities": ["prompt_moderation", "response_moderation"],
}
async def start(self) -> None:
if self.process is not None:
return
from .llm_worker import guard_worker_main
if not self.spec.file.is_dir():
raise LLMUnavailable()
parent, child = self.context.Pipe(duplex=True)
process = self.context.Process(
target=guard_worker_main,
args=(
child,
str(self.spec.file),
self.spec.load.model_dump(),
self.spec.limits.model_dump(),
),
daemon=True,
)
try:
process.start()
except Exception as exc:
parent.close()
child.close()
raise LLMUnavailable() from exc
child.close()
self.connection = parent
self.process = process
try:
response = await asyncio.wait_for(
asyncio.to_thread(parent.recv_bytes, 1024 * 1024),
timeout=300,
)
result = json.loads(response)
if not result.get("ok"):
raise LLMUnavailable()
except BaseException as exc:
await self.stop()
if isinstance(exc, (LLMFailure, asyncio.CancelledError)):
raise
raise LLMUnavailable() from exc
async def call(self, request: dict[str, Any]) -> dict[str, Any]:
guard_messages(request)
payload = _json_bytes({"op": "call", "request": request})
if len(payload) > 1024 * 1024:
raise LLMFailure("InvalidModelRequest")
async with self.pending_lock:
# queue_size counts waiting calls, plus one actively running call.
if self.pending >= self.spec.limits.queue_size + 1:
raise LLMQueueFull("ModelQueueFull")
self.pending += 1
acquired = False
try:
async with asyncio.timeout(self.spec.limits.timeout_seconds):
async with self.rpc_lock:
acquired = True
if not self.ready:
raise LLMUnavailable("ModelUnavailable")
connection = self.connection
await asyncio.to_thread(connection.send_bytes, payload)
raw = await asyncio.to_thread(connection.recv_bytes, 65536)
result = json.loads(raw)
if not isinstance(result, dict) or not result.get("ok"):
raise LLMFailure("ModelFailure")
return validate_guard_result(result.get("value"), request["task"])
except TimeoutError:
if acquired:
await self.stop()
raise LLMFailure("ModelTimeout") from None
except asyncio.CancelledError:
if acquired:
await self.stop()
raise
except LLMFailure:
raise
except Exception:
if acquired:
await self.stop()
raise LLMUnavailable("ModelUnavailable") from None
finally:
async with self.pending_lock:
self.pending -= 1
@property
def ready(self) -> bool:
return self.process is not None and self.process.is_alive() and self.connection is not None
async def stop(self) -> None:
process, connection = self.process, self.connection
self.process = None
self.connection = None
# Terminate first to unblock any thread waiting on pipe reads. Never send
# a stop message on a pipe whose peer may be stuck in a long inference.
if process is not None:
if process.is_alive():
process.terminate()
await asyncio.to_thread(process.join, 1)
if process.is_alive():
process.kill()
await asyncio.to_thread(process.join, 1)
if connection is not None:
connection.close()
class LLMRegistry:
def __init__(self, settings: Settings):
self.settings = settings
self.specs = {model.id: model for model in settings.llm}
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
}
async def start(self) -> None:
started: list[LLMAdapter] = []
try:
for adapter in self.adapters.values():
await adapter.start()
started.append(adapter)
except Exception:
await asyncio.gather(*(adapter.stop() for adapter in started), return_exceptions=True)
raise
def describe_for(self, plugin_id: str) -> list[dict[str, Any]]:
plugin = self.plugins.get(plugin_id)
if plugin is None:
return []
return [self.adapters[model_id].describe() for model_id in plugin.llm.allow]
async def call(self, plugin_id: str, model_id: str, request: dict[str, Any]) -> dict[str, Any]:
plugin = self.plugins.get(plugin_id)
if plugin is None or model_id not in plugin.llm.allow:
raise LLMFailure()
adapter = self.adapters.get(model_id)
if adapter is None:
raise LLMUnavailable()
return await adapter.call(request)
async def stop(self) -> None:
await asyncio.gather(
*(adapter.stop() for adapter in self.adapters.values()), return_exceptions=True
)
+83
View File
@@ -0,0 +1,83 @@
"""Local Transformers model process; never imported into Lua workers."""
import json
from typing import Any
from .llm import _send, guard_messages, parse_guard_output
def guard_worker_main(
connection, model_path: str, load: dict[str, Any], limits: dict[str, Any]
) -> None:
"""Load one model and serve serialized requests until stopped."""
try:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
hub_options = {"local_files_only": True, "trust_remote_code": False}
if load.get("revision") is not None:
hub_options["revision"] = load["revision"]
tokenizer = AutoTokenizer.from_pretrained(
model_path,
**hub_options,
)
dtype_name = load.get("dtype", "auto")
torch_dtype = "auto" if dtype_name == "auto" else getattr(torch, dtype_name)
device = load.get("device", "cpu")
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch_dtype,
**hub_options,
)
model.to(device)
model.eval()
_send(connection, {"ok": True})
except Exception:
try:
_send(connection, {"ok": False, "error": "ModelLoadFailed"})
finally:
connection.close()
return
try:
while True:
command = json.loads(connection.recv_bytes(1024 * 1024).decode())
if command.get("op") == "stop":
return
if command.get("op") != "call":
_send(connection, {"ok": False, "error": "InvalidRequest"})
continue
try:
request = command["request"]
messages = guard_messages(request)
text = tokenizer.apply_chat_template(messages, tokenize=False)
inputs = tokenizer(
[text],
return_tensors="pt",
truncation=False,
)
if inputs["input_ids"].shape[1] > limits["max_input_tokens"]:
_send(connection, {"ok": False, "error": "ModelInputTooLong"})
continue
device = next(model.parameters()).device
inputs = {key: value.to(device) for key, value in inputs.items()}
with torch.inference_mode():
generated = model.generate(
**inputs,
max_new_tokens=limits["max_new_tokens"],
do_sample=False,
)
output_ids = generated[0][inputs["input_ids"].shape[1] :].tolist()
output = tokenizer.decode(output_ids, skip_special_tokens=True)
value = parse_guard_output(output)
from .llm import validate_guard_result
_send(
connection, {"ok": True, "value": validate_guard_result(value, request["task"])}
)
except Exception:
_send(connection, {"ok": False, "error": "ModelFailure"})
except (EOFError, OSError, ValueError, json.JSONDecodeError):
pass
finally:
connection.close()
+30 -1
View File
@@ -9,6 +9,7 @@ from uuid import uuid4
from .config import Settings
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
from .llm import LLMRegistry
from .network import NetworkBroker
from .worker import json_bytes, worker_main
@@ -91,6 +92,18 @@ class Session:
self.context["request_id"],
plugin,
)
elif result["kind"] == "llm":
payload = result["value"]
if (
not isinstance(payload, dict)
or set(payload) != {"model", "request"}
or not isinstance(payload["model"], str)
or not isinstance(payload["request"], dict)
):
raise PluginFailure()
reply["value"] = await self.manager.llm.call(
plugin, payload["model"], payload["request"]
)
else:
raise PluginFailure()
except Exception:
@@ -130,7 +143,14 @@ class Session:
for plugin_id, source in self.manager.sources.items():
if adapter_only and plugin_id != ADAPTER_ID:
continue
await self.rpc({"op": "load", "plugin": plugin_id, "source": source})
await self.rpc(
{
"op": "load",
"plugin": plugin_id,
"source": source,
"llm": self.manager.llm.describe_for(plugin_id),
}
)
self.initialized.append(plugin_id)
config = self.manager.plugins_by_id.get(plugin_id)
result = await self.invoke(plugin_id, "init", config.config if config else {})
@@ -263,12 +283,20 @@ class PluginManager:
+ 65536
)
self.broker = NetworkBroker()
self.llm = LLMRegistry(settings)
self.llm_started = False
self.sessions = set()
self.stopping = False
async def start(self):
if not self.llm_started:
await self.llm.start()
self.llm_started = True
async def open(self, request_id=None, adapter_only=False):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded()
await self.start()
session = Session(self, request_id)
self.sessions.add(session)
try:
@@ -304,3 +332,4 @@ class PluginManager:
async def shutdown(self):
self.stopping = True
await asyncio.gather(*(s.aclose() for s in list(self.sessions)), return_exceptions=True)
await self.llm.stop()
+13 -2
View File
@@ -17,7 +17,7 @@ def json_bytes(value) -> bytes:
class LuaPlugin:
def __init__(self, source: str, limits: dict, callback):
def __init__(self, source: str, limits: dict, callback, llm_models=None):
self.limits = limits
self.callback = callback
self.lua = LuaRuntime(
@@ -62,6 +62,15 @@ class LuaPlugin:
self.callback("http", self.to_python(request)),
)
host["http"] = http
llm = self.lua.table()
llm["list"] = lambda: self.to_lua(llm_models or [])
llm["call"] = lambda model, request: self.to_lua(
self.callback("llm", {"model": model, "request": self.to_python(request)})
)
metatable = self.lua.table()
metatable["__call"] = lambda _, model, request: llm["call"](model, request)
self.lua.eval("setmetatable")(llm, metatable)
host["llm"] = llm
log = self.lua.table()
for level in ("info", "warning", "error"):
# Deliberately discard caller-provided text; logs contain metadata only.
@@ -177,7 +186,9 @@ def worker_main(connection, limits: dict):
current = command.get("plugin")
try:
if command["op"] == "load":
plugins[current] = LuaPlugin(command["source"], limits, callback)
plugins[current] = LuaPlugin(
command["source"], limits, callback, command.get("llm", [])
)
result = None
elif command["op"] == "invoke":
result = plugins[current].invoke(