-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_agui_protocol.py
More file actions
1187 lines (947 loc) · 38.8 KB
/
test_agui_protocol.py
File metadata and controls
1187 lines (947 loc) · 38.8 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""AG-UI 协议处理器测试
测试 AGUIProtocolHandler 的各种功能。
"""
import json
from typing import cast
from fastapi.testclient import TestClient
import pytest
from agentrun.server import (
AgentEvent,
AgentRequest,
AgentRunServer,
AGUIProtocolHandler,
EventType,
ServerConfig,
)
class TestAGUIProtocolHandler:
"""测试 AGUIProtocolHandler"""
def test_get_prefix_default(self):
"""测试默认前缀"""
handler = AGUIProtocolHandler()
assert handler.get_prefix() == "/ag-ui/agent"
def test_get_prefix_custom(self):
"""测试自定义前缀"""
from agentrun.server.model import AGUIProtocolConfig
config = ServerConfig(agui=AGUIProtocolConfig(prefix="/custom/agui"))
handler = AGUIProtocolHandler(config)
assert handler.get_prefix() == "/custom/agui"
class TestAGUIProtocolEndpoints:
"""测试 AG-UI 协议端点"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
@pytest.mark.asyncio
async def test_value_error_handling(self):
"""测试 ValueError 处理"""
def invoke_agent(request: AgentRequest):
raise ValueError("Test error")
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hello"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该包含 RUN_ERROR 事件
types = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
types.append(data.get("type"))
assert "RUN_ERROR" in types
@pytest.mark.asyncio
async def test_general_exception_handling(self):
"""测试一般异常处理(在 invoke_agent 中抛出异常)"""
def invoke_agent(request: AgentRequest):
raise RuntimeError("Internal error")
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hello"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该包含 RUN_ERROR 事件
types = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
types.append(data.get("type"))
assert "RUN_ERROR" in types
@pytest.mark.asyncio
async def test_exception_in_parse_request(self):
"""测试 parse_request 中的异常处理(覆盖 155-156 行)
通过发送一个会导致 parse_request 抛出非 ValueError 异常的请求
"""
from unittest.mock import AsyncMock, patch
def invoke_agent(request: AgentRequest):
return "Hello"
client = self.get_client(invoke_agent)
# 模拟 parse_request 抛出 RuntimeError
with patch.object(
AGUIProtocolHandler,
"parse_request",
new_callable=AsyncMock,
side_effect=RuntimeError("Unexpected error"),
):
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hello"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该包含 RUN_ERROR 事件
types = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
types.append(data.get("type"))
assert "RUN_ERROR" in types
# 错误消息应该包含 "Internal error"
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "RUN_ERROR":
assert "Internal error" in data.get("message", "")
break
@pytest.mark.asyncio
async def test_parse_messages_with_non_dict(self):
"""测试解析消息时跳过非字典项"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["messages"] = request.messages
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [
"invalid_message", # 非字典项,应该被跳过
{"role": "user", "content": "Hello"},
],
},
)
assert response.status_code == 200
assert len(captured_request["messages"]) == 1
@pytest.mark.asyncio
async def test_parse_messages_with_invalid_role(self):
"""测试解析消息时处理无效角色"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["messages"] = request.messages
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [
{"role": "invalid_role", "content": "Hello"}, # 无效角色
],
},
)
assert response.status_code == 200
# 无效角色应该默认为 user
from agentrun.server.model import MessageRole
assert captured_request["messages"][0].role == MessageRole.USER
@pytest.mark.asyncio
async def test_parse_messages_with_tool_calls(self):
"""测试解析带有 toolCalls 的消息"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["messages"] = request.messages
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [
{
"id": "msg-1",
"role": "assistant",
"content": None,
"toolCalls": [{
"id": "call_123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"city": "Beijing"}',
},
}],
},
{
"id": "msg-2",
"role": "tool",
"content": "Sunny",
"toolCallId": "call_123",
},
],
},
)
assert response.status_code == 200
assert len(captured_request["messages"]) == 2
assert captured_request["messages"][0].tool_calls is not None
assert captured_request["messages"][0].tool_calls[0].id == "call_123"
assert captured_request["messages"][1].tool_call_id == "call_123"
@pytest.mark.asyncio
async def test_parse_tools(self):
"""测试解析工具列表"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["tools"] = request.tools
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "Hi"}],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather",
},
}],
},
)
assert response.status_code == 200
assert captured_request["tools"] is not None
assert len(captured_request["tools"]) == 1
@pytest.mark.asyncio
async def test_parse_tools_with_non_dict(self):
"""测试解析工具列表时跳过非字典项"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["tools"] = request.tools
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "Hi"}],
"tools": [
"invalid_tool",
{"type": "function", "function": {"name": "valid"}},
],
},
)
assert response.status_code == 200
assert captured_request["tools"] is not None
assert len(captured_request["tools"]) == 1
@pytest.mark.asyncio
async def test_parse_tools_empty_after_filter(self):
"""测试解析工具列表后为空时返回 None"""
captured_request = {}
def invoke_agent(request: AgentRequest):
captured_request["tools"] = request.tools
return "Done"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "Hi"}],
"tools": ["invalid1", "invalid2"],
},
)
assert response.status_code == 200
assert captured_request["tools"] is None
@pytest.mark.asyncio
async def test_state_delta_event(self):
"""测试 STATE delta 事件"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.STATE,
data={"delta": [{"op": "add", "path": "/count", "value": 1}]},
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 STATE_DELTA 事件
found_delta = False
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "STATE_DELTA":
found_delta = True
assert data["delta"] == [
{"op": "add", "path": "/count", "value": 1}
]
assert found_delta
@pytest.mark.asyncio
async def test_state_snapshot_fallback(self):
"""测试 STATE 事件没有 snapshot 或 delta 时的回退"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.STATE,
data={
"custom_key": "custom_value"
}, # 既不是 snapshot 也不是 delta
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该作为 STATE_SNAPSHOT 处理
found_snapshot = False
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "STATE_SNAPSHOT":
found_snapshot = True
assert data["snapshot"]["custom_key"] == "custom_value"
assert found_snapshot
@pytest.mark.asyncio
async def test_unknown_event_type(self):
"""测试未知事件类型转换为 CUSTOM"""
# 直接测试 _process_event_with_boundaries 方法
# 由于我们无法直接发送未知事件类型,我们测试 CUSTOM 事件的正常处理
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.CUSTOM,
data={"name": "unknown_event", "value": {"data": "test"}},
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 CUSTOM 事件
found_custom = False
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "CUSTOM":
found_custom = True
assert data["name"] == "unknown_event"
assert found_custom
@pytest.mark.asyncio
async def test_addition_merge_overrides(self):
"""测试 addition 默认合并覆盖字段"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.TEXT,
data={"delta": "Hello"},
addition={"custom": "value", "delta": "overwritten"},
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 TEXT_MESSAGE_CONTENT 事件
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "TEXT_MESSAGE_CONTENT":
assert "custom" in data
assert data["delta"] == "overwritten"
break
@pytest.mark.asyncio
async def test_addition_protocol_only_mode(self):
"""测试 addition PROTOCOL_ONLY 模式"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.TEXT,
data={"delta": "Hello"},
addition={
"delta": "overwritten", # 已存在的字段会被覆盖
"new_field": "ignored", # 新字段会被忽略
},
addition_merge_options={"no_new_field": True},
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 TEXT_MESSAGE_CONTENT 事件
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "TEXT_MESSAGE_CONTENT":
assert data["delta"] == "overwritten"
assert "new_field" not in data
break
@pytest.mark.asyncio
async def test_raw_event_with_newline(self):
"""测试 RAW 事件自动添加换行符"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.RAW,
data={"raw": '{"custom": "data"}'}, # 没有换行符
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
# RAW 事件应该被正确处理
content = response.text
assert '{"custom": "data"}' in content
@pytest.mark.asyncio
async def test_raw_event_with_trailing_newlines(self):
"""测试 RAW 事件带有尾随换行符时的处理"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.RAW,
data={"raw": '{"custom": "data"}\n'}, # 只有一个换行符
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
content = response.text
assert '{"custom": "data"}' in content
@pytest.mark.asyncio
async def test_raw_event_already_has_double_newline(self):
"""测试 RAW 事件已经有双换行符时不再添加"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.RAW,
data={"raw": '{"custom": "data"}\n\n'}, # 已经有双换行符
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
content = response.text
assert '{"custom": "data"}' in content
@pytest.mark.asyncio
async def test_raw_event_empty(self):
"""测试空 RAW 事件"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.RAW,
data={"raw": ""}, # 空内容
)
yield "Hello"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该正常完成,包含 Hello 文本
types = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
types.append(data.get("type"))
assert "TEXT_MESSAGE_CONTENT" in types
@pytest.mark.asyncio
async def test_thread_id_and_run_id_from_request(self):
"""测试使用请求中的 threadId 和 runId"""
async def invoke_agent(request: AgentRequest):
yield "Hello"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "Hi"}],
"threadId": "custom-thread-123",
"runId": "custom-run-456",
},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 检查 RUN_STARTED 事件
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "RUN_STARTED":
assert data["threadId"] == "custom-thread-123"
assert data["runId"] == "custom-run-456"
break
@pytest.mark.asyncio
async def test_new_text_message_after_tool_result(self):
"""测试工具结果后的新文本消息有新的 messageId"""
async def invoke_agent(request: AgentRequest):
yield "First message"
yield AgentEvent(
event=EventType.TOOL_CALL_CHUNK,
data={"id": "tc-1", "name": "tool", "args_delta": "{}"},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={"id": "tc-1", "result": "done"},
)
# 这应该触发 TEXT_MESSAGE_END 然后 TEXT_MESSAGE_START(新消息)
yield "Second message"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 收集所有 messageId
message_ids = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") in [
"TEXT_MESSAGE_START",
"TEXT_MESSAGE_CONTENT",
"TEXT_MESSAGE_END",
]:
message_ids.append(data.get("messageId"))
# 第一段和第二段文本应该有相同的 messageId(AG-UI 允许并行)
# 实际上在当前实现中,工具调用后的文本是同一个消息的延续
assert len(message_ids) >= 2
class TestAGUIProtocolErrorStream:
"""测试 AG-UI 协议错误流"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
@pytest.mark.asyncio
async def test_error_stream_on_json_parse_error(self):
"""测试 JSON 解析错误时的错误流"""
def invoke_agent(request: AgentRequest):
return "Hello"
client = self.get_client(invoke_agent)
# 发送无效的 JSON
response = client.post(
"/ag-ui/agent",
content="invalid json",
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该包含 RUN_STARTED 和 RUN_ERROR
types = []
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
types.append(data.get("type"))
assert "RUN_STARTED" in types
assert "RUN_ERROR" in types
@pytest.mark.asyncio
async def test_error_stream_format(self):
"""测试错误流的格式"""
def invoke_agent(request: AgentRequest):
raise ValueError("Test validation error")
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 检查错误事件的格式
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "RUN_ERROR":
# 错误事件应该包含 message
assert "message" in data
break
class TestAGUIProtocolApplyAddition:
"""测试 _apply_addition 方法"""
def test_apply_addition_default_merge(self):
"""默认合并应覆盖已有字段"""
handler = AGUIProtocolHandler()
event_data = {"delta": "Hello", "type": "TEXT_MESSAGE_CONTENT"}
addition = {"delta": "overwritten", "new_field": "added"}
result = handler._apply_addition(
event_data.copy(),
addition.copy(),
)
assert result["delta"] == "overwritten"
assert result["new_field"] == "added"
assert result["type"] == "TEXT_MESSAGE_CONTENT"
def test_apply_addition_merge_options_none(self):
"""显式传入 merge_options=None 仍按默认合并"""
handler = AGUIProtocolHandler()
event_data = {"delta": "Hello", "type": "TEXT_MESSAGE_CONTENT"}
addition = {"delta": "overwritten", "new_field": "added"}
result = handler._apply_addition(
event_data.copy(),
addition.copy(),
)
assert result["delta"] == "overwritten"
assert result["new_field"] == "added"
def test_apply_addition_protocol_only_mode(self):
"""测试 PROTOCOL_ONLY 模式(覆盖 616->620 分支)"""
handler = AGUIProtocolHandler()
event_data = {"delta": "Hello", "type": "TEXT_MESSAGE_CONTENT"}
addition = {"delta": "overwritten", "new_field": "ignored"}
result = handler._apply_addition(
event_data.copy(),
addition.copy(),
{"no_new_field": True},
)
# delta 被覆盖
assert result["delta"] == "overwritten"
# new_field 不存在(被忽略)
assert "new_field" not in result
# type 保持不变
assert result["type"] == "TEXT_MESSAGE_CONTENT"
class TestAGUIProtocolConvertMessages:
"""测试消息转换功能"""
def test_convert_messages_for_snapshot(self):
"""测试 _convert_messages_for_snapshot 方法"""
handler = AGUIProtocolHandler()
messages = [
{"role": "user", "content": "Hello", "id": "msg-1"},
{"role": "assistant", "content": "Hi there", "id": "msg-2"},
{"role": "system", "content": "You are helpful", "id": "msg-3"},
{
"role": "tool",
"content": "Result",
"id": "msg-4",
"tool_call_id": "tc-1",
},
]
result = handler._convert_messages_for_snapshot(messages)
assert len(result) == 4
assert result[0].role == "user"
assert result[1].role == "assistant"
assert result[2].role == "system"
assert result[3].role == "tool"
def test_convert_messages_with_non_dict(self):
"""测试 _convert_messages_for_snapshot 跳过非字典项"""
handler = AGUIProtocolHandler()
messages = [
"invalid",
{"role": "user", "content": "Hello", "id": "msg-1"},
123,
{"role": "assistant", "content": "Hi", "id": "msg-2"},
]
result = handler._convert_messages_for_snapshot(messages)
assert len(result) == 2
def test_convert_messages_with_missing_id(self):
"""测试 _convert_messages_for_snapshot 自动生成 id"""
handler = AGUIProtocolHandler()
messages = [
{"role": "user", "content": "Hello"}, # 没有 id
]
result = handler._convert_messages_for_snapshot(messages)
assert len(result) == 1
assert result[0].id is not None
assert len(result[0].id) > 0
def test_convert_messages_with_unknown_role(self):
"""测试 _convert_messages_for_snapshot 处理未知角色"""
handler = AGUIProtocolHandler()
messages = [
{"role": "unknown", "content": "Hello", "id": "msg-1"},
{"role": "user", "content": "World", "id": "msg-2"},
]
result = handler._convert_messages_for_snapshot(messages)
# 未知角色的消息会被跳过
assert len(result) == 1
assert result[0].role == "user"
class TestAGUIProtocolUnknownEvent:
"""测试未知事件类型处理"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
@pytest.mark.asyncio
async def test_tool_result_event(self):
"""测试 TOOL_RESULT 事件(使用 content 字段)"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.TOOL_CALL_CHUNK,
data={"id": "tc-1", "name": "tool", "args_delta": "{}"},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={
"id": "tc-1",
"content": "Tool content result",
}, # 使用 content
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 TOOL_CALL_RESULT 事件
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "TOOL_CALL_RESULT":
assert data["content"] == "Tool content result"
break
class TestAGUIProtocolTextMessageRestart:
"""测试文本消息重新开始"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
@pytest.mark.asyncio
async def test_text_message_restart_after_end(self):
"""测试文本消息结束后重新开始新消息
当 text_state["ended"] 为 True 时,新的 TEXT 事件应该开始新消息
"""
async def invoke_agent(request: AgentRequest):
# 第一段文本
yield "First"
# 工具调用会导致文本消息结束
yield AgentEvent(
event=EventType.TOOL_CALL_CHUNK,
data={"id": "tc-1", "name": "tool", "args_delta": "{}"},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={"id": "tc-1", "result": "done"},
)
# 第二段文本应该开始新消息
yield "Second"
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 统计 TEXT_MESSAGE_START 事件数量
start_count = 0
message_ids = set()
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "TEXT_MESSAGE_START":
start_count += 1
message_ids.add(data.get("messageId"))
# 应该只有一个 TEXT_MESSAGE_START(AG-UI 允许并行)
# 但如果实现了重新开始逻辑,可能有两个
assert start_count >= 1
@pytest.mark.asyncio
async def test_state_delta_event(self):
"""测试 STATE delta 事件"""
async def invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.STATE,
data={
"delta": [{"op": "replace", "path": "/count", "value": 10}]
},
)
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 查找 STATE_DELTA 事件
found = False
for line in lines:
if line.startswith("data: "):
data = json.loads(line[6:])
if data.get("type") == "STATE_DELTA":
found = True
assert data["delta"][0]["op"] == "replace"
break
assert found
class TestAGUIProtocolExceptionHandling:
"""测试异常处理"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
@pytest.mark.asyncio
async def test_general_exception_returns_error_stream(self):
"""测试一般异常返回错误流"""
def invoke_agent(request: AgentRequest):
raise RuntimeError("Unexpected error")
client = self.get_client(invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "Hi"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines() if line]
# 应该包含 RUN_ERROR
types = [
json.loads(line[6:]).get("type")
for line in lines
if line.startswith("data: ")
]
assert "RUN_ERROR" in types
class TestAGUIProtocolUnknownEventType:
"""测试未知事件类型处理(覆盖第 531 行)
TOOL_CALL 事件没有在 _process_event_with_boundaries 中被显式处理,
所以它会走到第 531 行的 else 分支,被转换为 CUSTOM 事件。
"""
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
return TestClient(server.as_fastapi_app())
def test_process_event_with_boundaries_unknown_event(self):
"""直接测试 _process_event_with_boundaries 处理未知事件类型
TOOL_CALL 事件没有在 _process_event_with_boundaries 中被显式处理,
所以它会走到 else 分支,被转换为 CUSTOM 事件。
"""
handler = AGUIProtocolHandler()
# 创建 TOOL_CALL 事件(在协议层没有被显式处理)
event = AgentEvent(
event=EventType.TOOL_CALL,