-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathtest_agent.py
More file actions
2138 lines (1780 loc) · 96.2 KB
/
Copy pathtest_agent.py
File metadata and controls
2138 lines (1780 loc) · 96.2 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
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
#
# SPDX-License-Identifier: Apache-2.0
import logging
import os
import re
from collections.abc import Iterator
from datetime import datetime
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from jinja2 import TemplateSyntaxError
from openai import Stream
from openai.types.chat import ChatCompletionChunk, chat_completion_chunk
from haystack import Document, Pipeline, component
from haystack.components.agents.agent import Agent
from haystack.components.agents.state import State, merge_lists, replace_values
from haystack.components.agents.tool_calling import _run_tool
from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
from haystack.components.builders.prompt_builder import PromptBuilder
from haystack.components.generators.chat import MockChatGenerator
from haystack.components.generators.chat.openai import OpenAIChatGenerator
from haystack.components.joiners.branch import BranchJoiner
from haystack.components.joiners.list_joiner import ListJoiner
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.routers.conditional_router import ConditionalRouter
from haystack.core.component.types import OutputSocket
from haystack.dataclasses import ChatMessage, ToolCall
from haystack.dataclasses.chat_message import ChatRole, TextContent
from haystack.dataclasses.streaming_chunk import StreamingChunk
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.hooks import hook
from haystack.tools import ComponentTool, Tool
from haystack.tools.toolset import Toolset
from haystack.utils import Secret
def _user_msg(text: str) -> str:
return f'{{% message role="user" %}}{text}{{% endmessage %}}'
def _sys_msg(text: str) -> str:
return f'{{% message role="system" %}}{text}{{% endmessage %}}'
def _assistant_with_usage(text: str | None = None, *, tool_calls=None, usage: dict[str, Any] | None = None):
"""Build an assistant ChatMessage with optional tool_calls and `meta['usage']` populated."""
meta: dict[str, Any] = {}
if usage is not None:
meta["usage"] = usage
if tool_calls is not None:
return ChatMessage.from_assistant(tool_calls=tool_calls, meta=meta or None)
return ChatMessage.from_assistant(text or "", meta=meta or None)
def sync_streaming_callback(chunk: StreamingChunk) -> None:
"""A synchronous streaming callback."""
pass
async def async_streaming_callback(chunk: StreamingChunk) -> None:
"""An asynchronous streaming callback."""
pass
def weather_function(location):
weather_info = {
"berlin": {"weather": "mostly sunny", "temperature": 7, "unit": "celsius"},
"paris": {"weather": "mostly cloudy", "temperature": 8, "unit": "celsius"},
"rome": {"weather": "sunny", "temperature": 14, "unit": "celsius"},
}
for city, result in weather_info.items():
if city in location.lower():
return result
return {"weather": "unknown", "temperature": 0, "unit": "celsius"}
@pytest.fixture
def weather_tool():
return Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters={"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]},
function=weather_function,
)
@pytest.fixture
def component_tool():
return ComponentTool(name="parrot", description="This is a parrot.", component=PromptBuilder(template="{{parrot}}"))
@pytest.fixture
def make_agent(weather_tool):
def _factory(**kwargs):
return Agent(chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], **kwargs)
return _factory
class OpenAIMockStream(Stream[ChatCompletionChunk]):
def __init__(self, mock_chunk: ChatCompletionChunk, client=None, *args, **kwargs):
client = client or MagicMock()
super().__init__(client=client, *args, **kwargs) # noqa: B026
self.mock_chunk = mock_chunk
def __stream__(self) -> Iterator[ChatCompletionChunk]:
yield self.mock_chunk
@pytest.fixture
def openai_mock_chat_completion_chunk():
"""
Mock the OpenAI API completion chunk response and reuse it for tests
"""
with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
completion = ChatCompletionChunk(
id="foo",
model="gpt-4",
object="chat.completion.chunk",
choices=[
chat_completion_chunk.Choice(
finish_reason="stop",
logprobs=None,
index=0,
delta=chat_completion_chunk.ChoiceDelta(content="Hello", role="assistant"),
)
],
created=int(datetime.now().timestamp()),
usage=None,
)
mock_chat_completion_create.return_value = OpenAIMockStream(
completion, cast_to=None, response=None, client=None
)
yield mock_chat_completion_create
@component
class MockChatGeneratorWithoutTools:
"""A mock chat generator that implements ChatGenerator protocol but doesn't support tools."""
def to_dict(self) -> dict[str, Any]:
return {"type": "test.components.agents.test_agent.MockChatGeneratorWithoutTools", "init_parameters": {}}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "MockChatGeneratorWithoutTools":
return cls()
@component.output_types(replies=list[ChatMessage])
def run(self, messages: list[ChatMessage]) -> dict[str, Any]:
return {"replies": [ChatMessage.from_assistant("Hello")]}
@component
class MockChatGeneratorWithoutRunAsync:
"""A mock chat generator that implements ChatGenerator protocol but doesn't have run_async method."""
def to_dict(self) -> dict[str, Any]:
return {"type": "MockChatGeneratorWithoutRunAsync", "data": {}}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "MockChatGeneratorWithoutRunAsync":
return cls()
@component.output_types(replies=list[ChatMessage])
def run(self, messages: list[ChatMessage], tools: list[Tool] | Toolset | None = None, **kwargs) -> dict[str, Any]:
return {"replies": [ChatMessage.from_assistant("Hello")]}
@component
class ToolAssertingChatGenerator:
"""Asserts the Agent forwards the expected tools, then drives one tool call before a plain reply."""
def __init__(self, expected_tools):
self.expected_tools = expected_tools
self.tool_invoked = False
@component.output_types(replies=list[ChatMessage])
def run(self, messages: list[ChatMessage], tools: list[Tool] | Toolset | None = None, **kwargs) -> dict[str, Any]:
assert tools == self.expected_tools
tool_message = ChatMessage.from_assistant(
tool_calls=[ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})]
)
message = tool_message if not self.tool_invoked else ChatMessage.from_assistant("Hello")
self.tool_invoked = True
return {"replies": [message]}
def _parallel_tool_calling_generator() -> MockChatGenerator:
"""Requests two `weather_tool` calls on the first turn, then returns a plain reply so the agent loop exits."""
return MockChatGenerator(
[
ChatMessage.from_assistant(
tool_calls=[
ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Paris"}),
]
),
"done",
]
)
class TestAgentInit:
def test_state_schema_resolution(self, weather_tool):
agent = Agent(
chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], state_schema={"foo": {"type": str}}
)
assert agent.state_schema == {"foo": {"type": str}}
assert agent.resolved_state_schema == {
"foo": {"type": str},
"messages": {"type": list[ChatMessage], "handler": merge_lists},
"step_count": {"type": int, "handler": replace_values},
"token_usage": {"type": dict[str, Any], "handler": replace_values},
"tool_call_counts": {"type": dict[str, int], "handler": replace_values},
"exit_reason": {"type": str, "handler": replace_values},
"continue_run": {"type": bool, "handler": replace_values},
"tools": {"type": list, "handler": replace_values},
"hook_context": {"type": dict[str, Any], "handler": replace_values},
"context_tokens": {"type": int, "handler": replace_values},
}
def test_output_types(self, weather_tool, component_tool, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
chat_generator = OpenAIChatGenerator()
agent = Agent(chat_generator=chat_generator, tools=[weather_tool, component_tool])
assert agent.__haystack_output__._sockets_dict == {
"messages": OutputSocket(name="messages", type=list[ChatMessage], receivers=[]),
"last_message": OutputSocket(name="last_message", type=ChatMessage, receivers=[]),
"step_count": OutputSocket(name="step_count", type=int, receivers=[]),
"token_usage": OutputSocket(name="token_usage", type=dict[str, Any], receivers=[]),
"tool_call_counts": OutputSocket(name="tool_call_counts", type=dict[str, int], receivers=[]),
"exit_reason": OutputSocket(name="exit_reason", type=str, receivers=[]),
}
# Check that the run-metadata keys are not set up as input sockets
assert {"step_count", "token_usage", "tool_call_counts", "exit_reason"}.isdisjoint(
agent.__haystack_input__._sockets_dict.keys()
)
# Internal-only state keys (those that are not also run parameters) are exposed as neither inputs nor outputs.
for internal_key in ("continue_run", "context_tokens"):
assert internal_key not in agent.__haystack_input__._sockets_dict
assert internal_key not in agent.__haystack_output__._sockets_dict
def test_reserved_state_schema_keys_raise(self, weather_tool):
for reserved in ("step_count", "token_usage", "context_tokens", "tool_call_counts", "exit_reason"):
with pytest.raises(ValueError, match="reserved for Agent internal state"):
Agent(
chat_generator=MockChatGenerator("Hello"),
tools=[weather_tool],
state_schema={reserved: {"type": int}},
)
def test_exit_conditions(self, weather_tool, component_tool):
# Default exit condition
agent = Agent(chat_generator=MockChatGenerator("Hello"), tools=[weather_tool, component_tool])
assert agent.exit_conditions == ["text"]
# Multiple exit conditions are stored as-is
agent = Agent(
chat_generator=MockChatGenerator("Hello"),
tools=[weather_tool, component_tool],
exit_conditions=["text", "weather_tool"],
)
assert agent.exit_conditions == ["text", "weather_tool"]
# Exit conditions are no longer validated against tool names at init: tool sets can be dynamic
# (e.g. SearchableToolset/MCPToolset) or provided at runtime, so unknown names pass through.
agent = Agent(
chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], exit_conditions=["not_loaded_yet"]
)
assert agent.exit_conditions == ["not_loaded_yet"]
def test_tool_concurrency_limit_validation(self, weather_tool):
with pytest.raises(ValueError, match="tool_concurrency_limit must be greater than or equal to 1"):
Agent(chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], tool_concurrency_limit=0)
def test_chat_generator_must_support_tools(self, weather_tool):
chat_generator = MockChatGeneratorWithoutTools()
with pytest.raises(TypeError, match="MockChatGeneratorWithoutTools does not accept tools"):
Agent(chat_generator=chat_generator, tools=[weather_tool])
def test_empty_tools_list_with_chat_generator_without_tools_support(self):
# An empty list carries no tools, so it must be accepted just like `tools=None`. `run()` already
# treats it that way, and `clone()`/`to_dict()` both feed the normalized `[]` back into `__init__`.
agent = Agent(chat_generator=MockChatGeneratorWithoutTools(), tools=[])
assert agent.tools == []
class TestAgentSerialization:
def test_to_dict(self, weather_tool, component_tool, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
generator = OpenAIChatGenerator()
agent = Agent(
chat_generator=generator,
tools=[weather_tool, component_tool],
exit_conditions=["text", "weather_tool"],
state_schema={"foo": {"type": str}},
tool_concurrency_limit=5,
tool_streaming_callback_passthrough=True,
)
serialized_agent = agent.to_dict()
# Verify the model is truthy and serialized
assert "model" in serialized_agent["init_parameters"]["chat_generator"]["init_parameters"]
model_name = serialized_agent["init_parameters"]["chat_generator"]["init_parameters"]["model"]
# Check the rest of the structure
expected_structure = {
"type": "haystack.components.agents.agent.Agent",
"init_parameters": {
"chat_generator": {
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
"init_parameters": {
"model": model_name,
"streaming_callback": None,
"api_base_url": None,
"organization": None,
"generation_kwargs": {},
"api_key": {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": True},
"timeout": None,
"max_retries": None,
"tools": None,
"tools_strict": False,
"http_client_kwargs": None,
},
},
"tools": [
{
"type": "haystack.tools.tool.Tool",
"data": {
"name": "weather_tool",
"description": "Provides weather information for a given location.",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
"function": "agents.test_agent.weather_function",
"async_function": None,
"outputs_to_string": None,
"inputs_from_state": None,
"outputs_to_state": None,
},
},
{
"type": "haystack.tools.component_tool.ComponentTool",
"data": {
"component": {
"type": "haystack.components.builders.prompt_builder.PromptBuilder",
"init_parameters": {
"template": "{{parrot}}",
"variables": None,
"required_variables": "*",
},
},
"name": "parrot",
"description": "This is a parrot.",
"parameters": None,
"outputs_to_string": None,
"inputs_from_state": None,
"outputs_to_state": None,
},
},
],
"system_prompt": None,
"user_prompt": None,
"required_variables": "*",
"exit_conditions": ["text", "weather_tool"],
"state_schema": {"foo": {"type": "str"}},
"max_agent_steps": 100,
"streaming_callback": None,
"raise_on_tool_invocation_failure": False,
"tool_concurrency_limit": 5,
"tool_streaming_callback_passthrough": True,
"hooks": None,
},
}
assert serialized_agent == expected_structure
def test_from_dict(self, monkeypatch):
model = "gpt-5"
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
data = {
"type": "haystack.components.agents.agent.Agent",
"init_parameters": {
"chat_generator": {
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
"init_parameters": {
"model": model,
"streaming_callback": None,
"api_base_url": None,
"organization": None,
"generation_kwargs": {},
"api_key": {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": True},
"timeout": None,
"max_retries": None,
"tools": None,
"tools_strict": False,
"http_client_kwargs": None,
},
},
"tools": [
{
"type": "haystack.tools.tool.Tool",
"data": {
"name": "weather_tool",
"description": "Provides weather information for a given location.",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
"function": "agents.test_agent.weather_function",
"async_function": None,
"outputs_to_string": None,
"inputs_from_state": None,
"outputs_to_state": None,
},
},
{
"type": "haystack.tools.component_tool.ComponentTool",
"data": {
"component": {
"type": "haystack.components.builders.prompt_builder.PromptBuilder",
"init_parameters": {
"template": "{{parrot}}",
"variables": None,
"required_variables": "*",
},
},
"name": "parrot",
"description": "This is a parrot.",
"parameters": None,
"outputs_to_string": None,
"inputs_from_state": None,
"outputs_to_state": None,
},
},
],
"system_prompt": None,
"exit_conditions": ["text", "weather_tool"],
"state_schema": {"foo": {"type": "str"}},
"max_agent_steps": 100,
"raise_on_tool_invocation_failure": False,
"streaming_callback": None,
"tool_concurrency_limit": 5,
"tool_streaming_callback_passthrough": True,
},
}
agent = Agent.from_dict(data)
assert isinstance(agent, Agent)
assert isinstance(agent.chat_generator, OpenAIChatGenerator)
# from_dict should restore the model from the dict (testing backward compatibility)
assert agent.chat_generator.model == model
assert agent.chat_generator.api_key == Secret.from_env_var("OPENAI_API_KEY")
assert agent.tools[0].function is weather_function
assert isinstance(agent.tools[1]._component, PromptBuilder)
assert agent.exit_conditions == ["text", "weather_tool"]
assert agent.state_schema == {"foo": {"type": str}}
assert agent.tool_concurrency_limit == 5
assert agent.tool_streaming_callback_passthrough is True
def test_from_dict_state_schema_none(self, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
data = {
"type": "haystack.components.agents.agent.Agent",
"init_parameters": {
"chat_generator": {
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
"init_parameters": {"model": "gpt-4o-mini"},
},
"state_schema": None,
},
}
agent = Agent.from_dict(data)
assert agent.state_schema == {}
def test_serde(self, weather_tool, component_tool, monkeypatch):
monkeypatch.setenv("FAKE_OPENAI_KEY", "fake-key")
generator = OpenAIChatGenerator(api_key=Secret.from_env_var("FAKE_OPENAI_KEY"))
agent = Agent(
chat_generator=generator,
tools=[weather_tool, component_tool],
exit_conditions=["text", "weather_tool"],
state_schema={"foo": {"type": str}},
streaming_callback=sync_streaming_callback,
)
deserialized_agent = Agent.from_dict(agent.to_dict())
assert deserialized_agent.to_dict() == agent.to_dict()
assert isinstance(deserialized_agent.chat_generator, OpenAIChatGenerator)
assert deserialized_agent.tools[0].function is weather_function
assert isinstance(deserialized_agent.tools[1]._component, PromptBuilder)
assert deserialized_agent.streaming_callback is sync_streaming_callback
def test_serde_with_toolset(self, weather_tool, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
agent = Agent(chat_generator=OpenAIChatGenerator(), tools=Toolset(tools=[weather_tool]))
restored = Agent.from_dict(agent.to_dict())
assert isinstance(restored.tools, Toolset)
assert restored.tools[0].function is weather_function
def test_serde_with_list_of_toolsets(self, weather_tool, component_tool, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
agent = Agent(chat_generator=OpenAIChatGenerator(), tools=[Toolset([weather_tool]), Toolset([component_tool])])
restored = Agent.from_dict(agent.to_dict())
assert isinstance(restored.tools, list)
assert len(restored.tools) == 2
assert all(isinstance(ts, Toolset) for ts in restored.tools)
assert restored.tools[0][0].function is weather_function
def test_to_dict_from_dict_without_tools(self):
# `to_dict` serializes the normalized `self.tools`, which is `[]` when no tools were given.
# `from_dict` hands that `[]` straight back to `__init__`, so the round trip must survive it.
agent = Agent(chat_generator=MockChatGeneratorWithoutTools(), max_agent_steps=3)
data = agent.to_dict()
assert data["init_parameters"]["tools"] == []
restored = Agent.from_dict(data)
assert restored.tools == []
assert restored.max_agent_steps == 3
assert type(restored.chat_generator).__name__ == "MockChatGeneratorWithoutTools"
class TestAgentClone:
def test_clone_without_tools(self):
# `clone()` reads back the normalized `self.tools` (`[]`) and passes it to `__init__`.
agent = Agent(chat_generator=MockChatGeneratorWithoutTools(), system_prompt="You are helpful")
clone = agent.clone()
assert clone is not agent
assert clone.tools == []
assert clone.to_dict() == agent.to_dict()
def test_clone(self, weather_tool):
agent = Agent(
chat_generator=MockChatGenerator("Hello"),
tools=[weather_tool],
system_prompt="You are helpful",
exit_conditions=["text", "weather_tool"],
state_schema={"foo": {"type": str}},
max_agent_steps=7,
)
clone = agent.clone()
assert clone is not agent
assert clone.to_dict() == agent.to_dict()
@pytest.mark.parametrize(
"name, value",
[
("system_prompt", "A nice system prompt"),
("max_agent_steps", 3),
("exit_conditions", ["weather_tool"]),
("state_schema", {"bar": {"type": int}}),
],
)
def test_clone_with_overrides(self, weather_tool, name, value):
agent = Agent(
chat_generator=MockChatGenerator("Hello"),
tools=[weather_tool],
system_prompt="You are helpful",
state_schema={"foo": {"type": str}},
)
clone = agent.clone(**{name: value})
assert getattr(clone, name) == value
# only the overridden init parameter differs
original_params = agent.to_dict()["init_parameters"]
clone_params = clone.to_dict()["init_parameters"]
assert clone_params.keys() == original_params.keys()
for key in original_params:
if key == name:
assert clone_params[key] != original_params[key]
else:
assert clone_params[key] == original_params[key]
def test_clone_with_additional_state_schema_and_tools(self, weather_tool, component_tool):
agent = Agent(
chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], state_schema={"foo": {"type": str}}
)
clone = agent.clone(
tools=[*agent.tools, component_tool], state_schema={**agent.state_schema, "notes": {"type": str}}
)
assert clone.tools == [weather_tool, component_tool]
assert clone.state_schema == {"foo": {"type": str}, "notes": {"type": str}}
class TestAgentRun:
def test_agent_with_no_tools(self):
agent = Agent(chat_generator=MockChatGenerator("Berlin"), tools=[], max_agent_steps=3)
response = agent.run([ChatMessage.from_user("What is the capital of Germany?")])
assert isinstance(response, dict)
assert "messages" in response
assert isinstance(response["messages"], list)
assert len(response["messages"]) == 2
assert response["messages"][0].text == "What is the capital of Germany?"
assert response["messages"][1].text == "Berlin"
assert "last_message" in response
assert isinstance(response["last_message"], ChatMessage)
assert response["messages"][-1] == response["last_message"]
# With no tools the loop always exits after the first reply, reporting the "text" exit reason.
assert response["exit_reason"] == "text"
def test_no_tools_with_chat_generator_without_tools_support(self):
chat_generator = MockChatGeneratorWithoutTools()
agent = Agent(chat_generator=chat_generator, max_agent_steps=1)
response = agent.run(messages=[ChatMessage.from_user("Hello")])
assert isinstance(response, dict)
assert "messages" in response
assert len(response["messages"]) == 2
assert response["messages"][0].text == "Hello"
assert response["messages"][1].text == "Hello"
assert response["last_message"] == response["messages"][-1]
def test_run_with_system_prompt(self, weather_tool):
chat_generator = MockChatGeneratorWithoutRunAsync()
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], system_prompt="This is a system prompt.")
response = agent.run([ChatMessage.from_user("What is the weather in Berlin?")])
assert response["messages"][0].text == "This is a system prompt."
def test_run_only_system_prompt(self, caplog):
chat_generator = MockChatGeneratorWithoutRunAsync()
agent = Agent(chat_generator=chat_generator, tools=[], system_prompt="This is a system prompt.")
_ = agent.run([])
assert "All messages provided to the Agent component are system messages." in caplog.text
def test_run_no_messages(self, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "fake-key")
agent = Agent(chat_generator=OpenAIChatGenerator(), tools=[])
result = agent.run([])
assert result["messages"] == []
def test_run_with_tools_run_param(self, weather_tool: Tool, component_tool: Tool):
chat_generator = ToolAssertingChatGenerator(expected_tools=[weather_tool])
agent = Agent(
chat_generator=chat_generator,
tools=[component_tool],
system_prompt="This is a system prompt.",
tool_concurrency_limit=3,
tool_streaming_callback_passthrough=True,
)
with patch("haystack.components.agents.agent._run_tool", wraps=_run_tool) as run_tool_mock:
agent.run([ChatMessage.from_user("What is the weather in Berlin?")], tools=[weather_tool])
run_tool_mock.assert_called_once()
assert run_tool_mock.call_args.kwargs["tools"] == [weather_tool]
assert run_tool_mock.call_args.kwargs["max_workers"] == 3
assert run_tool_mock.call_args.kwargs["enable_streaming_callback_passthrough"] is True
def test_run_with_tools_run_param_for_tool_selection(self, weather_tool: Tool, component_tool: Tool):
chat_generator = ToolAssertingChatGenerator(expected_tools=[weather_tool])
agent = Agent(
chat_generator=chat_generator,
tools=[weather_tool, component_tool],
system_prompt="This is a system prompt.",
)
with patch("haystack.components.agents.agent._run_tool", wraps=_run_tool) as run_tool_mock:
agent.run([ChatMessage.from_user("What is the weather in Berlin?")], tools=[weather_tool.name])
run_tool_mock.assert_called_once()
assert run_tool_mock.call_args.kwargs["tools"] == [weather_tool]
@pytest.mark.asyncio
async def test_generation_kwargs(self):
chat_generator = MockChatGenerator("Hello")
agent = Agent(chat_generator=chat_generator)
chat_generator.run_async = AsyncMock(return_value={"replies": [ChatMessage.from_assistant("Hello")]})
await agent.run_async([ChatMessage.from_user("Hello")], generation_kwargs={"temperature": 0.0})
expected_messages = [
ChatMessage(_role=ChatRole.USER, _content=[TextContent(text="Hello")], _name=None, _meta={})
]
# No tools were configured, so the Agent does not pass a `tools` argument to the chat generator.
chat_generator.run_async.assert_called_once_with(
messages=expected_messages, generation_kwargs={"temperature": 0.0}
)
@pytest.mark.asyncio
async def test_run_async_uses_chat_generator_run_async_when_available(self, weather_tool):
chat_generator = MockChatGenerator("Hello")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
chat_generator.run_async = AsyncMock(
return_value={"replies": [ChatMessage.from_assistant("Hello from run_async")]}
)
result = await agent.run_async([ChatMessage.from_user("Hello")])
expected_messages = [
ChatMessage(_role=ChatRole.USER, _content=[TextContent(text="Hello")], _name=None, _meta={})
]
chat_generator.run_async.assert_called_once_with(messages=expected_messages, tools=[weather_tool])
assert isinstance(result, dict)
assert "messages" in result
assert isinstance(result["messages"], list)
assert len(result["messages"]) == 2
assert "Hello from run_async" in result["messages"][1].text
assert "last_message" in result
assert isinstance(result["last_message"], ChatMessage)
assert result["messages"][-1] == result["last_message"]
@pytest.mark.asyncio
async def test_run_async_falls_back_to_sync_run_for_sync_only_chat_generator(self, weather_tool):
"""`agent.run_async` must accept a chat generator that only implements `run` (no `run_async`).
The Agent should dispatch the sync call to the default executor rather than raising AttributeError."""
chat_generator = MockChatGeneratorWithoutRunAsync()
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
assert not getattr(chat_generator, "__haystack_supports_async__", False)
run_mock = MagicMock(wraps=chat_generator.run)
chat_generator.run = run_mock
result = await agent.run_async([ChatMessage.from_user("Hello")])
run_mock.assert_called_once()
# MockChatGeneratorWithoutRunAsync.run returns ChatMessage.from_assistant("Hello")
assert result["messages"][1].text == "Hello"
assert result["last_message"] == result["messages"][-1]
def test_run_populates_token_usage_and_tool_call_counts(self, weather_tool):
"""A multi-step run aggregates step_count, token_usage, and tool_call_counts."""
first_step = [
_assistant_with_usage(
tool_calls=[ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})],
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
)
]
second_step = [
_assistant_with_usage("Done.", usage={"prompt_tokens": 6, "completion_tokens": 3, "total_tokens": 9})
]
agent = Agent(chat_generator=MockChatGenerator(first_step + second_step), tools=[weather_tool])
result = agent.run([ChatMessage.from_user("Hi")])
assert result["step_count"] == 2
assert result["tool_call_counts"] == {"weather_tool": 1}
assert result["token_usage"] == {"prompt_tokens": 16, "completion_tokens": 8, "total_tokens": 24}
@pytest.mark.asyncio
async def test_run_async_populates_token_usage_and_tool_call_counts(self, weather_tool):
first_step = [
_assistant_with_usage(
tool_calls=[ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})],
usage={"prompt_tokens": 4, "completion_tokens": 2, "total_tokens": 6},
)
]
second_step = [
_assistant_with_usage("Done.", usage={"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4})
]
agent = Agent(chat_generator=MockChatGenerator(first_step + second_step), tools=[weather_tool])
result = await agent.run_async([ChatMessage.from_user("Hi")])
assert result["step_count"] == 2
assert result["tool_call_counts"] == {"weather_tool": 1}
assert result["token_usage"] == {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}
def test_metadata_outputs_show_defaults_when_no_data(self, weather_tool):
"""`token_usage` stays empty and `tool_call_counts` reports zero for every tool when nothing happens."""
# A text-only reply whose `usage` meta is empty leaves `token_usage` empty after aggregation.
chat_generator = MockChatGenerator(ChatMessage.from_assistant("Hello", meta={"usage": {}}))
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
result = agent.run([ChatMessage.from_user("Hi")])
assert result["step_count"] == 1
assert result["token_usage"] == {}
assert result["tool_call_counts"] == {"weather_tool": 0}
@pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set")
@pytest.mark.integration
def test_run(self, weather_tool):
chat_generator = OpenAIChatGenerator(model="gpt-4.1-nano")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], max_agent_steps=3)
response = agent.run([ChatMessage.from_user("What is the weather in Berlin?")])
assert isinstance(response, dict)
assert "messages" in response
assert isinstance(response["messages"], list)
assert len(response["messages"]) == 4
# Loose check of message texts
assert response["messages"][0].text == "What is the weather in Berlin?"
assert response["messages"][1].text is None
assert response["messages"][2].text is None
assert response["messages"][3].text is not None
# Loose check of message metadata
assert response["messages"][0].meta == {}
assert response["messages"][1].meta.get("model") is not None
assert response["messages"][2].meta == {}
assert response["messages"][3].meta.get("model") is not None
# Loose check of tool calls and results
assert response["messages"][1].tool_calls[0].tool_name == "weather_tool"
assert response["messages"][1].tool_calls[0].arguments is not None
assert response["messages"][2].tool_call_results[0].result is not None
assert response["messages"][2].tool_call_results[0].origin is not None
assert "last_message" in response
assert isinstance(response["last_message"], ChatMessage)
assert response["messages"][-1] == response["last_message"]
# Auto-populated run outputs:
# 4 messages → tool call + final answer = 2 LLM calls = 2 steps; one weather_tool invocation.
assert response["step_count"] == 2
assert response["tool_call_counts"] == {"weather_tool": 1}
assert response["token_usage"]["prompt_tokens"] > 0
assert response["token_usage"]["completion_tokens"] > 0
assert response["token_usage"]["total_tokens"] > 0
class TestAgentStreaming:
def test_run_with_params_streaming(self, openai_mock_chat_completion_chunk, weather_tool):
streaming_callback_called = False
def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
chat_generator = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"))
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], streaming_callback=streaming_callback)
response = agent.run([ChatMessage.from_user("Hello")])
assert streaming_callback_called is True
assert len(response["messages"]) == 2
assert "Hello" in response["messages"][1].text # see openai_mock_chat_completion_chunk
assert response["last_message"] == response["messages"][-1]
def test_run_with_run_streaming(self, openai_mock_chat_completion_chunk, weather_tool):
streaming_callback_called = False
def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
chat_generator = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"))
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
response = agent.run([ChatMessage.from_user("Hello")], streaming_callback=streaming_callback)
assert streaming_callback_called is True
assert len(response["messages"]) == 2
assert "Hello" in response["messages"][1].text # see openai_mock_chat_completion_chunk
assert response["last_message"] == response["messages"][-1]
def test_keep_generator_streaming(self, openai_mock_chat_completion_chunk, weather_tool):
streaming_callback_called = False
def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
chat_generator = OpenAIChatGenerator(
api_key=Secret.from_token("test-api-key"), streaming_callback=streaming_callback
)
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
response = agent.run([ChatMessage.from_user("Hello")])
assert streaming_callback_called is True
assert len(response["messages"]) == 2
assert "Hello" in response["messages"][1].text # see openai_mock_chat_completion_chunk
assert response["last_message"] == response["messages"][-1]
def test_run_with_async_streaming_callback_fails(self, weather_tool):
chat_generator = MockChatGenerator("Hello")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], streaming_callback=async_streaming_callback)
with pytest.raises(ValueError, match="The init callback cannot be a coroutine"):
agent.run([ChatMessage.from_user("Hello")])
@pytest.mark.asyncio
async def test_run_async_with_async_streaming_callback(self, weather_tool):
chat_generator = MockChatGenerator("Hello")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], streaming_callback=async_streaming_callback)
# This should not raise any exception
result = await agent.run_async([ChatMessage.from_user("Hello")])
assert "messages" in result
assert len(result["messages"]) == 2
assert result["messages"][1].text == "Hello"
@pytest.mark.asyncio
async def test_run_async_with_sync_streaming_callback_warns(self, weather_tool, caplog):
chat_generator = MockChatGenerator("Hello")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool], streaming_callback=sync_streaming_callback)
with caplog.at_level(logging.WARNING):
result = await agent.run_async([ChatMessage.from_user("Hello")])
assert "sync streaming callback" in caplog.text
assert "messages" in result
assert len(result["messages"]) == 2
@pytest.mark.integration
@pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set")
def test_agent_streaming_with_tool_call(self, weather_tool):
chat_generator = OpenAIChatGenerator(model="gpt-4.1-nano")
agent = Agent(chat_generator=chat_generator, tools=[weather_tool])
streaming_callback_called = False
def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
result = agent.run(
[ChatMessage.from_user("What's the weather in Paris?")],
streaming_callback=streaming_callback,
generation_kwargs={"stream_options": {"include_usage": True}},
)
assert result is not None
assert result["messages"] is not None
assert result["last_message"] is not None
assert streaming_callback_called
# Auto-populated run outputs.
assert result["step_count"] == 2
assert result["tool_call_counts"] == {"weather_tool": 1}
assert result["token_usage"]["prompt_tokens"] > 0
assert result["token_usage"]["completion_tokens"] > 0
assert result["token_usage"]["total_tokens"] > 0
class TestAgentContextTokens:
"""The Agent refreshes the internal `context_tokens` after each LLM call so a hook can read the current
context-window size (e.g. to trigger compaction). It is a per-call snapshot, not accumulated."""
def test_before_llm_hook_reads_refreshed_context_tokens(self, weather_tool):
# Step 1: a tool call (prompt 10 + completion 5 = 15). Step 2: the final text answer.
first_step = [
_assistant_with_usage(
tool_calls=[ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})],
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
)
]
second_step = [_assistant_with_usage("Done.", usage={"prompt_tokens": 20, "completion_tokens": 8})]
seen: list[int] = []
@hook
def capture(state: State) -> None:
seen.append(state.get("context_tokens"))
agent = Agent(
chat_generator=MockChatGenerator(first_step + second_step),
tools=[weather_tool],
hooks={"before_llm": [capture]},
)
agent.run([ChatMessage.from_user("Weather in Berlin?")])
# Before the first call there is no usage yet (0); before the second call it reflects the first call (15),
# confirming the recorder runs in the loop and the value is refreshed per call rather than accumulated.
assert seen == [0, 15]
@pytest.mark.asyncio
async def test_before_llm_hook_reads_refreshed_context_tokens_async(self, weather_tool):
first_step = [
_assistant_with_usage(
tool_calls=[ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})],
usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
)
]
second_step = [_assistant_with_usage("Done.", usage={"prompt_tokens": 20, "completion_tokens": 8})]
seen: list[int] = []
@hook
def capture(state: State) -> None:
seen.append(state.get("context_tokens"))
agent = Agent(
chat_generator=MockChatGenerator(first_step + second_step),
tools=[weather_tool],
hooks={"before_llm": [capture]},
)
await agent.run_async([ChatMessage.from_user("Weather in Berlin?")])
assert seen == [0, 15]
class TestAgentExitConditions:
def test_check_exit_conditions_parallel_tool_calls(self, weather_tool):
agent = Agent(chat_generator=MockChatGenerator("Hello"), tools=[weather_tool], exit_conditions=["weather_tool"])