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

+11
View File
@@ -0,0 +1,11 @@
FROM python:3.13-slim
WORKDIR /service
COPY pyproject.toml ./
COPY middleware ./middleware
RUN pip install --no-cache-dir ".[guard]"
COPY config.yaml ./
COPY plugins ./plugins
ENV HF_HUB_OFFLINE=1
USER 65532:65532
EXPOSE 8080
CMD ["agent-safe-middleware", "--config", "/service/config.yaml"]
+1
View File
@@ -12,6 +12,7 @@ limits:
max_plugin_buffer_bytes: 1048576 max_plugin_buffer_bytes: 1048576
max_host_calls_per_hook: 64 max_host_calls_per_hook: 64
upstream_timeout_seconds: 120 upstream_timeout_seconds: 120
llm: []
plugins: plugins:
- id: request-rewrite - id: request-rewrite
file: plugins/request_rewrite.lua file: plugins/request_rewrite.lua
+45
View File
@@ -80,3 +80,48 @@ local result = host.http.request({
`host.log.info(...)`、`warning(...)`、`error(...)` 只生成固定的插件日志标记,不保存文本参数。每钩子最多 64 次宿主调用,限制可配置;日志和 HTTP 都计数。 `host.log.info(...)`、`warning(...)`、`error(...)` 只生成固定的插件日志标记,不保存文本参数。每钩子最多 64 次宿主调用,限制可配置;日志和 HTTP 都计数。
模块加载及所有钩子都有超时与内存限制;配置修改后重启生效,不提供热加载或长期跨请求状态。业务规则应有正常对照测试,避免关键词规则把合法的安全研究或引用内容误判为攻击。 模块加载及所有钩子都有超时与内存限制;配置修改后重启生效,不提供热加载或长期跨请求状态。业务规则应有正常对照测试,避免关键词规则把合法的安全研究或引用内容误判为攻击。
## Python LLM capability
The optional `guard` dependency (`pip install -e ".[guard]"`) enables local Transformers guard models. Model definitions live at the top level and plugins explicitly allow model IDs:
```yaml
llm:
- id: Qwen3Guard-Gen-0.6B
type: guard
backend: transformers
file: /models/Qwen3Guard-Gen-0.6B
enabled: true
load:
device: cpu
dtype: bfloat16
revision: "fixed-model-revision"
limits:
max_input_tokens: 4096
max_new_tokens: 32
timeout_seconds: 3
queue_size: 8
plugins:
- id: response-guard
file: plugins/response_guard.lua
llm:
allow: [Qwen3Guard-Gen-0.6B]
config:
model: Qwen3Guard-Gen-0.6B
```
A Lua plugin receives only the authorized model metadata:
```lua
for _, model in ipairs(host.llm.list()) do
-- model.id, model.type, model.capabilities
end
local result = host.llm("Qwen3Guard-Gen-0.6B", {
task = "response_moderation",
prompt = prompt,
response = text,
})
-- result = {safety="Safe|Controversial|Unsafe", categories={}, refusal="Yes|No|nil"}
```
`host.llm.call(id, request)` is equivalent to the callable form. Calls are synchronous from Lua, serialized per model, and executed in a separate Python process. The worker is started before `/readyz` becomes ready. Model failures are returned as capability failures; plugins should fail closed (the example `response_guard.lua` blocks on a failed moderation call). The model worker is local-only and does not download weights at request time.
+49 -1
View File
@@ -1,5 +1,6 @@
import ipaddress import ipaddress
from pathlib import Path from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit from urllib.parse import urlsplit
import yaml import yaml
@@ -80,12 +81,41 @@ class NetworkPolicy(Model):
max_response_bytes: int = Field(default=1024 * 1024, gt=0) 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): class PluginConfig(Model):
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
file: Path file: Path
enabled: bool = True enabled: bool = True
config: dict = Field(default_factory=dict) config: dict = Field(default_factory=dict)
network: NetworkPolicy = Field(default_factory=NetworkPolicy) network: NetworkPolicy = Field(default_factory=NetworkPolicy)
llm: PluginLLMAccess = Field(default_factory=PluginLLMAccess)
class Limits(Model): class Limits(Model):
@@ -105,6 +135,7 @@ class Settings(Model):
listen_host: str = "0.0.0.0" listen_host: str = "0.0.0.0"
listen_port: int = Field(default=8080, ge=1, le=65535) listen_port: int = Field(default=8080, ge=1, le=65535)
limits: Limits = Field(default_factory=Limits) limits: Limits = Field(default_factory=Limits)
llm: list[LLMConfig] = Field(default_factory=list)
plugins: list[PluginConfig] = Field(default_factory=list) plugins: list[PluginConfig] = Field(default_factory=list)
@field_validator("upstream") @field_validator("upstream")
@@ -123,6 +154,17 @@ class Settings(Model):
ids = [p.id for p in self.plugins] ids = [p.id for p in self.plugins]
if len(ids) != len(set(ids)): if len(ids) != len(set(ids)):
raise ValueError("duplicate plugin 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 return self
@@ -137,4 +179,10 @@ def load_settings(path: str | Path) -> Settings:
if not file.is_file(): if not file.is_file():
raise ValueError(f"plugin file not found: {plugin.id}") raise ValueError(f"plugin file not found: {plugin.id}")
plugins.append(plugin.model_copy(update={"file": file})) 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 .config import Settings
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
from .llm import LLMRegistry
from .network import NetworkBroker from .network import NetworkBroker
from .worker import json_bytes, worker_main from .worker import json_bytes, worker_main
@@ -91,6 +92,18 @@ class Session:
self.context["request_id"], self.context["request_id"],
plugin, 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: else:
raise PluginFailure() raise PluginFailure()
except Exception: except Exception:
@@ -130,7 +143,14 @@ class Session:
for plugin_id, source in self.manager.sources.items(): for plugin_id, source in self.manager.sources.items():
if adapter_only and plugin_id != ADAPTER_ID: if adapter_only and plugin_id != ADAPTER_ID:
continue 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) self.initialized.append(plugin_id)
config = self.manager.plugins_by_id.get(plugin_id) config = self.manager.plugins_by_id.get(plugin_id)
result = await self.invoke(plugin_id, "init", config.config if config else {}) result = await self.invoke(plugin_id, "init", config.config if config else {})
@@ -263,12 +283,20 @@ class PluginManager:
+ 65536 + 65536
) )
self.broker = NetworkBroker() self.broker = NetworkBroker()
self.llm = LLMRegistry(settings)
self.llm_started = False
self.sessions = set() self.sessions = set()
self.stopping = False 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): async def open(self, request_id=None, adapter_only=False):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions: if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded() raise Overloaded()
await self.start()
session = Session(self, request_id) session = Session(self, request_id)
self.sessions.add(session) self.sessions.add(session)
try: try:
@@ -304,3 +332,4 @@ class PluginManager:
async def shutdown(self): async def shutdown(self):
self.stopping = True self.stopping = True
await asyncio.gather(*(s.aclose() for s in list(self.sessions)), return_exceptions=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: 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.limits = limits
self.callback = callback self.callback = callback
self.lua = LuaRuntime( self.lua = LuaRuntime(
@@ -62,6 +62,15 @@ class LuaPlugin:
self.callback("http", self.to_python(request)), self.callback("http", self.to_python(request)),
) )
host["http"] = http 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() log = self.lua.table()
for level in ("info", "warning", "error"): for level in ("info", "warning", "error"):
# Deliberately discard caller-provided text; logs contain metadata only. # Deliberately discard caller-provided text; logs contain metadata only.
@@ -177,7 +186,9 @@ def worker_main(connection, limits: dict):
current = command.get("plugin") current = command.get("plugin")
try: try:
if command["op"] == "load": if command["op"] == "load":
plugins[current] = LuaPlugin(command["source"], limits, callback) plugins[current] = LuaPlugin(
command["source"], limits, callback, command.get("llm", [])
)
result = None result = None
elif command["op"] == "invoke": elif command["op"] == "invoke":
result = plugins[current].invoke( result = plugins[current].invoke(
+53
View File
@@ -0,0 +1,53 @@
local plugin = {}
local config = {}
local prompt = ""
local pending = {}
local text = ""
function plugin.init(ctx, options)
config = options
end
function plugin.on_request(ctx, request)
local body = host.json.decode(request.body)
prompt = body.message or ""
end
local function check_and_release()
if #pending == 0 then return nil end
local ok, result = pcall(host.llm.call, config.model, {
task = "response_moderation",
prompt = prompt,
response = text,
})
if not ok or result.safety == "Unsafe" then
return {action = "block"}
end
local released = host.json.array(pending)
pending = {}
text = ""
return {action = "replace", events = released}
end
function plugin.on_event(ctx, event)
if event.event ~= "text_delta" then return nil end
local data = host.json.decode(event.data)
local content = data.data and data.data.content or ""
pending[#pending + 1] = event
text = text .. content
if text:match("[。!?.!?]\s*$") then
return check_and_release()
end
return {action = "hold"}
end
function plugin.on_end(ctx)
return check_and_release()
end
function plugin.close(ctx)
pending = {}
text = ""
end
return plugin
+1
View File
@@ -17,6 +17,7 @@ dependencies = [
[project.optional-dependencies] [project.optional-dependencies]
dev = ["pytest>=8,<10", "pytest-asyncio>=1,<2", "httpx>=0.28,<1", "ruff>=0.14,<1"] dev = ["pytest>=8,<10", "pytest-asyncio>=1,<2", "httpx>=0.28,<1", "ruff>=0.14,<1"]
guard = ["torch>=2.2", "transformers>=4.51,<5"]
[project.scripts] [project.scripts]
agent-safe-middleware = "middleware.cli:main" agent-safe-middleware = "middleware.cli:main"
+119
View File
@@ -0,0 +1,119 @@
import pytest
from pydantic import ValidationError
from middleware.config import LLMConfig, PluginConfig, PluginLLMAccess, Settings
from middleware.llm import LLMFailure, LLMRegistry, parse_guard_output
from middleware.runtime import PluginManager
def settings_for(tmp_path, source, allow=None):
file = tmp_path / "plugin.lua"
file.write_text(source, encoding="utf-8")
return Settings(
upstream="http://agent",
llm=[LLMConfig(id="guard", type="guard", file=tmp_path)],
plugins=[
PluginConfig(id="plugin", file=file, llm=PluginLLMAccess(allow=allow or ["guard"]))
],
)
@pytest.mark.parametrize(
("content", "expected"),
[
("Safety: Safe\nCategories: None", {"safety": "Safe", "categories": [], "refusal": None}),
(
"Safety: Unsafe\nCategories: Violent\nRefusal: No",
{"safety": "Unsafe", "categories": ["Violent"], "refusal": "No"},
),
(
"Safety: Controversial\nCategories: PII\nRefusal: Yes",
{"safety": "Controversial", "categories": ["PII"], "refusal": "Yes"},
),
],
)
def test_parse_guard_output(content, expected):
assert parse_guard_output(content) == expected
@pytest.mark.parametrize("content", ["oops", "Safety: Safe", "Safety: Safe\nCategories: Unknown"])
def test_bad_guard_output(content):
with pytest.raises(LLMFailure):
parse_guard_output(content)
def test_configuration_validation(tmp_path):
plugin = PluginConfig(id="p", file=tmp_path, llm=PluginLLMAccess(allow=["missing"]))
with pytest.raises(ValidationError):
Settings(upstream="http://agent", plugins=[plugin])
with pytest.raises(ValidationError):
LLMConfig(id="bad", type="chat", file=tmp_path)
model = LLMConfig(id="g", type="guard", file=tmp_path)
with pytest.raises(ValidationError):
Settings(upstream="http://agent", llm=[model, model])
disabled = model.model_copy(update={"enabled": False})
plugin = plugin.model_copy(update={"llm": PluginLLMAccess(allow=["g"])})
with pytest.raises(ValidationError):
Settings(upstream="http://agent", llm=[disabled], plugins=[plugin])
class FakeAdapter:
def __init__(self):
self.started = 0
self.calls = []
async def start(self):
self.started += 1
async def stop(self):
pass
def describe(self):
return {"id": "guard", "type": "guard", "capabilities": ["prompt_moderation"]}
async def call(self, request):
self.calls.append(request)
return {"safety": "Safe", "categories": [], "refusal": None}
async def test_registry_authorization_and_single_adapter(tmp_path):
settings = settings_for(tmp_path, "return {}")
registry = LLMRegistry(settings)
fake = FakeAdapter()
registry.adapters["guard"] = fake
await registry.start()
assert registry.describe_for("plugin") == [fake.describe()]
assert registry.describe_for("unknown") == []
assert (await registry.call("plugin", "guard", {"task": "prompt_moderation", "prompt": "x"}))[
"safety"
] == "Safe"
with pytest.raises(LLMFailure):
await registry.call("unknown", "guard", {})
assert fake.started == 1
await registry.stop()
async def test_lua_llm_list_call_and_callable(tmp_path):
settings = settings_for(
tmp_path,
"""
return {on_request=function(ctx, request)
local models=host.llm.list()
assert(#models==1 and models[1].id=='guard')
local input={task='prompt_moderation',prompt='x'}
assert(host.llm.call('guard',input).safety=='Safe')
assert(host.llm('guard',input).safety=='Safe')
return {action='pass'}
end}
""",
)
manager = PluginManager(settings)
fake = FakeAdapter()
manager.llm.adapters["guard"] = fake
session = await manager.open()
try:
assert await session.apply("on_request", {"body": "x"}) == [{"body": "x"}]
assert len(fake.calls) == 2
finally:
await session.aclose()
await manager.shutdown()