新增顶层 LLM 注册配置、插件授权列表和 guard 类型适配器。\n模型由独立 Python 进程加载,通过受限 IPC 为 Lua 提供 host.llm.list、host.llm.call 和可调用接口。\n增加 Qwen3Guard 结果解析、流式审核示例、可选依赖、Docker 构建文件和协议测试。
289 lines
10 KiB
Python
289 lines
10 KiB
Python
"""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
|
|
)
|