Files
starrrLight 1ad508c413 fix(运行时): 要求会话提供请求路径
普通插件会话必须显式传入请求路径,启动全量校验和协议错误适配器保留专用入口。同步更新运行时测试调用。
2026-10-15 15:59:03 +08:00

120 lines
4.1 KiB
Python

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(path="/chat/stream")
try:
assert await session.apply("on_request", {"body": "x"}) == [{"body": "x"}]
assert len(fake.calls) == 2
finally:
await session.aclose()
await manager.shutdown()