-
Notifications
You must be signed in to change notification settings - Fork 9.2k
Expand file tree
/
Copy pathtest_assistant_agent.py
More file actions
3627 lines (3066 loc) · 136 KB
/
Copy pathtest_assistant_agent.py
File metadata and controls
3627 lines (3066 loc) · 136 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
"""Comprehensive tests for AssistantAgent functionality."""
# Standard library imports
import asyncio
import json
import os
from typing import Any, List, Optional, Union, cast
from unittest.mock import AsyncMock, MagicMock, patch
# Third-party imports
import pytest
# First-party imports
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.agents._assistant_agent import AssistantAgentConfig
from autogen_agentchat.base import Handoff, Response, TaskResult
from autogen_agentchat.messages import (
BaseAgentEvent,
BaseChatMessage,
HandoffMessage,
MemoryQueryEvent,
ModelClientStreamingChunkEvent,
StructuredMessage,
TextMessage,
ThoughtEvent,
ToolCallExecutionEvent,
ToolCallRequestEvent,
ToolCallSummaryMessage,
)
from autogen_core import CancellationToken, ComponentModel, FunctionCall
from autogen_core.memory import Memory, MemoryContent, UpdateContextResult
from autogen_core.memory import MemoryQueryResult as MemoryQueryResultSet
from autogen_core.model_context import BufferedChatCompletionContext
from autogen_core.models import (
AssistantMessage,
CreateResult,
FunctionExecutionResult,
ModelFamily,
RequestUsage,
SystemMessage,
UserMessage,
)
from autogen_ext.models.anthropic import AnthropicChatCompletionClient
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.models.replay import ReplayChatCompletionClient
from autogen_ext.tools.mcp import McpWorkbench, SseServerParams
from pydantic import BaseModel, ValidationError
def mock_tool_function(param: str) -> str:
"""Mock tool function for testing.
Args:
param: Input parameter to process
Returns:
Formatted string with the input parameter
"""
return f"Tool executed with: {param}"
async def async_mock_tool_function(param: str) -> str:
"""Async mock tool function for testing.
Args:
param: Input parameter to process
Returns:
Formatted string with the input parameter
"""
return f"Async tool executed with: {param}"
def _pass_function(input: str) -> str:
"""Pass through function for testing.
Args:
input: Input to pass through
Returns:
The string "pass"
"""
return "pass"
def _echo_function(input: str) -> str:
"""Echo function for testing.
Args:
input: Input to echo
Returns:
The input string
"""
return input
class MockMemory(Memory):
"""Mock memory implementation for testing.
A simple memory implementation that stores strings and provides basic memory operations
for testing purposes.
Args:
contents: Optional list of initial memory contents
"""
def __init__(self, contents: Optional[List[str]] = None) -> None:
"""Initialize mock memory.
Args:
contents: Optional list of initial memory contents
"""
self._contents: List[str] = contents or []
async def add(self, content: MemoryContent, cancellation_token: Optional[CancellationToken] = None) -> None:
"""Add content to memory.
Args:
content: Content to add to memory
cancellation_token: Optional token for cancelling operation
"""
self._contents.append(str(content))
async def query(
self, query: Union[str, MemoryContent], cancellation_token: Optional[CancellationToken] = None, **kwargs: Any
) -> MemoryQueryResultSet:
"""Query memory contents.
Args:
query: Search query
cancellation_token: Optional token for cancelling operation
kwargs: Additional query parameters
Returns:
Query results containing all memory contents
"""
results = [MemoryContent(content=content, mime_type="text/plain") for content in self._contents]
return MemoryQueryResultSet(results=results)
async def clear(self, cancellation_token: Optional[CancellationToken] = None) -> None:
"""Clear all memory contents.
Args:
cancellation_token: Optional token for cancelling operation
"""
self._contents.clear()
async def close(self) -> None:
"""Close memory resources."""
pass
async def update_context(self, model_context: Any) -> UpdateContextResult:
"""Update model context with memory contents.
Args:
model_context: Context to update
Returns:
Update result containing memory contents
"""
if self._contents:
results = [MemoryContent(content=content, mime_type="text/plain") for content in self._contents]
return UpdateContextResult(memories=MemoryQueryResultSet(results=results))
return UpdateContextResult(memories=MemoryQueryResultSet(results=[]))
def dump_component(self) -> ComponentModel:
"""Dump memory state as component model.
Returns:
Component model representing memory state
"""
return ComponentModel(provider="test", config={"type": "mock_memory"})
class StructuredOutput(BaseModel):
"""Test structured output model.
Attributes:
content: Main content string
confidence: Confidence score between 0 and 1
"""
content: str
confidence: float
@pytest.mark.asyncio
async def test_model_client_stream() -> None:
mock_client = ReplayChatCompletionClient(
[
"Response to message 3",
]
)
agent = AssistantAgent(
"test_agent",
model_client=mock_client,
model_client_stream=True,
)
chunks: List[str] = []
async for message in agent.run_stream(task="task"):
if isinstance(message, TaskResult):
assert isinstance(message.messages[-1], TextMessage)
assert message.messages[-1].content == "Response to message 3"
elif isinstance(message, ModelClientStreamingChunkEvent):
chunks.append(message.content)
assert "".join(chunks) == "Response to message 3"
@pytest.mark.asyncio
async def test_model_client_stream_with_tool_calls() -> None:
mock_client = ReplayChatCompletionClient(
[
CreateResult(
content=[
FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),
FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),
],
finish_reason="function_calls",
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
"Example response 2 to task",
]
)
mock_client._model_info["function_calling"] = True # pyright: ignore
agent = AssistantAgent(
"test_agent",
model_client=mock_client,
model_client_stream=True,
reflect_on_tool_use=True,
tools=[_pass_function, _echo_function],
)
chunks: List[str] = []
async for message in agent.run_stream(task="task"):
if isinstance(message, TaskResult):
assert isinstance(message.messages[-1], TextMessage)
assert isinstance(message.messages[1], ToolCallRequestEvent)
assert message.messages[-1].content == "Example response 2 to task"
assert message.messages[1].content == [
FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),
FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),
]
assert isinstance(message.messages[2], ToolCallExecutionEvent)
assert message.messages[2].content == [
FunctionExecutionResult(call_id="1", content="pass", is_error=False, name="_pass_function"),
FunctionExecutionResult(call_id="3", content="task", is_error=False, name="_echo_function"),
]
elif isinstance(message, ModelClientStreamingChunkEvent):
chunks.append(message.content)
assert "".join(chunks) == "Example response 2 to task"
@pytest.mark.asyncio
async def test_invalid_structured_output_format() -> None:
class AgentResponse(BaseModel):
response: str
status: str
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content='{"response": "Hello"}',
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
]
)
agent = AssistantAgent(
name="assistant",
model_client=model_client,
output_content_type=AgentResponse,
)
with pytest.raises(ValidationError):
await agent.run()
@pytest.mark.asyncio
async def test_structured_message_factory_serialization() -> None:
class AgentResponse(BaseModel):
result: str
status: str
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content=AgentResponse(result="All good", status="ok").model_dump_json(),
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
]
)
agent = AssistantAgent(
name="structured_agent",
model_client=model_client,
output_content_type=AgentResponse,
output_content_type_format="{result} - {status}",
)
dumped = agent.dump_component()
restored_agent = AssistantAgent.load_component(dumped)
result = await restored_agent.run()
assert isinstance(result.messages[0], StructuredMessage)
assert result.messages[0].content.result == "All good" # type: ignore
assert result.messages[0].content.status == "ok" # type: ignore
@pytest.mark.asyncio
async def test_structured_message_format_string() -> None:
class AgentResponse(BaseModel):
field1: str
field2: str
expected = AgentResponse(field1="foo", field2="bar")
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content=expected.model_dump_json(),
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
]
)
agent = AssistantAgent(
name="formatted_agent",
model_client=model_client,
output_content_type=AgentResponse,
output_content_type_format="{field1} - {field2}",
)
result = await agent.run()
assert len(result.messages) == 1
message = result.messages[0]
# Check that it's a StructuredMessage with the correct content model
assert isinstance(message, StructuredMessage)
assert isinstance(message.content, AgentResponse) # type: ignore[reportUnknownMemberType]
assert message.content == expected
# Check that the format_string was applied correctly
assert message.to_model_text() == "foo - bar"
@pytest.mark.asyncio
async def test_tools_serialize_and_deserialize() -> None:
def test() -> str:
return "hello world"
client = OpenAIChatCompletionClient(
model="gpt-4o",
api_key="API_KEY",
)
agent = AssistantAgent(
name="test",
model_client=client,
tools=[test],
)
serialize = agent.dump_component()
deserialize = AssistantAgent.load_component(serialize)
assert deserialize.name == agent.name
for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore
assert await original.list_tools() == await restored.list_tools() # type: ignore
assert agent.component_version == deserialize.component_version
@pytest.mark.asyncio
async def test_workbench_serialize_and_deserialize() -> None:
workbench = McpWorkbench(server_params=SseServerParams(url="http://test-url"))
client = OpenAIChatCompletionClient(
model="gpt-4o",
api_key="API_KEY",
)
agent = AssistantAgent(
name="test",
model_client=client,
workbench=workbench,
)
serialize = agent.dump_component()
deserialize = AssistantAgent.load_component(serialize)
assert deserialize.name == agent.name
for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore
assert isinstance(original, McpWorkbench)
assert isinstance(restored, McpWorkbench)
assert original._to_config() == restored._to_config() # type: ignore
@pytest.mark.asyncio
async def test_multiple_workbenches_serialize_and_deserialize() -> None:
workbenches: List[McpWorkbench] = [
McpWorkbench(server_params=SseServerParams(url="http://test-url-1")),
McpWorkbench(server_params=SseServerParams(url="http://test-url-2")),
]
client = OpenAIChatCompletionClient(
model="gpt-4o",
api_key="API_KEY",
)
agent = AssistantAgent(
name="test_multi",
model_client=client,
workbench=workbenches,
)
serialize = agent.dump_component()
deserialized_agent: AssistantAgent = AssistantAgent.load_component(serialize)
assert deserialized_agent.name == agent.name
assert isinstance(deserialized_agent._workbench, list) # type: ignore
assert len(deserialized_agent._workbench) == len(workbenches) # type: ignore
for original, restored in zip(agent._workbench, deserialized_agent._workbench, strict=True): # type: ignore
assert isinstance(original, McpWorkbench)
assert isinstance(restored, McpWorkbench)
assert original._to_config() == restored._to_config() # type: ignore
@pytest.mark.asyncio
async def test_tools_deserialize_aware() -> None:
dump = """
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
"version": 1,
"component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
"name": "TestAgent",
"model_client":{
"provider": "autogen_ext.models.replay.ReplayChatCompletionClient",
"component_type": "replay_chat_completion_client",
"version": 1,
"component_version": 1,
"description": "A mock chat completion client that replays predefined responses using an index-based approach.",
"label": "ReplayChatCompletionClient",
"config": {
"chat_completions": [
{
"finish_reason": "function_calls",
"content": [
{
"id": "hello",
"arguments": "{}",
"name": "hello"
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0
},
"cached": false
}
],
"model_info": {
"vision": false,
"function_calling": true,
"json_output": false,
"family": "unknown",
"structured_output": false
}
}
},
"tools": [
{
"provider": "autogen_core.tools.FunctionTool",
"component_type": "tool",
"version": 1,
"component_version": 1,
"description": "Create custom tools by wrapping standard Python functions.",
"label": "FunctionTool",
"config": {
"source_code": "def hello():\\n return 'Hello, World!'\\n",
"name": "hello",
"description": "",
"global_imports": [],
"has_cancellation_support": false
}
}
],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
"version": 1,
"component_version": 1,
"description": "An unbounded chat completion context that keeps a view of the all the messages.",
"label": "UnboundedChatCompletionContext",
"config": {}
},
"description": "An agent that provides assistance with ability to use tools.",
"system_message": "You are a helpful assistant.",
"model_client_stream": false,
"reflect_on_tool_use": false,
"tool_call_summary_format": "{result}",
"metadata": {}
}
}
"""
# Test that agent can be deserialized from configuration
config = json.loads(dump)
agent = AssistantAgent.load_component(config)
# Verify the agent was loaded correctly
assert agent.name == "TestAgent"
assert agent.description == "An agent that provides assistance with ability to use tools."
class TestAssistantAgentToolCallLoop:
"""Test suite for tool call loop functionality.
Tests the behavior of AssistantAgent's tool call loop feature, which allows
multiple sequential tool calls before producing a final response.
"""
@pytest.mark.asyncio
async def test_tool_call_loop_enabled(self) -> None:
"""Test that tool call loop works when enabled.
Verifies that:
1. Multiple tool calls are executed in sequence
2. Loop continues until non-tool response
3. Final response is correct type
"""
# Create mock client with multiple tool calls followed by text response
model_client = ReplayChatCompletionClient(
[
# First tool call
CreateResult(
finish_reason="function_calls",
content=[FunctionCall(id="1", arguments=json.dumps({"param": "first"}), name="mock_tool_function")],
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
# Second tool call (loop continues)
CreateResult(
finish_reason="function_calls",
content=[
FunctionCall(id="2", arguments=json.dumps({"param": "second"}), name="mock_tool_function")
],
usage=RequestUsage(prompt_tokens=12, completion_tokens=5),
cached=False,
),
# Final text response (loop ends)
CreateResult(
finish_reason="stop",
content="Task completed successfully!",
usage=RequestUsage(prompt_tokens=15, completion_tokens=10),
cached=False,
),
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
tools=[mock_tool_function],
max_tool_iterations=3,
)
result = await agent.run(task="Execute multiple tool calls")
# Verify multiple model calls were made
assert len(model_client.create_calls) == 3, f"Expected 3 calls, got {len(model_client.create_calls)}"
# Verify final response is text
final_message = result.messages[-1]
assert isinstance(final_message, TextMessage)
assert final_message.content == "Task completed successfully!"
@pytest.mark.asyncio
async def test_tool_call_loop_disabled_default(self) -> None:
"""Test that tool call loop is disabled by default.
Verifies that:
1. Only one tool call is made when loop is disabled
2. Agent returns after first tool call
"""
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="function_calls",
content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
tools=[mock_tool_function],
max_tool_iterations=1,
)
result = await agent.run(task="Execute single tool call")
# Should only make one model call
assert len(model_client.create_calls) == 1, f"Expected 1 call, got {len(model_client.create_calls)}"
assert result is not None
@pytest.mark.asyncio
async def test_tool_call_loop_max_iterations(self) -> None:
"""Test that tool call loop respects max_iterations limit."""
# Create responses that would continue forever without max_iterations
responses: List[CreateResult] = []
for i in range(15): # More than default max_iterations (10)
responses.append(
CreateResult(
finish_reason="function_calls",
content=[
FunctionCall(id=str(i), arguments=json.dumps({"param": f"call_{i}"}), name="mock_tool_function")
],
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
)
model_client = ReplayChatCompletionClient(
responses,
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
tools=[mock_tool_function],
max_tool_iterations=5, # Set max iterations to 5
)
result = await agent.run(task="Test max iterations")
# Should stop at max_iterations
assert len(model_client.create_calls) == 5, f"Expected 5 calls, got {len(model_client.create_calls)}"
# Verify result is not None
assert result is not None
@pytest.mark.asyncio
async def test_tool_call_loop_with_handoff(self) -> None:
"""Test that tool call loop stops on handoff."""
model_client = ReplayChatCompletionClient(
[
# Tool call followed by handoff
CreateResult(
finish_reason="function_calls",
content=[
FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function"),
FunctionCall(
id="2", arguments=json.dumps({"target": "other_agent"}), name="transfer_to_other_agent"
),
],
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
tools=[mock_tool_function],
handoffs=["other_agent"],
max_tool_iterations=1,
)
result = await agent.run(task="Test handoff in loop")
# Should stop at handoff
assert len(model_client.create_calls) == 1, f"Expected 1 call, got {len(model_client.create_calls)}"
# Should return HandoffMessage
assert isinstance(result.messages[-1], HandoffMessage)
@pytest.mark.asyncio
async def test_tool_call_config_validation(self) -> None:
"""Test that ToolCallConfig validation works correctly."""
# Test that max_iterations must be >= 1
with pytest.raises(
ValueError, match="Maximum number of tool iterations must be greater than or equal to 1, got 0"
):
AssistantAgent(
name="test_agent",
model_client=MagicMock(),
max_tool_iterations=0, # Should raise error
)
class TestAssistantAgentInitialization:
"""Test suite for AssistantAgent initialization.
Tests various initialization scenarios and configurations of the AssistantAgent class.
"""
@pytest.mark.asyncio
async def test_basic_initialization(self) -> None:
"""Test basic agent initialization with minimal parameters.
Verifies that:
1. Agent initializes with required parameters
2. Default values are set correctly
3. Basic functionality works
"""
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content="Hello!",
usage=RequestUsage(prompt_tokens=5, completion_tokens=2),
cached=False,
)
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(name="test_agent", model_client=model_client)
result = await agent.run(task="Say hello")
assert isinstance(result.messages[-1], TextMessage)
assert result.messages[-1].content == "Hello!"
@pytest.mark.asyncio
async def test_initialization_with_tools(self) -> None:
"""Test agent initialization with tools.
Verifies that:
1. Agent accepts tool configurations
2. Tools are properly registered
3. Tool calls work correctly
"""
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="function_calls",
content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
tools=[mock_tool_function],
)
result = await agent.run(task="Use the tool")
assert isinstance(result.messages[-1], ToolCallSummaryMessage)
assert "Tool executed with: test" in result.messages[-1].content
@pytest.mark.asyncio
async def test_initialization_with_memory(self) -> None:
"""Test agent initialization with memory.
Verifies that:
1. Memory is properly integrated
2. Memory contents affect responses
3. Memory updates work correctly
"""
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content="Using memory content",
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
)
],
model_info={
"function_calling": True,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
memory = MockMemory(contents=["Test memory content"])
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
memory=[memory],
)
result = await agent.run(task="Use memory")
assert isinstance(result.messages[-1], TextMessage)
assert result.messages[-1].content == "Using memory content"
@pytest.mark.asyncio
async def test_initialization_with_handoffs(self) -> None:
"""Test agent initialization with handoffs."""
model_client = MagicMock()
model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
handoffs=["agent1", Handoff(target="agent2")],
)
assert len(agent._handoffs) == 2 # type: ignore[reportPrivateUsage]
assert "transfer_to_agent1" in agent._handoffs # type: ignore[reportPrivateUsage]
assert "transfer_to_agent2" in agent._handoffs # type: ignore[reportPrivateUsage]
@pytest.mark.asyncio
async def test_initialization_with_custom_model_context(self) -> None:
"""Test agent initialization with custom model context."""
model_client = MagicMock()
model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}
model_context = BufferedChatCompletionContext(buffer_size=5)
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
model_context=model_context,
)
assert agent._model_context == model_context # type: ignore[reportPrivateUsage]
@pytest.mark.asyncio
async def test_initialization_with_structured_output(self) -> None:
"""Test agent initialization with structured output."""
model_client = MagicMock()
model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
output_content_type=StructuredOutput,
)
assert agent._output_content_type == StructuredOutput # type: ignore[reportPrivateUsage]
assert agent._reflect_on_tool_use is True # type: ignore[reportPrivateUsage] # Should be True by default with structured output
@pytest.mark.asyncio
async def test_initialization_with_metadata(self) -> None:
"""Test agent initialization with metadata."""
model_client = MagicMock()
model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}
metadata = {"key1": "value1", "key2": "value2"}
agent = AssistantAgent(
name="test_agent",
model_client=model_client,
metadata=metadata,
)
assert agent._metadata == metadata # type: ignore[reportPrivateUsage]
@pytest.mark.asyncio
async def test_output_task_messages_false(self) -> None:
"""Test agent with output_task_messages=False.
Verifies that:
1. Task messages are excluded from result when output_task_messages=False
2. Only agent response messages are included in output
3. Both run and run_stream respect the parameter
"""
model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content="Agent response without task message",
usage=RequestUsage(prompt_tokens=10, completion_tokens=8),
cached=False,
),
CreateResult(
finish_reason="stop",
content="Second agent response",
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
],
model_info={
"function_calling": False,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
agent = AssistantAgent(name="test_agent", model_client=model_client)
# Test run() with output_task_messages=False
result = await agent.run(task="Test task message", output_task_messages=False)
# Should only contain the agent's response, not the task message
assert len(result.messages) == 1
assert isinstance(result.messages[0], TextMessage)
assert result.messages[0].content == "Agent response without task message"
assert result.messages[0].source == "test_agent" # Test run_stream() with output_task_messages=False
# Create a new model client for streaming test to avoid response conflicts
stream_model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content="Stream agent response",
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
],
model_info={
"function_calling": False,
"vision": False,
"json_output": False,
"family": ModelFamily.GPT_4O,
"structured_output": False,
},
)
stream_agent = AssistantAgent(name="test_agent", model_client=stream_model_client)
streamed_messages: List[BaseAgentEvent | BaseChatMessage] = []
final_result: TaskResult | None = None
async for message in stream_agent.run_stream(task="Test task message", output_task_messages=False):
if isinstance(message, TaskResult):
final_result = message
else:
streamed_messages.append(message)
# Verify streaming behavior
assert final_result is not None
assert len(final_result.messages) == 1
assert isinstance(final_result.messages[0], TextMessage)
assert final_result.messages[0].content == "Stream agent response"
# Verify that no task message was streamed
task_messages = [msg for msg in streamed_messages if isinstance(msg, TextMessage) and msg.source == "user"]
assert len(task_messages) == 0 # Test with multiple task messages
multi_model_client = ReplayChatCompletionClient(
[
CreateResult(
finish_reason="stop",
content="Multi task response",
usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
cached=False,
),
],
model_info={
"function_calling": False,