test_skills.py
11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""对话技能:登记校验、零件号出处(原话 / 最近聊天记录)、大模型不可用时的提示、定时补货只读、
技能开关 / 参数 / 提示词片段(后台接口)、对话参数、试聊、处理记录清理。"""
from __future__ import annotations
import datetime as dt
import pytest
from sqlalchemy import select
from app import features
from app.core import db
from app.features import AgentTool, Feature, guards, skills
from app.models import ai_prompts_t, ai_traces_t, notify_logs_t, runs_t
from app.services import agent, aitrace, audit, edge, msglog
from tests.test_restock_flow import FakeEdge, _fake_llm, group_msgs, say, settle, setup_store
@pytest.fixture()
def fake_edge(monkeypatch):
f = FakeEdge()
monkeypatch.setattr(edge, "run", f)
return f
# ---------------------------------------------------------------- 登记 / 校验
def test_registry(client):
assert [s.key for s in skills.all_skills()] == ["restock.single", "restock.scheduled"]
tools = {s.key: [t.name for t in s.tools()] for s in skills.all_skills()}
assert tools == {"restock.single": ["single_restock", "confirm_order", "submit_order", "cancel_order", "single_status"],
"restock.scheduled": ["scheduled_status", "scheduled_link"]}
async def h(*a, **kw):
return None
class Dup(Feature): # 只要名称 + 说明 + 工具就能登记;工具名不能和别的技能重复
key = "dup"
def skills(self):
return [skills.Skill(key="dup.x", feature="dup", name="x", description="x",
tools=lambda: [AgentTool("single_restock", "x", {}, h)])]
try:
with pytest.raises(RuntimeError, match="工具名 single_restock"):
skills.load([*features.FEATURES.values(), Dup()])
finally:
skills.load(features.FEATURES.values())
assert len(skills.all_skills()) == 2
def test_guards_from_text_and_history():
params = {"type": "object", "properties": {"part_no": {"type": "string", "x-from-text": True}, "qty": {}}}
assert guards.check_from_text(params, {"part_no": "8713902280"}, "帮我订 8713-902280 2个") == ""
assert guards.check_from_text(params, {"part_no": "8713902280"}, "那订 2 个", "[11-09 14:05] 助手:查到 8713902280") == ""
assert "都没有出现" in guards.check_from_text(params, {"part_no": "99999999"}, "那订 2 个", "查到 8713902280")
assert "x-from-text" not in str(guards.llm_schema(params))
def test_guards_qty_from_sentence():
"""数量必须是这句话里说过的:不能沿用聊天记录里的数字,更不能让模型自己假设。"""
params = {"type": "object", "properties": {"part_no": {"type": "string", "x-from-text": True},
"qty": {"type": "integer", "x-from-sentence": True}}}
ok = lambda text, qty: guards.check_from_text(params, {"part_no": "8713902280", "qty": qty}, text, "查到 8713902280") == "" # noqa: E731
for text, qty in (("8713902280 2个", 2), ("帮我定:8713902280*2", 2), ("8713902280 x10", 10), ("那订两个", 2),
("来十二个", 12), ("订 3 个", 3), ("041520V010×5", 5)):
assert ok(text, qty), (text, qty)
for text, qty in (("订", 1), ("那就订吧", 2), ("8713902280", 0 + 8), ("订 20 个", 2)):
assert not ok(text, qty), (text, qty)
assert "reply_text 问对方" in guards.check_from_text(params, {"part_no": "8713902280", "qty": 1}, "订", "查到 8713902280")
# ---------------------------------------------------------------- 大模型不可用
def test_llm_unavailable_no_tools(client, admin, outbox, fake_edge, monkeypatch):
"""大模型不可用:只回「暂时不可用」,不执行任何工具(不会靠规则绕过大模型去补货)。"""
k = setup_store(client, admin)
k.heartbeat()
monkeypatch.setattr(agent, "llm_ready", lambda: "没有配置大模型 API Key")
d = say(k, "8713902280 2个")
assert d["result"] == "llm_unavailable" and d["calls"] == []
assert "暂时不可用" in group_msgs(k, outbox)[-1] and fake_edge.calls == []
assert k.svc().single_open(k.store_id) is None
async def boom(system, user, tools, call):
raise TimeoutError("超时")
monkeypatch.setattr(agent, "llm_ready", lambda: "")
_fake_llm(monkeypatch, boom)
d = say(k, "8713902280 2个")
assert d["result"] == "llm_unavailable" and "超时" in d["llm_error"] and "暂时不可用" in group_msgs(k, outbox)[-1]
assert fake_edge.calls == []
def test_tool_name_as_text(client, admin, outbox, fake_edge, monkeypatch):
"""模型把工具名当回复文字输出:不带参数的工具照调;要参数的不猜。工具名永远不会发到群里。"""
k = setup_store(client, admin)
async def name_only(system, user, tools, call):
return "scheduled_status"
_fake_llm(monkeypatch, name_only)
d = say(k, "今天的补货推了吗")
assert d["calls"][0]["tool"] == "scheduled_status" and d["result"] == "tool"
assert "定时补货还没开始" in group_msgs(k, outbox)[-1]
async def name_with_args(system, user, tools, call):
return "`single_restock`"
_fake_llm(monkeypatch, name_with_args)
d = say(k, "帮我订那个")
assert not d["calls"] and d["result"] == "refused" and "single_restock" not in group_msgs(k, outbox)[-1]
# ---------------------------------------------------------------- 零件号出处:只认看得见的聊天记录
def test_part_no_only_from_visible_history(client, admin, outbox, fake_edge, monkeypatch):
"""零件号只认原话和给模型看的最近 N 条:报价滑出窗口后,「那订 2 个」不再放行(没有时间窗口)。"""
k = setup_store(client, admin)
k.heartbeat()
client.put("/api/assistant/settings", json={"values": {"history_limit": 2}}, headers=admin)
say(k, "8713902280 2个")
settle(k)
say(k, "不订")
say(k, "你好")
say(k, "你能做什么")
async def order(system, user, tools, call):
await call(*tools["single_restock"], {"part_no": "8713902280", "qty": 2})
return "__NO_REPLY__"
_fake_llm(monkeypatch, order)
d = say(k, "那订 2 个")
assert d["calls"][0]["blocked"] == "from_text" and k.svc().single_open(k.store_id) is None
# ---------------------------------------------------------------- 定时补货:群里只读
def test_scheduled_skill_read_only(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
k.heartbeat()
say(k, "今天定时补货到哪了")
assert "定时补货还没开始" in group_msgs(k, outbox)[-1]
d = say(k, "帮我把定时补货确认一下")
assert d["calls"][0]["tool"] == "scheduled_link" and "不能在群里发起" in group_msgs(k, outbox)[-1]
assert fake_edge.calls == [] and not db.rows(select(runs_t))
d = say(k, "我那单到哪了") # 本会话没有单次补货:说整体进度
assert d["calls"][0]["tool"] == "single_status" and "定时补货还没开始" in group_msgs(k, outbox)[-1]
say(k, "8713902280 2个")
settle(k)
say(k, "我那单到哪了")
assert "本会话的单次补货" in group_msgs(k, outbox)[-1] and "回「订」建单" in group_msgs(k, outbox)[-1]
# ---------------------------------------------------------------- 后台:技能开关 / 参数 / 提示词
def test_skill_settings_api(client, admin, kit):
r = client.get("/api/assistant/skills", headers=admin).json()["skills"]
single = next(s for s in r if s["key"] == "restock.single")
assert single["active"] and single["config"]["max_qty"] == 500 and "risk" not in single
assert single["schema"]["properties"]["max_qty"]["unit"] == "件"
assert client.put("/api/assistant/skills/restock.single", json={"config": {"max_qty": 0}},
headers=admin).status_code == 400
r = client.put("/api/assistant/skills/restock.single", json={"enabled": False, "config": {"max_qty": 8}},
headers=admin).json()
assert not r["active"] and r["config"]["max_qty"] == 8
p = agent.system_prompt(kit.store_id)
assert "single_restock" not in p and "【单次补货】" not in p and "scheduled_status" in p and "【定时补货】" in p
assert "单次补货" not in agent.refuse_text(kit.store_id)
assert audit.query(store_ids=[kit.store_id], action="assistant.skill.update", limit=1)[1]
r = client.put("/api/assistant/skills/restock.scheduled", json={"prompt": "测试片段 {{ persona.name }}"},
headers=admin).json()
assert r["prompt"]["changed"] and "测试片段" in agent.system_prompt(kit.store_id)
r = client.put("/api/assistant/skills/restock.scheduled", json={"prompt": ""}, headers=admin).json()
assert not r["prompt"]["changed"]
assert client.put("/api/assistant/skills/nope", json={}, headers=admin).status_code == 404
def test_single_disabled_and_max_qty(client, admin, outbox, fake_edge):
k = setup_store(client, admin)
k.heartbeat()
client.put("/api/assistant/skills/restock.single", json={"config": {"max_qty": 5}}, headers=admin)
say(k, "8713902280 6个")
assert "超过单次补货上限 5 个" in group_msgs(k, outbox)[-1]
client.put("/api/assistant/skills/restock.single", json={"enabled": False}, headers=admin)
d = say(k, "8713902280 2个") # 技能停用:大模型看不到它的工具
assert "single_restock" not in d["tools"] and not d["calls"]
settle(k)
assert k.svc().single_open(k.store_id) is None
def test_assistant_dialog_params(client, admin, kit):
r = client.put("/api/assistant/settings", json={"values": {"history_limit": 50}}, headers=admin)
assert r.status_code == 200 and r.json()["values"]["history_limit"] == 50 and "max_iters" not in r.json()["values"]
assert agent.history_limit() == 50
for bad in ({"history_limit": 51}, {"history_limit": 0}, {"history_chars": 99}):
assert client.put("/api/assistant/settings", json={"values": bad}, headers=admin).status_code == 400, bad
# ---------------------------------------------------------------- 处理记录:提示词去重 + 按天清理
def test_trace_prompt_dedup_and_purge(client, admin, kit):
say(kit, "你好")
say(kit, "你能做什么")
traces = db.rows(select(ai_traces_t))
assert len(traces) == 2 and traces[0]["prompt_id"] == traces[1]["prompt_id"] # 同样的提示词只存一份
assert len(db.rows(select(ai_prompts_t))) == 1
old = db.now() - dt.timedelta(days=40)
db.q(ai_traces_t.update().where(ai_traces_t.c.id == traces[0]["id"]).values(ts=old))
db.q(notify_logs_t.update().where(notify_logs_t.c.id == traces[0]["log_id"]).values(ts=old - dt.timedelta(days=200)))
assert aitrace.purge(30) == 1 and len(db.rows(select(ai_traces_t))) == 1
assert len(db.rows(select(ai_prompts_t))) == 1 # 还有记录在用,提示词保留
assert msglog.purge(180) == 1
assert not db.rows(select(notify_logs_t).where(notify_logs_t.c.id == traces[0]["log_id"]))
db.q(ai_traces_t.update().values(ts=old))
assert aitrace.purge(30) == 1 and not db.rows(select(ai_prompts_t))