feat(LLM): 增加可扩展模型插件能力
新增顶层 LLM 注册配置、插件授权列表和 guard 类型适配器。\n模型由独立 Python 进程加载,通过受限 IPC 为 Lua 提供 host.llm.list、host.llm.call 和可调用接口。\n增加 Qwen3Guard 结果解析、流式审核示例、可选依赖、Docker 构建文件和协议测试。
This commit is contained in:
1 parent
8c1d243b51
commit
b331927773
11 files changed
+693
-4
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user