"""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 import aiohttp from .config import LLMConfig, Settings logger = logging.getLogger("middleware.audit") # Only fixed diagnostic labels may cross the startup IPC boundary or enter logs. MODEL_LOAD_STAGES = { "import_torch", "import_transformers", "load_tokenizer", "load_model", "move_to_device", "eval_model", } MODEL_LOAD_ERRORS = { "ModuleNotFoundError", "ImportError", "FileNotFoundError", "PermissionError", "OSError", "ValueError", "TypeError", "RuntimeError", "MemoryError", "SafetensorError", "OutOfMemoryError", } MODEL_DEPENDENCIES = {"torch", "transformers", "tokenizers", "safetensors", "numpy", "accelerate"} def model_load_diagnostic(result: dict[str, Any]) -> str: labels = [] for key, allowed in ( ("stage", MODEL_LOAD_STAGES), ("exception", MODEL_LOAD_ERRORS), ("dependency", MODEL_DEPENDENCIES), ): value = result.get(key) labels.append(f"{key}={value if isinstance(value, str) and value in allowed else 'unknown'}") return " ".join(labels) 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"(? 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("ModelDirectoryMissing") 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"): diagnostic = model_load_diagnostic(result) logger.error("model_load_failed model=%s %s", self.spec.id, diagnostic) raise LLMUnavailable(f"ModelLoadFailed {diagnostic}") 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 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 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: ( 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: 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 )