test_query_answer_timeline.py
5.92 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
"""Wiki 问答答案渲染的 append-only 时间线契约。
核心约束:assistant 的每个 text block 各占一个 part,按 id 覆盖、按到达顺序追加,
**绝不回撤**。历史上这里用时间去抖猜测「本轮是不是最终回答」,猜错就发一帧空内容
清空气泡,表现为「前导文字闪一下又消失」。这些用例锁住不会再退回那个实现。
"""
import asyncio
import unittest
from agentscope.message import Msg
from src.api.routes.query import WikiQueryRunner
def _text_msg(msg_id: str, text: str) -> Msg:
msg = Msg("WikiAssistant", [{"type": "text", "text": text}], "assistant")
msg.id = msg_id
return msg
def _text_and_tool_msg(msg_id: str, text: str, tool_name: str = "read_local_file") -> Msg:
msg = Msg(
"WikiAssistant",
[
{"type": "text", "text": text},
{"type": "tool_use", "id": f"{msg_id}-call", "name": tool_name, "input": {"file_path": "a.md"}},
],
"assistant",
)
msg.id = msg_id
return msg
class _FakeAgent:
"""只提供 _configure_agent 需要的最小接口。"""
def __init__(self) -> None:
self.print = None
def set_console_output_enabled(self, enabled: bool) -> None: # noqa: ARG002
pass
class QueryAnswerTimelineTest(unittest.TestCase):
def setUp(self) -> None:
self.queue: asyncio.Queue = asyncio.Queue()
self.runner = WikiQueryRunner("测试问题", [], session_id="t", event_queue=self.queue)
agent = _FakeAgent()
self.runner._configure_agent(agent)
self.hooked_print = agent.print
def _feed(self, *msgs: Msg) -> None:
async def run() -> None:
for msg in msgs:
await self.hooked_print(msg, True)
asyncio.run(run())
def _drain(self) -> list[dict]:
events = []
while not self.queue.empty():
events.append(self.queue.get_nowait())
return events
def _bot_events(self) -> list[dict]:
return [e for e in self._drain() if e.get("type") == "bot"]
def test_preamble_before_tool_call_is_never_retracted(self):
"""前导文字 + 随后的 tool_use:绝不能出现清空气泡的空内容帧。"""
self._feed(
_text_msg("msg-A", "好的,我先检索话术。"),
_text_and_tool_msg("msg-A", "好的,我先检索话术。"),
)
bots = self._bot_events()
self.assertTrue(bots, "前导文字应当作为答案 part 推送")
self.assertEqual(
[e for e in bots if e["content"] == ""],
[],
"出现了空内容的 bot 事件 = 回撤清空气泡,正是要根除的泄漏闪烁",
)
self.assertEqual({e["id"] for e in bots}, {"msg-A-answer"})
def test_multiple_rounds_become_ordered_parts(self):
"""跨轮 text 各占一个 part,id 不同、按序到达,前端 join 后即完整时间线。"""
self._feed(
_text_msg("msg-A", "我先查一下知识库。"),
_text_msg("msg-B", "以下是应对话术。"),
)
bots = self._bot_events()
self.assertEqual([e["id"] for e in bots], ["msg-A-answer", "msg-B-answer"])
# 复现前端 messageMap[id] = content; Object.values(map).join("")
message_map: dict[str, str] = {}
for event in bots:
message_map[event["id"]] = event["content"]
self.assertEqual("".join(message_map.values()), "我先查一下知识库。以下是应对话术。")
def test_same_round_streams_incrementally(self):
"""同一轮内按 id 覆盖,内容单调增长(逐字流式)。"""
self._feed(
_text_msg("msg-A", "以下"),
_text_msg("msg-A", "以下是应对"),
_text_msg("msg-A", "以下是应对话术。"),
)
bots = self._bot_events()
self.assertEqual({e["id"] for e in bots}, {"msg-A-answer"})
contents = [e["content"] for e in bots]
self.assertEqual(contents, ["以下", "以下是应对", "以下是应对话术。"])
def test_emit_answer_overwrites_last_part_only(self):
"""权威收尾覆盖最后一个 part,更早的前导 part 原样保留。"""
self._feed(
_text_msg("msg-A", "我先查一下知识库。"),
_text_msg("msg-B", "草稿答案"),
)
self._drain()
asyncio.run(self.runner._emit_answer("清洗后的最终答案"))
bots = self._bot_events()
self.assertEqual(len(bots), 1)
self.assertEqual(bots[0]["id"], "msg-B-answer", "应覆盖最后一个 part,而非固定 id")
self.assertEqual(bots[0]["content"], "清洗后的最终答案")
def test_emit_answer_falls_back_when_no_text_part(self):
"""异常/兜底路径下没有任何 text part 时,回落到固定 id 新起一个 part。"""
asyncio.run(self.runner._emit_answer("兜底回答"))
bots = self._bot_events()
self.assertEqual(len(bots), 1)
self.assertEqual(bots[0]["id"], "final-answer")
def test_tool_events_still_go_to_reasoning_box(self):
"""工具调用/返回仍走思考框,前端折叠框功能不受影响。"""
self._feed(_text_and_tool_msg("msg-A", "查一下。"))
events = self._drain()
calls = [e for e in events if e.get("type") == "call"]
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0]["name"], "read_local_file")
self.assertTrue(calls[0]["id"].startswith("call-"))
def test_debounce_heuristics_are_gone(self):
"""锁死:去抖/回撤/粘性标记这套启发式不得复活。"""
import src.api.routes.query as query_module
self.assertFalse(hasattr(query_module, "ANSWER_COMMIT_DEBOUNCE"))
for attr in ("_msg_has_tool", "_answer_sent_len", "_text_first_ts"):
self.assertFalse(hasattr(self.runner, attr), f"{attr} 应已删除")
if __name__ == "__main__":
unittest.main()