-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_server.py
More file actions
970 lines (852 loc) · 36 KB
/
test_server.py
File metadata and controls
970 lines (852 loc) · 36 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
import asyncio
import json
from typing import Any, cast, Union
import pytest
from agentrun.server.model import AgentRequest, MessageRole
from agentrun.server.server import AgentRunServer
class ProtocolValidator:
def try_parse_streaming_line(self, line: str) -> Union[str, dict, list]:
"""解析流式响应行,去除前缀 'data: ' 并转换为 JSON"""
if type(line) is not str or line.startswith("data: [DONE]"):
return line
if line.startswith("data: {") or line.startswith("data: ["):
json_str = line[len("data: ") :]
return json.loads(json_str)
return line
def parse_streaming_line(self, line: str) -> Union[str, dict, list]:
"""解析流式响应行,去除前缀 'data: ' 并转换为 JSON"""
if type(line) is not str or line.startswith("data: [DONE]"):
return line
if line.startswith("data: {") or line.startswith("data: ["):
json_str = line[len("data: ") :]
return json.loads(json_str)
return line
def valid_json(self, got: Any, expect: Any):
"""检查 json 是否匹配,如果 expect 的 value 为 mock-placeholder 则仅检查 key 存在"""
def valid(path: str, got: Any, expect: Any):
if expect == "mock-placeholder":
assert got, f"{path} 存在但值为空"
else:
got = self.try_parse_streaming_line(got)
expect = self.try_parse_streaming_line(expect)
if isinstance(expect, dict):
assert isinstance(
got, dict
), f"{path} 类型不匹配,期望 dict,实际 {type(got)}"
for k, v in expect.items():
valid(f"{path}.{k}", got.get(k), v)
for k in got.keys():
if k not in expect:
assert False, f"{path} 多余的键: {k}"
elif isinstance(expect, list):
assert isinstance(
got, list
), f"{path} 类型不匹配,期望 list,实际 {type(got)}"
assert len(got) == len(
expect
), f"{path} 列表长度不匹配,期望 {len(expect)},实际 {len(got)}"
for i in range(len(expect)):
valid(f"{path}[{i}]", got[i], expect[i])
else:
assert (
got == expect
), f"{path} 不匹配,期望: {type(expect)} {expect},实际: {got}"
print("valid", got, expect)
valid("", got, expect)
def all_field_equal(
self,
key: str,
arr: list,
):
"""检查列表中所有对象的指定字段值是否相等"""
print("all_field_equal", arr, key)
value = ""
for item in arr:
data = self.try_parse_streaming_line(item)
data = cast(dict, data)
if value == "":
value = data[key]
assert value == data[key]
assert value
class TestServer(ProtocolValidator):
def get_invoke_agent_non_streaming(self):
def invoke_agent(request: AgentRequest):
# 检查请求消息,返回预期的响应
user_message = next(
(
msg.content
for msg in request.messages
if msg.role == MessageRole.USER
),
"Hello",
)
return f"You said: {user_message}"
return invoke_agent
def get_invoke_agent_streaming(self):
async def streaming_invoke_agent(request: AgentRequest):
yield "Hello, "
await asyncio.sleep(0.01) # 短暂延迟
yield "this is "
await asyncio.sleep(0.01)
yield "a test."
return streaming_invoke_agent
def get_client(self, invoke_agent):
server = AgentRunServer(invoke_agent=invoke_agent)
app = server.as_fastapi_app()
from fastapi.testclient import TestClient
return TestClient(app)
async def test_health_check(self):
"""测试 /health 健康检查路由"""
client = self.get_client(self.get_invoke_agent_non_streaming())
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
async def test_health_check_post_not_allowed(self):
"""测试 POST /health 不被允许"""
client = self.get_client(self.get_invoke_agent_non_streaming())
response = client.post("/health")
# FastAPI 对不匹配的方法返回 405
assert response.status_code == 405
async def test_health_check_with_custom_protocols(self):
"""测试自定义协议列表时 /health 仍可用"""
from agentrun.server.openai_protocol import OpenAIProtocolHandler
server = AgentRunServer(
invoke_agent=self.get_invoke_agent_non_streaming(),
protocols=[OpenAIProtocolHandler()],
)
from fastapi.testclient import TestClient
client = TestClient(server.as_fastapi_app())
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
async def test_server_non_streaming_protocols(self):
"""测试非流式的 OpenAI 和 AGUI 服务器响应功能"""
client = self.get_client(self.get_invoke_agent_non_streaming())
# 测试 OpenAI 协议
response_openai = client.post(
"/openai/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "AgentRun"}],
"model": "test-model",
},
)
# 检查响应状态
assert response_openai.status_code == 200
# 检查响应内容
response_data_openai = response_openai.json()
self.valid_json(
response_data_openai,
{
"id": "mock-placeholder",
"object": "chat.completion",
"created": "mock-placeholder",
"model": "test-model",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "You said: AgentRun",
},
"finish_reason": "stop",
}],
},
)
# AGUI 协议始终是流式传输,因此没有非流式测试
# 测试 AGUI 协议(即使非流式请求也会以流式方式处理)
response_agui = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "AgentRun"}],
"model": "test-model",
},
)
# 检查响应状态
assert response_agui.status_code == 200
lines_agui = [line async for line in response_agui.aiter_lines()]
lines_agui = [line for line in lines_agui if line]
# AG-UI 流式格式:RUN_STARTED + TEXT_MESSAGE_START + TEXT_MESSAGE_CONTENT + TEXT_MESSAGE_END + RUN_FINISHED
assert len(lines_agui) == 5
# 验证 AGUI 流式事件序列
self.valid_json(
lines_agui,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"You'
' said: AgentRun"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
async def test_server_streaming_protocols(self):
"""测试流式的 OpenAI 和 AGUI 服务器响应功能"""
# 测试 OpenAI 协议流式响应
client = self.get_client(self.get_invoke_agent_streaming())
response_openai = client.post(
"/openai/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "AgentRun"}],
"model": "test-model",
"stream": True,
},
)
# 检查响应状态
assert response_openai.status_code == 200
lines_openai = [line async for line in response_openai.aiter_lines()]
# 过滤空行
lines_openai = [line for line in lines_openai if line]
# OpenAI 流式格式:第一个 chunk 是 role 声明,后续是内容
# 格式:data: {...}
self.valid_json(
lines_openai,
[
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {"role": "assistant", "content": "Hello, "},'
' "finish_reason": null}]}'
),
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {"content": "this is "}, "finish_reason": null}]}'
),
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {"content": "a test."}, "finish_reason": null}]}'
),
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {}, "finish_reason": "stop"}]}'
),
"data: [DONE]",
],
)
self.all_field_equal("id", lines_openai[:-1])
# 测试 AGUI 协议流式响应
response_agui = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "AgentRun"}],
"model": "test-model",
"stream": True,
},
)
# 检查响应状态
assert response_agui.status_code == 200
lines_agui = [line async for line in response_agui.aiter_lines()]
# 过滤空行
lines_agui = [line for line in lines_agui if line]
# AG-UI 流式格式:每个 chunk 是一个 JSON 对象
self.valid_json(
lines_agui,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"Hello, "}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"this'
' is "}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"a'
' test."}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("runId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("messageId", lines_agui[1:6])
async def test_server_raw_event_protocols(self):
"""测试 RAW 事件直接返回原始数据(OpenAI 和 AG-UI 协议)
RAW 事件可以在任何时间触发,输出原始 SSE 内容,不影响其他事件的正常处理。
支持任意 SSE 格式(data:, :注释, 等)。
"""
from agentrun.server import AgentEvent, AgentRequest, EventType
async def streaming_invoke_agent(request: AgentRequest):
# 测试 RAW 事件与其他事件混合
yield "你好"
yield AgentEvent(
event=EventType.RAW,
data={"raw": '{"custom": "data"}'},
)
yield AgentEvent(event=EventType.TEXT, data={"delta": "再见"})
client = self.get_client(streaming_invoke_agent)
# 测试 OpenAI 协议的 RAW 事件
response_openai = client.post(
"/openai/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "test"}],
"model": "agentrun",
"stream": True,
},
)
assert response_openai.status_code == 200
lines_openai = [line async for line in response_openai.aiter_lines()]
lines_openai = [line for line in lines_openai if line]
# OpenAI 流式响应:
# 1. role: assistant + content: 你好(合并在首个 chunk)
# 2. RAW: {"custom": "data"}
# 3. content: 再见
# 4. finish_reason: stop
# 5. [DONE]
self.valid_json(
lines_openai,
[
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "agentrun", "choices": [{"index": 0, "delta":'
' {"role": "assistant", "content": "你好"},'
' "finish_reason": null}]}'
),
'{"custom": "data"}',
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "agentrun", "choices": [{"index": 0, "delta":'
' {"content": "再见"}, "finish_reason": null}]}'
),
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "agentrun", "choices": [{"index": 0, "delta":'
' {}, "finish_reason": "stop"}]}'
),
"data: [DONE]",
],
)
self.all_field_equal("id", [lines_openai[0], *lines_openai[2:-1]])
# 测试 AGUI 协议的 RAW 事件
response_agui = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "test"}],
"stream": True,
},
)
assert response_agui.status_code == 200
lines_agui = [line async for line in response_agui.aiter_lines()]
lines_agui = [line for line in lines_agui if line]
# AGUI 流式响应中应该包含 RAW 事件
# 1. RUN_STARTED
# 2. TEXT_MESSAGE_START
# 3. TEXT_MESSAGE_CONTENT ("你好")
# 4. RAW 事件 '{"custom": "data"}'
# 5. TEXT_MESSAGE_CONTENT ("再见")
# 6. TEXT_MESSAGE_END
# 7. RUN_FINISHED
self.valid_json(
lines_agui,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"你好"}'
),
'{"custom": "data"}',
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"再见"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("runId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal(
"messageId",
[lines_agui[1], lines_agui[2], lines_agui[4], lines_agui[5]],
)
async def test_server_addition_merge(self):
"""测试 addition 字段的合并功能"""
from agentrun.server import AgentEvent, AgentRequest, EventType
async def streaming_invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.TEXT,
data={"message_id": "msg_1", "delta": "Hello"},
addition={
"model": "custom_model",
"custom_field": "custom_value",
},
)
client = self.get_client(streaming_invoke_agent)
# 测试 OpenAI 协议
response_openai = client.post(
"/openai/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "test"}],
"model": "test-model",
"stream": True,
},
)
assert response_openai.status_code == 200
lines = [line async for line in response_openai.aiter_lines()]
lines = [line for line in lines if line]
# OpenAI 流式格式:只有一个内容行 + 完成行 + [DONE]
self.valid_json(
lines,
[
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {"role": "assistant", "content": "Hello", "model":'
' "custom_model", "custom_field": "custom_value"},'
' "finish_reason": null}]}'
),
(
'data: {"id": "mock-placeholder", "object":'
' "chat.completion.chunk", "created": "mock-placeholder",'
' "model": "test-model", "choices": [{"index": 0, "delta":'
' {}, "finish_reason": "stop"}]}'
),
"data: [DONE]",
],
)
self.all_field_equal("id", lines[:-1])
response_agui = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "test"}]},
)
assert response_agui.status_code == 200
lines_agui = [line async for line in response_agui.aiter_lines()]
lines_agui = [line for line in lines_agui if line]
# AG-UI 流式格式:RUN_STARTED + TEXT_MESSAGE_START + TEXT_MESSAGE_CONTENT + TEXT_MESSAGE_END + RUN_FINISHED
self.valid_json(
lines_agui,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
'data: {"type": "TEXT_MESSAGE_CONTENT", "messageId":'
' "mock-placeholder", "delta": "Hello", "model":'
' "custom_model", "custom_field": "custom_value"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("runId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("messageId", lines_agui[1:4])
async def test_server_tool_call_protocols(self):
"""测试 OpenAI 和 AG-UI 协议中的工具调用事件序列"""
from agentrun.server import AgentEvent, AgentRequest, EventType
async def streaming_invoke_agent(request: AgentRequest):
yield AgentEvent(
event=EventType.TOOL_CALL,
data={
"id": "tc-1",
"name": "weather_tool",
"args": '{"location": "Beijing"}',
},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={"id": "tc-1", "result": "Sunny, 25°C"},
)
client = self.get_client(streaming_invoke_agent)
# 测试 OpenAI 协议的工具调用
response_openai = client.post(
"/openai/v1/chat/completions",
json={
"messages": [
{"role": "user", "content": "What's the weather?"}
],
"stream": True,
},
)
assert response_openai.status_code == 200
lines_openai = [line async for line in response_openai.aiter_lines()]
lines_openai = [line for line in lines_openai if line]
# OpenAI 流式格式:包含工具调用的事件序列
# 1. role + tool_calls(包含 id, type, function.name, function.arguments)
# 2. tool_calls(包含 id 和 function.arguments delta)
# 3. finish_reason: tool_calls
# 4. [DONE]
assert len(lines_openai) == 4
# 第一个 chunk 包含工具调用信息(可能不包含role,具体取决于工具调用的类型)
assert lines_openai[0].startswith("data: {")
line0 = self.try_parse_streaming_line(lines_openai[0])
line0 = cast(dict, line0) # 类型断言
assert line0["object"] == "chat.completion.chunk"
assert "tool_calls" in line0["choices"][0]["delta"]
assert (
line0["choices"][0]["delta"]["tool_calls"][0]["type"] == "function"
)
assert (
line0["choices"][0]["delta"]["tool_calls"][0]["function"]["name"]
== "weather_tool"
)
assert line0["choices"][0]["delta"]["tool_calls"][0]["id"] == "tc-1"
# 第二个 chunk 包含函数参数(不包含ID,只有参数)
assert lines_openai[1].startswith("data: {")
line1 = self.try_parse_streaming_line(lines_openai[1])
line1 = cast(dict, line1) # 类型断言
assert line1["object"] == "chat.completion.chunk"
assert (
line1["choices"][0]["delta"]["tool_calls"][0]["function"][
"arguments"
]
== '{"location": "Beijing"}'
)
# 第三个 chunk 包含 finish_reason
assert lines_openai[2].startswith("data: {")
line2 = self.try_parse_streaming_line(lines_openai[2])
line2 = cast(dict, line2) # 类型断言
assert line2["object"] == "chat.completion.chunk"
assert line2["choices"][0]["finish_reason"] == "tool_calls"
# 最后是 [DONE]
assert lines_openai[3] == "data: [DONE]"
# 测试 AG-UI 协议的工具调用
response_agui = client.post(
"/ag-ui/agent",
json={
"messages": [{"role": "user", "content": "What's the weather?"}]
},
)
assert response_agui.status_code == 200
lines_agui = [line async for line in response_agui.aiter_lines()]
lines_agui = [line for line in lines_agui if line]
# AG-UI 流式格式:RUN_STARTED + TOOL_CALL_START + TOOL_CALL_ARGS + TOOL_CALL_END + TOOL_CALL_RESULT + RUN_FINISHED
# 注意:由于没有文本内容,所以不会触发 TEXT_MESSAGE_* 事件
# TOOL_CALL 会先触发 TOOL_CALL_START,然后是 TOOL_CALL_ARGS(使用 args_delta),最后是 TOOL_CALL_END
# TOOL_RESULT 会被转换为 TOOL_CALL_RESULT
self.valid_json(
lines_agui,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TOOL_CALL_START","toolCallId":"tc-1","toolCallName":"weather_tool"}'
),
(
"data:"
' {"type":"TOOL_CALL_ARGS","toolCallId":"tc-1","delta":"{\\"location\\":'
' \\"Beijing\\"}"}'
),
'data: {"type":"TOOL_CALL_END","toolCallId":"tc-1"}',
(
"data:"
' {"type":"TOOL_CALL_RESULT","messageId":"mock-placeholder","toolCallId":"tc-1","content":"Sunny,'
' 25°C","role":"tool"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("runId", [lines_agui[0], lines_agui[-1]])
self.all_field_equal("toolCallId", lines_agui[1:5])
@pytest.mark.asyncio
async def test_server_text_then_tool_call_agui(self):
"""测试 AG-UI 协议中先文本后工具调用的事件序列
AG-UI 协议要求:发送 TOOL_CALL_START 前必须先发送 TEXT_MESSAGE_END
"""
from agentrun.server import AgentEvent, AgentRequest, EventType
async def streaming_invoke_agent(request: AgentRequest):
# 先发送文本
yield "思考中..."
# 然后发送工具调用
yield AgentEvent(
event=EventType.TOOL_CALL_CHUNK,
data={
"id": "tc-1",
"name": "search_tool",
"args_delta": '{"query": "test"}',
},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={"id": "tc-1", "result": "搜索结果"},
)
client = self.get_client(streaming_invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "搜索一下"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines()]
lines = [line for line in lines if line]
# 预期事件序列:
# 1. RUN_STARTED
# 2. TEXT_MESSAGE_START
# 3. TEXT_MESSAGE_CONTENT
# 4. TEXT_MESSAGE_END <-- 必须在 TOOL_CALL_START 之前
# 5. TOOL_CALL_START
# 6. TOOL_CALL_ARGS
# 7. TOOL_CALL_END
# 8. TOOL_CALL_RESULT
# 9. RUN_FINISHED
self.valid_json(
lines,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"思考中..."}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TOOL_CALL_START","toolCallId":"tc-1","toolCallName":"search_tool"}'
),
(
"data:"
' {"type":"TOOL_CALL_ARGS","toolCallId":"tc-1","delta":"{\\"query\\":'
' \\"test\\"}"}'
),
'data: {"type":"TOOL_CALL_END","toolCallId":"tc-1"}',
(
"data:"
' {"type":"TOOL_CALL_RESULT","messageId":"mock-placeholder","toolCallId":"tc-1","content":"搜索结果","role":"tool"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines[0], lines[-1]])
self.all_field_equal("runId", [lines[0], lines[-1]])
self.all_field_equal("messageId", [lines[1], lines[2], lines[3]])
self.all_field_equal("toolCallId", lines[4:8])
@pytest.mark.asyncio
async def test_server_text_tool_text_agui(self):
"""测试 AG-UI 协议中 文本->工具调用->文本 的事件序列
场景:先输出思考内容,然后调用工具,最后输出结果
AG-UI 协议要求:
1. 发送 TOOL_CALL_START 前必须先发送 TEXT_MESSAGE_END
2. 工具调用后的新文本需要新的 TEXT_MESSAGE_START
"""
from agentrun.server import AgentEvent, AgentRequest, EventType
async def streaming_invoke_agent(request: AgentRequest):
# 第一段文本
yield "让我搜索一下..."
# 工具调用
yield AgentEvent(
event=EventType.TOOL_CALL_CHUNK,
data={
"id": "tc-1",
"name": "search",
"args_delta": '{"q": "天气"}',
},
)
yield AgentEvent(
event=EventType.TOOL_RESULT,
data={"id": "tc-1", "result": "晴天"},
)
# 第二段文本(工具调用后)
yield "根据搜索结果,今天是晴天。"
client = self.get_client(streaming_invoke_agent)
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "今天天气如何"}]},
)
assert response.status_code == 200
lines = [line async for line in response.aiter_lines()]
lines = [line for line in lines if line]
# 预期事件序列:
# 1. RUN_STARTED
# 2. TEXT_MESSAGE_START (第一个文本消息)
# 3. TEXT_MESSAGE_CONTENT
# 4. TEXT_MESSAGE_END <-- 工具调用前必须结束
# 5. TOOL_CALL_START
# 6. TOOL_CALL_ARGS
# 7. TOOL_CALL_END
# 8. TOOL_CALL_RESULT
# 9. TEXT_MESSAGE_START (第二个文本消息,新的 messageId)
# 10. TEXT_MESSAGE_CONTENT
# 11. TEXT_MESSAGE_END
# 12. RUN_FINISHED
self.valid_json(
lines,
[
(
"data:"
' {"type":"RUN_STARTED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"让我搜索一下..."}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"TOOL_CALL_START","toolCallId":"tc-1","toolCallName":"search"}'
),
(
"data:"
' {"type":"TOOL_CALL_ARGS","toolCallId":"tc-1","delta":"{\\"q\\":'
' \\"天气\\"}"}'
),
'data: {"type":"TOOL_CALL_END","toolCallId":"tc-1"}',
(
"data:"
' {"type":"TOOL_CALL_RESULT","messageId":"mock-placeholder","toolCallId":"tc-1","content":"晴天","role":"tool"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_START","messageId":"mock-placeholder","role":"assistant"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_CONTENT","messageId":"mock-placeholder","delta":"根据搜索结果,'
'今天是晴天。"}'
),
(
"data:"
' {"type":"TEXT_MESSAGE_END","messageId":"mock-placeholder"}'
),
(
"data:"
' {"type":"RUN_FINISHED","threadId":"mock-placeholder","runId":"mock-placeholder"}'
),
],
)
self.all_field_equal("threadId", [lines[0], lines[-1]])
self.all_field_equal("runId", [lines[0], lines[-1]])
self.all_field_equal("messageId", [lines[1], lines[2], lines[3]])
self.all_field_equal("toolCallId", lines[4:8])
@pytest.mark.asyncio
async def test_agent_request_raw_request(self):
"""测试 AgentRequest.raw_request 可以访问原始请求对象
验证:
1. raw_request 包含完整的 Starlette Request 对象
2. 可以访问 headers, query_params, client 等属性
"""
from agentrun.server import AgentRequest
captured_request: dict = {}
async def invoke_agent(request: AgentRequest):
# 捕获请求信息
captured_request["protocol"] = request.protocol
captured_request["has_raw_request"] = (
request.raw_request is not None
)
if request.raw_request:
captured_request["headers"] = dict(request.raw_request.headers)
captured_request["path"] = request.raw_request.url.path
captured_request["method"] = request.raw_request.method
return "Hello"
client = self.get_client(invoke_agent)
# 测试 AG-UI 协议
response = client.post(
"/ag-ui/agent",
json={"messages": [{"role": "user", "content": "test"}]},
headers={"X-Custom-Header": "custom-value"},
)
assert response.status_code == 200
# 验证捕获的请求信息
assert captured_request["protocol"] == "agui"
assert captured_request["has_raw_request"] is True
assert captured_request["path"] == "/ag-ui/agent"
assert captured_request["method"] == "POST"
assert (
captured_request["headers"].get("x-custom-header") == "custom-value"
)
# 重置
captured_request.clear()
# 测试 OpenAI 协议
response = client.post(
"/openai/v1/chat/completions",
json={"messages": [{"role": "user", "content": "test"}]},
headers={"Authorization": "Bearer test-token"},
)
assert response.status_code == 200
# 验证捕获的请求信息
assert captured_request["protocol"] == "openai"
assert captured_request["has_raw_request"] is True
assert captured_request["path"] == "/openai/v1/chat/completions"
assert (
captured_request["headers"].get("authorization")
== "Bearer test-token"
)