test_agents.py
19 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""多智能体提问与经验中枢:主 Agent 分派 → 子 Agent 并行调工具(经 MCP)→ 行动建议 → 作答;
轨迹落库与回放、中断的轮次、案例沉淀与快路径、点赞晋升 SQL、纠错回流、操作习惯。
LLM 全部打桩:按系统提示词里的角色分辨是哪个 Agent 在说话。
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parent))
from app.core import llm # noqa: E402
from test_platform import as_user, build_basics, env, make_action # noqa: E402,F401
def _say(thought: str, obj: dict):
yield "思考:"
for i in range(0, len(thought), 4): # 逐字吐,验证思考流式拆分
yield thought[i:i + 4]
yield "\n``" # 故意把代码块标记切成两半
yield "`json\n" + json.dumps(obj, ensure_ascii=False) + "\n```"
class FakeLLM:
"""按角色回话。lead / agent / action / answer / reflect 各自可替换。"""
def __init__(self, lead: dict, answer: str = "好的。", action: dict | None = None,
agent_final: dict | None = None, reflect: dict | None = None):
self.lead = lead
self.answer = answer
self.action = action or {"suggest_actions": [], "suggest_sops": []}
self.agent_final = agent_final or {"final": {"summary": "查到了", "findings": ["网点 1 最高"],
"insights": ["网点 1 占比最高"], "confidence": 0.9}}
self.reflect = reflect or {"sufficient": True}
self.calls: list[str] = []
self.prompts: dict[str, str] = {}
def stream(self, msgs, **k):
sys_ = msgs[0]["content"] if msgs else ""
user = msgs[-1]["content"]
if "负责理解问题、分派给专业子 Agent" in sys_:
self.calls.append("lead")
self.prompts["lead"] = sys_ + user
yield from _say("先取数,再看要不要处理。", self.lead)
elif "子 Agent 已经汇报了结果" in sys_:
self.calls.append("reflect")
yield from _say("信息够了。", self.reflect)
elif "你接到主 Agent 分派的任务" in sys_:
self.calls.append("agent")
yield from _say("结果已经能回答任务。", self.agent_final)
elif "「行动 Agent」" in sys_:
self.calls.append("action")
yield from _say("网点偏低,建议标记重点跟进。", self.action)
else:
self.calls.append("answer")
self.prompts["answer"] = user
text = self.answer
m = re.search(r"数据编号 run:(\d+)", user)
text = text.replace("{run}", m.group(1) if m else "0")
yield text
@pytest.fixture()
def agents_env(env, monkeypatch):
from app.memory import service as memory
def no_embed(*a, **k):
raise RuntimeError("测试环境没有向量服务")
monkeypatch.setattr(llm, "embed", no_embed)
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: {"facts": []})
# 沉淀同步做,好断言
monkeypatch.setattr(memory, "learn_async", lambda tid: memory.learn(tid))
return env
def _fake(monkeypatch, **kw) -> FakeLLM:
f = FakeLLM(**kw)
monkeypatch.setattr(llm, "chat_stream", f.stream)
return f
DATA_PLAN = {"intent": "action", "rewrite": "各网点成交金额,偏低的标记跟进", "delegations": [
{"agent": "data", "task": "取各网点成交金额",
"calls": [{"tool": "metric.query", "args": {"metric": "成交金额", "dimensions": ["网点"]}, "why": "取数"},
{"tool": "object.write", "args": {}, "why": "越权"}]},
{"agent": "action", "task": "偏低的给出动作"}],
"follow_ups": ["按品牌拆开看"]}
def test_多智能体_分派并行_经MCP_思考流式_动作建议(agents_env, monkeypatch):
from app.agents import lead
from app.capability import actions
from app.governance import audit
b = build_basics(agents_env["ds_id"])
make_action(b["ot"]["id"])
f = _fake(monkeypatch, lead=DATA_PLAN, answer="**网点 1 成交最高** [^run:{run}]。",
action={"suggest_actions": [{"action": "mark_follow", "params": {"reason": "偏低"},
"object_key": "2", "reason": "成交偏低"}]})
events = list(lead.run("各网点成交金额,偏低的怎么办"))
types = [e["type"] for e in events]
assert types[0] == "start" and types[-1] == "done"
# 思考是逐字推出来的,不是一次性
assert sum(1 for e in events if e["type"] == "thought" and e["span"] == "lead") > 2
# 越权工具被拒绝,不会执行;合法工具经 MCP 执行、审计来源标到子 Agent
done = [e for e in events if e["type"] == "tool_done"]
assert sorted((e["tool"], e["ok"]) for e in done) == [("object.write", False), ("query_metric", True)]
logs = audit.query(event="mcp.call", full=True)["items"]
assert [x["after"]["via"] for x in logs] == ["ask:data"]
agents = [e["agent"] for e in events if e["type"] == "agent_start"]
assert agents == ["lead", "data", "action"]
ans = next(e for e in events if e["type"] == "answer")
assert ans["data_refs"] and ans["data_refs"][0]["cited"]
assert ans["actions"][0]["preview"]["effects"][0]["tool"] == "object.write"
assert ans["follow_ups"] == ["按品牌拆开看"]
assert "query_metric" in [x["call"] for x in ans["plan"]["steps"]] # 评测按它判调用
assert actions.list_runs() == [] # 只建议,不提议
assert "网点 1 占比最高" in f.prompts["answer"] # 子 Agent 的解读交给作答
# 轨迹完整落库:思考合并成整段,逐字作答不存
tr = lead.session.get_trace(ans["turn_id"])
kinds = [e["type"] for e in tr["events"]]
assert "answer_delta" not in kinds and kinds.count("tool_done") == 2
lead_thoughts = [e for e in tr["events"] if e["type"] == "thought" and e["span"] == "lead"]
assert len(lead_thoughts) == 1 and lead_thoughts[0]["text"] == "先取数,再看要不要处理。"
assert tr["stats"]["tools"] == 2 and tr["stats"]["agents"] == 3
def test_停止的轮次_打开历史不崩_状态为已中断(agents_env, monkeypatch):
from app.agents import lead, session
build_basics(agents_env["ds_id"])
_fake(monkeypatch, lead=DATA_PLAN)
gen = lead.run("各网点成交金额")
first = next(gen)
assert first["type"] == "start"
assert lead.stop_turn(first["turn_id"]) # 用户点「停止」
gen.close()
# 等工作线程收尾:它不等的话会在本用例结束、测试库拆掉之后还在跑,把调用落到真实库里
assert lead.wait_worker(first["turn_id"])
conv = session.get_conversation(first["conversation_id"])
t = conv["turns"][0]
assert t["status"] == "aborted"
assert isinstance(t["links"]["concepts"], list) and isinstance(t["links"]["instances"], list)
assert isinstance(t["steps"], list) and isinstance(t["data_refs"], list)
def test_切走页面_断开连接_回答在后台照常跑完(agents_env, monkeypatch):
from app.agents import lead, session
build_basics(agents_env["ds_id"])
_fake(monkeypatch, lead=DATA_PLAN)
gen = lead.run("各网点成交金额")
first = next(gen)
gen.close() # 听事件的一端没了(切到别的页面 / 断网),不是点了停止
assert lead.wait_worker(first["turn_id"], 60)
t = session.get_conversation(first["conversation_id"])["turns"][0]
assert t["status"] == "done" and t["answer"]
assert lead.stop_turn(first["turn_id"]) is False # 已经跑完,没有可停的
def test_闲聊不分派_追问直接返回(agents_env, monkeypatch):
from app.agents import lead
_fake(monkeypatch, lead={"intent": "chitchat", "delegations": []}, answer="你好")
out = lead.run_collect("你好")
assert out["answer"] == "你好" and out["plan"]["delegations"] == []
_fake(monkeypatch, lead={"intent": "data", "delegations": [], "clarify": "要看哪个月?"})
out = lead.run_collect("销售额")
assert out["answer"] == "要看哪个月?" and out["clarify"]
def test_子Agent失败时主Agent反思并追加分派(agents_env, monkeypatch):
from app.agents import lead
build_basics(agents_env["ds_id"])
plan = {"intent": "data", "delegations": [
{"agent": "data", "task": "取数", "calls": [{"tool": "query_metric", "args": {"metric": "不存在"}}]}]}
f = _fake(monkeypatch, lead=plan, agent_final={"final": {"summary": "没取到", "confidence": 0.1}},
reflect={"sufficient": False, "missing": "指标名写错",
"delegations": [{"agent": "data", "task": "换成成交金额",
"calls": [{"tool": "query_metric", "args": {"metric": "成交金额"}}]}]})
# 这类单指标问题现在走快车道;这里要测的是多智能体那条路,把快车道关掉
monkeypatch.setattr("app.agents.router.route", lambda *a, **k: None)
events = list(lead.run("成交金额是多少"))
assert "reflect" in f.calls
rf = next(e for e in events if e["type"] == "reflect")
assert rf["sufficient"] is False
done = [(e["tool"], e["ok"]) for e in events if e["type"] == "tool_done"]
assert done == [("query_metric", False), ("query_metric", True)]
def test_经验沉淀_点赞晋升_相似问题走快路径(agents_env, monkeypatch):
from app.agents import lead, session
from app.memory import service as memory
from app.text2sql import library
build_basics(agents_env["ds_id"])
plan = {"intent": "data", "delegations": [
{"agent": "data", "task": "取数", "calls": [{"tool": "data_ask", "args": {"question": "各网点成交金额"}}]}]}
# 这类单指标问题现在走快车道;这里要测的是多智能体那条路,把快车道关掉
monkeypatch.setattr("app.agents.router.route", lambda *a, **k: None)
f = _fake(monkeypatch, lead=plan, answer="网点 1 最高 [^run:{run}]")
# data_ask 走 SQL 路时要写 SQL:打桩成固定 SQL
from app.text2sql import pipeline
def fake_run_ask(ds_id, q, history=None, summarize=False):
from app.text2sql import library as lib
yield {"type": "execute", "sql": "SELECT store_id, SUM(amount) FROM order_item GROUP BY store_id"}
yield {"type": "rows", "columns": ["store_id", "amt"], "rows": [[1, 900.0]]}
pid = lib.capture(ds_id, q, "SELECT store_id, SUM(amount) FROM order_item GROUP BY store_id", run_id=42)
yield {"type": "done", "run_id": 42, "outcome": "ok", "pair_id": pid}
monkeypatch.setattr(pipeline, "run_ask", fake_run_ask)
out = lead.run_collect("各网点成交金额分别是多少")
cases = memory.list_cases()
assert len(cases) == 1 and cases[0]["status"] == "draft"
assert cases[0]["plan"]["delegations"][0]["agent"] == "data"
# 点赞:案例升为已验证,这轮用到的问数 SQL 晋升为 verified
fb = session.feedback(out["turn_id"], 1)
assert fb["learned"]["case"]["status"] == "verified"
assert library.list_pairs(status="verified")[0]["origin_run_id"] == 42
# 同样的问题再问:召回案例、直接复用路径,不再调主 Agent 规划
f.calls.clear()
events = list(lead.run("各网点成交金额分别是多少?"))
mem = next(e for e in events if e["type"] == "memory")
assert mem["fast"] == cases[0]["id"]
assert "lead" not in f.calls
plan_ev = next(e for e in events if e["type"] == "plan")
assert plan_ev["from_case"] == cases[0]["id"]
assert memory.list_cases()[0]["fast_hits"] == 1
# 点踩两次:案例作废,点赞晋升的 SQL 退回草稿
t2 = next(e for e in events if e["type"] == "answer")["turn_id"]
session.feedback(t2, -1, "不对")
session.feedback(out["turn_id"], -1, "还是不对")
assert memory.list_cases()[0]["status"] in ("draft", "deprecated")
assert not library.list_pairs(status="verified")
def test_记忆_mem0式合并_偏好直接生效_口径要审核(agents_env, monkeypatch):
from app.governance import review
from app.memory import service as memory
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: {"facts": [
{"text": "我只看华东区的数据", "kind": "preference"},
{"text": "缺货指可用库存低于安全库存", "kind": "definition"}]})
out = memory.extract_facts("以后我只看华东区;缺货指可用库存低于安全库存")
by = {f["kind"]: f for f in out}
assert by["preference"]["status"] == "active" and by["preference"]["scope"] == "user"
assert by["definition"]["status"] == "pending"
item = review.list_items(kind="memory_fact")["items"][0]
review.decide(item["id"], True)
assert memory.list_facts(status="active", kind="definition")[0]["text"].startswith("缺货")
# 同一件事换了说法:模型判为 UPDATE,不新增重复记忆
calls = iter([{"facts": [{"text": "我只看华东区和华南区的数据", "kind": "preference"}]},
{"ops": [{"new": 0, "op": "UPDATE", "id": by["preference"]["id"],
"text": "我只看华东区和华南区的数据"}]}])
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: next(calls))
memory.extract_facts("我现在也看华南区了")
prefs = memory.list_facts(kind="preference")
assert len(prefs) == 1 and "华南" in prefs[0]["text"]
# 召回时个人偏好总会带上
rec = memory.recall("上个月销售额")
assert any("华南" in x["text"] for x in rec["facts"])
def test_纠错采纳_回流记忆同义词与评测用例(agents_env, monkeypatch):
from app.agents import lead, session
from app.evals import service as evals
from app.governance import review
from app.kernel import service as ksvc
build_basics(agents_env["ds_id"])
_fake(monkeypatch, lead={"intent": "chitchat", "delegations": []}, answer="不知道")
out = lead.run_collect("营业额是多少")
fb = session.feedback(out["turn_id"], -1, "营业额就是成交金额", "营业额即成交金额")
monkeypatch.setattr(llm, "chat_json", lambda *a, **k: {
"facts": [{"text": "营业额即成交金额", "kind": "definition"}],
"synonyms": [{"concept": "成交金额", "alias": "营业额"}]})
res = review.decide(fb["review_item"]["id"], True)
assert evals.list_cases("feedback")[0]["expected"] == "营业额即成交金额"
c = ksvc.find("成交金额")
assert "营业额" in ksvc.get_concept(c["id"])["synonyms"]
from app.memory import service as memory
assert memory.list_facts(status="active")[0]["text"] == "营业额即成交金额"
assert res
def test_操作习惯_重复三次建议固化(agents_env, monkeypatch):
from app.memory import service as memory
for _ in range(3):
memory.record_pattern("action", "mark_follow", "标记重点跟进", "偏低")
sug = memory.suggestions()
assert sug and sug[0]["kind"] == "action" and "3 次" in sug[0]["text"]
memory.decide_pattern(sug[0]["id"], False)
assert memory.suggestions() == []
def test_A2A_直接把任务交给问数Agent(agents_env, monkeypatch):
from app.capability import mcp
from app.core import identity
build_basics(agents_env["ds_id"])
plan_final = {"calls": [{"tool": "query_metric", "args": {"metric": "成交金额"}}]}
seq = iter([plan_final, {"final": {"summary": "成交金额 1800 元", "confidence": 0.9}}])
def stream(msgs, **k):
yield from _say("先取数。", next(seq))
monkeypatch.setattr(llm, "chat_stream", stream)
ok, out = mcp.call_logged(identity.current(), "ask_data_agent", {"task": "成交金额是多少"}, "agent")
assert ok and out["summary"] == "成交金额 1800 元"
assert out["evidence"][0]["tool"] == "query_metric" and out["data"]
def test_接口_提问元数据_经验库_老接口权限(agents_env):
from fastapi.testclient import TestClient
from app.main import app
c = TestClient(app)
assert c.get("/api/memory/stats", headers={"X-User-Id": "viewer"}).status_code == 200
# 业务人员只能记个人偏好,不能写组织口径
r = c.post("/api/memory/facts", json={"text": "我只看华东区", "kind": "definition", "scope": "workspace"},
headers={"X-User-Id": "viewer"}).json()
assert r["kind"] == "preference" and r["scope"] == "user"
assert c.put("/api/memory/facts/" + r["id"], json={"status": "deprecated"},
headers={"X-User-Id": "viewer"}).status_code == 403
# 老接口也按权限:只读用户能看,不能改
assert c.get("/api/config", headers={"X-User-Id": "viewer"}).status_code == 200
assert c.put("/api/config", json={"items": {"MAX_HOPS": "2"}}, headers={"X-User-Id": "viewer"}).status_code == 403
assert c.post("/api/cache/clear", headers={"X-User-Id": "viewer"}).status_code == 403
assert c.get("/api/ask/chunk?id=nope").status_code == 404
def test_思考格式_兼容三种写法(monkeypatch):
from app.agents.base import think_json
from app.agents.trace import Tracer
cases = [
(["思考:先", "取数。\n", "```json\n{\"a\": 1}\n```"], "先取数。"),
(["<think>看一下</think>\n{\"a\": 1}"], "看一下"),
(["```json\n{\"a\": 1, \"thought\": \"直接给了 JSON\"}\n```"], "直接给了 JSON"),
]
for pieces, want in cases:
t = Tracer()
monkeypatch.setattr(llm, "chat_stream", lambda msgs, pieces=pieces, **k: iter(pieces))
obj = think_json(t, "lead", "lead", [])
assert obj["a"] == 1
assert "".join(e["text"] for e in t.events if e["type"] == "thought") == want
def test_快路径要求问的是同一批对象(agents_env, monkeypatch):
from app.core import db as core_db
from app.core.dbx import jdump, session
core_db.set_config({"MEMORY_FAST_PATH": "0.5"}) # 放低门槛:只靠「对象一致」这一道闸拦
from app.memory import service as memory
from app.memory.models import MemCase
plan = {"delegations": [{"agent": "data", "task": "取华南纸品的库存", "calls": []}]}
with session() as s:
s.add(MemCase(id="mc1", workspace="default", question="华南纸品延期影响哪些库存",
question_norm=memory.normalize("华南纸品延期影响哪些库存"), status="verified", score=0.9,
plan_json=jdump(plan), concepts_json=jdump([{"id": "inst:sup:S003", "instance": True}])))
s.commit()
same = memory.recall("华南纸品延期影响哪些库存", {"concepts": [], "instances": [
{"concept_id": "sup", "key": "S003", "type_name": "供应商", "label": "华南纸品"}]})
assert same["fast"] and same["fast"]["id"] == "mc1"
other = memory.recall("华北纸品延期影响哪些库存", {"concepts": [], "instances": [
{"concept_id": "sup", "key": "S009", "type_name": "供应商", "label": "华北纸品"}]})
assert other["fast"] is None and other["cases"][0]["id"] == "mc1" # 仍作为参考,但不复用路径