-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathtest_tool_invoker.py
More file actions
1471 lines (1207 loc) · 61.6 KB
/
test_tool_invoker.py
File metadata and controls
1471 lines (1207 loc) · 61.6 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 datetime
import json
import time
from typing import Any
from unittest.mock import patch
import pytest
from haystack import Document, Pipeline
from haystack.components.agents.state import State
from haystack.components.builders.prompt_builder import PromptBuilder
from haystack.components.generators.chat.openai import OpenAIChatGenerator
from haystack.components.generators.utils import print_streaming_chunk
from haystack.components.tools.tool_invoker import (
ResultConversionError,
StringConversionError,
ToolInvoker,
ToolNotFoundException,
ToolOutputMergeError,
)
from haystack.dataclasses import (
ChatMessage,
ChatRole,
ImageContent,
StreamingChunk,
TextContent,
ToolCall,
ToolCallResult,
)
from haystack.tools import ComponentTool, Tool, Toolset
from haystack.tools.errors import ToolInvocationError
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"},
}
return weather_info.get(location, {"weather": "unknown", "temperature": 0, "unit": "celsius"})
weather_parameters = {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}
@pytest.fixture
def weather_tool():
return Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
)
@pytest.fixture
def weather_tool_with_outputs_to_state():
return Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
outputs_to_state={"weather": {"source": "weather"}},
)
@pytest.fixture
def faulty_tool():
def faulty_tool_func(location):
raise Exception("This tool always fails.")
faulty_tool_parameters = {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
}
return Tool(
name="faulty_tool",
description="A tool that always fails when invoked.",
parameters=faulty_tool_parameters,
function=faulty_tool_func,
)
def add_function(num1: int, num2: int):
return num1 + num2
@pytest.fixture
def tool_set():
return Toolset(
tools=[
Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
),
Tool(
name="addition_tool",
description="A tool that adds two numbers.",
parameters={
"type": "object",
"properties": {"num1": {"type": "integer"}, "num2": {"type": "integer"}},
"required": ["num1", "num2"],
},
function=add_function,
),
]
)
@pytest.fixture
def invoker(weather_tool):
return ToolInvoker(tools=[weather_tool], raise_on_failure=True, convert_result_to_json_string=False)
@pytest.fixture
def faulty_invoker(faulty_tool):
return ToolInvoker(tools=[faulty_tool], raise_on_failure=True, convert_result_to_json_string=False)
class WarmupTrackingTool(Tool):
"""A tool that tracks whether warm_up was called."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.was_warmed_up = False
def warm_up(self):
self.was_warmed_up = True
class WarmupTrackingToolset(Toolset):
"""A toolset that tracks whether warm_up was called."""
def __init__(self, tools):
super().__init__(tools)
self.was_warmed_up = False
def warm_up(self):
self.was_warmed_up = True
# Call parent to warm up individual tools
super().warm_up()
class TestToolInvokerCore:
def test_init(self, weather_tool):
invoker = ToolInvoker(tools=[weather_tool])
assert invoker.tools == [weather_tool]
assert invoker._tools_with_names == {"weather_tool": weather_tool}
assert invoker.raise_on_failure
assert not invoker.convert_result_to_json_string
def test_validate_and_prepare_tools(self, weather_tool, faulty_tool):
result = ToolInvoker._validate_and_prepare_tools([weather_tool, faulty_tool])
assert result == {"weather_tool": weather_tool, "faulty_tool": faulty_tool}
toolset = Toolset([weather_tool, faulty_tool])
result = ToolInvoker._validate_and_prepare_tools(toolset)
assert result == {"weather_tool": weather_tool, "faulty_tool": faulty_tool}
def test_validate_and_prepare_tools_validation_failures(self, weather_tool):
with pytest.raises(ValueError):
ToolInvoker._validate_and_prepare_tools([])
with pytest.raises(ValueError):
ToolInvoker._validate_and_prepare_tools([weather_tool, weather_tool])
def test_inject_state_args_no_tool_inputs(self, invoker):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
)
state = State(schema={"location": {"type": str}}, data={"location": "Berlin"})
args = invoker._inject_state_args(tool=weather_tool, llm_args={}, state=state)
assert args == {"location": "Berlin"}
def test_inject_state_args_no_tool_inputs_component_tool(self, invoker):
comp = PromptBuilder(template="Hello, {{name}}!")
prompt_tool = ComponentTool(
component=comp, name="prompt_tool", description="Creates a personalized greeting prompt."
)
state = State(schema={"name": {"type": str}}, data={"name": "James"})
args = invoker._inject_state_args(tool=prompt_tool, llm_args={}, state=state)
assert args == {"name": "James"}
def test_inject_state_args_with_tool_inputs(self, invoker):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
inputs_from_state={"loc": "location"},
)
state = State(schema={"location": {"type": str}}, data={"loc": "Berlin"})
args = invoker._inject_state_args(tool=weather_tool, llm_args={}, state=state)
assert args == {"location": "Berlin"}
def test_inject_state_args_param_in_state_and_llm(self, invoker):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
)
state = State(schema={"location": {"type": str}}, data={"location": "Berlin"})
args = invoker._inject_state_args(tool=weather_tool, llm_args={"location": "Paris"}, state=state)
assert args == {"location": "Paris"}
def test_inject_state_args_injects_state_object_for_state_annotated_param(self, invoker):
def function_with_state(city: str, state: State) -> str:
return f"Weather in {city}"
state_tool = Tool(
name="state_tool",
description="A tool that receives the live State object.",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
function=function_with_state,
)
state = State(schema={"city": {"type": str}}, data={"city": "Berlin"})
args = invoker._inject_state_args(tool=state_tool, llm_args={"city": "Paris"}, state=state)
assert args["city"] == "Paris"
assert args["state"] is state
def test_inject_state_args_injects_state_object_for_optional_state_annotated_param(self, invoker):
def function_with_optional_state(city: str, state: State | None = None) -> str:
return f"Weather in {city}"
state_tool = Tool(
name="state_tool",
description="A tool that receives an optional State object.",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
function=function_with_optional_state,
)
state = State(schema={})
args = invoker._inject_state_args(tool=state_tool, llm_args={"city": "Paris"}, state=state)
assert args["city"] == "Paris"
assert args["state"] is state
class TestToolInvokerSerde:
def test_to_dict(self, invoker, weather_tool):
data = invoker.to_dict()
assert data == {
"type": "haystack.components.tools.tool_invoker.ToolInvoker",
"init_parameters": {
"tools": [weather_tool.to_dict()],
"raise_on_failure": True,
"convert_result_to_json_string": False,
"enable_streaming_callback_passthrough": False,
"streaming_callback": None,
"max_workers": 4,
},
}
def test_to_dict_with_params(self, weather_tool):
invoker = ToolInvoker(
tools=[weather_tool],
raise_on_failure=False,
convert_result_to_json_string=True,
enable_streaming_callback_passthrough=True,
streaming_callback=print_streaming_chunk,
)
assert invoker.to_dict() == {
"type": "haystack.components.tools.tool_invoker.ToolInvoker",
"init_parameters": {
"tools": [weather_tool.to_dict()],
"raise_on_failure": False,
"convert_result_to_json_string": True,
"enable_streaming_callback_passthrough": True,
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
"max_workers": 4,
},
}
def test_from_dict(self, weather_tool):
data = {
"type": "haystack.components.tools.tool_invoker.ToolInvoker",
"init_parameters": {
"tools": [weather_tool.to_dict()],
"raise_on_failure": True,
"convert_result_to_json_string": False,
"enable_streaming_callback_passthrough": False,
"streaming_callback": None,
},
}
invoker = ToolInvoker.from_dict(data)
assert invoker.tools == [weather_tool]
assert invoker._tools_with_names == {"weather_tool": weather_tool}
assert invoker.raise_on_failure
assert not invoker.convert_result_to_json_string
assert invoker.streaming_callback is None
assert invoker.enable_streaming_callback_passthrough is False
def test_from_dict_with_streaming_callback(self, weather_tool):
data = {
"type": "haystack.components.tools.tool_invoker.ToolInvoker",
"init_parameters": {
"tools": [weather_tool.to_dict()],
"raise_on_failure": True,
"convert_result_to_json_string": False,
"enable_streaming_callback_passthrough": True,
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
},
}
invoker = ToolInvoker.from_dict(data)
assert invoker.tools == [weather_tool]
assert invoker._tools_with_names == {"weather_tool": weather_tool}
assert invoker.raise_on_failure
assert not invoker.convert_result_to_json_string
assert invoker.streaming_callback == print_streaming_chunk
assert invoker.enable_streaming_callback_passthrough is True
def test_serde_in_pipeline(self, invoker, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
pipeline = Pipeline()
pipeline.add_component("invoker", invoker)
pipeline.add_component("chatgenerator", OpenAIChatGenerator())
pipeline.connect("invoker", "chatgenerator")
pipeline_dict = pipeline.to_dict()
# Verify the chatgenerator component structure (model will be whatever the default is)
chatgen = pipeline_dict["components"]["chatgenerator"]
assert chatgen["type"] == "haystack.components.generators.chat.openai.OpenAIChatGenerator"
assert "model" in chatgen["init_parameters"]
model_name = chatgen["init_parameters"]["model"]
# Build expected dict with dynamic model value
expected = {
"metadata": {},
"connection_type_validation": True,
"max_runs_per_component": 100,
"components": {
"invoker": {
"type": "haystack.components.tools.tool_invoker.ToolInvoker",
"init_parameters": {
"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": "tools.test_tool_invoker.weather_function",
"outputs_to_string": None,
"inputs_from_state": None,
"outputs_to_state": None,
},
}
],
"raise_on_failure": True,
"convert_result_to_json_string": False,
"enable_streaming_callback_passthrough": False,
"streaming_callback": None,
"max_workers": 4,
},
},
"chatgenerator": {
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
"init_parameters": {
"model": model_name,
"streaming_callback": None,
"api_base_url": None,
"organization": None,
"generation_kwargs": {},
"max_retries": None,
"timeout": None,
"api_key": {"type": "env_var", "env_vars": ["OPENAI_API_KEY"], "strict": True},
"tools": None,
"tools_strict": False,
"http_client_kwargs": None,
},
},
},
"connections": [{"sender": "invoker.tool_messages", "receiver": "chatgenerator.messages"}],
}
assert pipeline_dict == expected
pipeline_yaml = pipeline.dumps()
new_pipeline = Pipeline.loads(pipeline_yaml)
assert new_pipeline == pipeline
class TestToolInvokerRun:
def test_run_with_streaming_callback_finish_reason(self, invoker):
streaming_chunks = []
def streaming_callback(chunk: StreamingChunk) -> None:
streaming_chunks.append(chunk)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = invoker.run(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result
assert len(result["tool_messages"]) == 1
# Check that we received streaming chunks
assert len(streaming_chunks) >= 2 # At least one for tool result and one for finish reason
# The last chunk should have finish_reason set to "tool_call_results"
final_chunk = streaming_chunks[-1]
assert final_chunk.finish_reason == "tool_call_results"
assert final_chunk.meta["finish_reason"] == "tool_call_results"
assert final_chunk.content == ""
@pytest.mark.asyncio
async def test_run_async_with_streaming_callback_finish_reason(self, weather_tool):
streaming_chunks = []
async def streaming_callback(chunk: StreamingChunk) -> None:
streaming_chunks.append(chunk)
tool_invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=True, convert_result_to_json_string=False)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = await tool_invoker.run_async(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result
assert len(result["tool_messages"]) == 1
# Check that we received streaming chunks
assert len(streaming_chunks) >= 2 # At least one for tool result and one for finish reason
# The last chunk should have finish_reason set to "tool_call_results"
final_chunk = streaming_chunks[-1]
assert final_chunk.finish_reason == "tool_call_results"
assert final_chunk.meta["finish_reason"] == "tool_call_results"
assert final_chunk.content == ""
def test_enable_streaming_callback_passthrough(self, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
llm_tool = ComponentTool(
component=OpenAIChatGenerator(),
name="chat_generator_tool",
description="A tool that generates chat messages using OpenAI's GPT model.",
)
invoker = ToolInvoker(
tools=[llm_tool], enable_streaming_callback_passthrough=True, streaming_callback=print_streaming_chunk
)
with patch("haystack.components.generators.chat.OpenAIChatGenerator.run") as mock_run:
mock_run.return_value = {"replies": [ChatMessage.from_assistant("Hello! How can I help you?")]}
invoker.run(
messages=[
ChatMessage.from_assistant(
tool_calls=[
ToolCall(
tool_name="chat_generator_tool",
arguments={"messages": [{"role": "user", "content": [{"text": "Hello!"}]}]},
id="12345",
)
]
)
]
)
mock_run.assert_called_once_with(
messages=[ChatMessage.from_user(text="Hello!")], streaming_callback=print_streaming_chunk
)
def test_enable_streaming_callback_passthrough_runtime(self, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
llm_tool = ComponentTool(
component=OpenAIChatGenerator(),
name="chat_generator_tool",
description="A tool that generates chat messages using OpenAI's GPT model.",
)
invoker = ToolInvoker(
tools=[llm_tool], enable_streaming_callback_passthrough=True, streaming_callback=print_streaming_chunk
)
with patch("haystack.components.generators.chat.OpenAIChatGenerator.run") as mock_run:
mock_run.return_value = {"replies": [ChatMessage.from_assistant("Hello! How can I help you?")]}
invoker.run(
messages=[
ChatMessage.from_assistant(
tool_calls=[
ToolCall(
tool_name="chat_generator_tool",
arguments={"messages": [{"role": "user", "content": [{"text": "Hello!"}]}]},
id="12345",
)
]
)
],
enable_streaming_callback_passthrough=False,
)
mock_run.assert_called_once_with(messages=[ChatMessage.from_user(text="Hello!")])
def test_run_no_messages(self, invoker):
result = invoker.run(messages=[])
assert result["tool_messages"] == []
def test_run_no_tool_calls(self, invoker):
user_message = ChatMessage.from_user(text="Hello!")
assistant_message = ChatMessage.from_assistant(text="How can I help you?")
result = invoker.run(messages=[user_message, assistant_message])
assert result["tool_messages"] == []
def test_run_multiple_tool_calls(self, invoker):
tool_calls = [
ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Paris"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Rome"}),
]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
result = invoker.run(messages=[message])
assert "tool_messages" in result
assert len(result["tool_messages"]) == 3
for i, tool_message in enumerate(result["tool_messages"]):
assert isinstance(tool_message, ChatMessage)
assert tool_message.is_from(ChatRole.TOOL)
assert tool_message.tool_call_results
tool_call_result = tool_message.tool_call_result
assert isinstance(tool_call_result, ToolCallResult)
assert not tool_call_result.error
assert tool_call_result.origin == tool_calls[i]
def test_run_tool_calls_with_empty_args(self):
hello_world_tool = Tool(
name="hello_world",
description="A tool that returns a greeting.",
parameters={"type": "object", "properties": {}},
function=lambda: "Hello, world!",
)
invoker = ToolInvoker(tools=[hello_world_tool])
tool_call = ToolCall(tool_name="hello_world", arguments={})
tool_call_message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = invoker.run(messages=[tool_call_message])
assert "tool_messages" in result
assert len(result["tool_messages"]) == 1
tool_message = result["tool_messages"][0]
assert isinstance(tool_message, ChatMessage)
assert tool_message.is_from(ChatRole.TOOL)
assert tool_message.tool_call_results
tool_call_result = tool_message.tool_call_result
assert isinstance(tool_call_result, ToolCallResult)
assert not tool_call_result.error
assert tool_call_result.result == "Hello, world!"
def test_run_with_tools_override(self, weather_tool, faulty_tool):
"""Tests that tools passed to run override the tools passed in init"""
invoker = ToolInvoker(tools=[faulty_tool])
assert invoker._tools_with_names == {"faulty_tool": faulty_tool}
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = invoker.run(messages=[message], tools=[weather_tool])
tool_message = result["tool_messages"][0]
tool_call_result = tool_message.tool_call_result
assert not tool_call_result.error
assert tool_call_result.result == str({"weather": "mostly sunny", "temperature": 7, "unit": "celsius"})
assert tool_call_result.origin == tool_call
@pytest.mark.asyncio
async def test_run_async_with_tools_override(self, weather_tool, faulty_tool):
"""Tests that tools passed to run_async override the tools passed in init"""
invoker = ToolInvoker(tools=[faulty_tool])
assert invoker._tools_with_names == {"faulty_tool": faulty_tool}
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = await invoker.run_async(messages=[message], tools=[weather_tool])
tool_message = result["tool_messages"][0]
tool_call_result = tool_message.tool_call_result
assert not tool_call_result.error
assert tool_call_result.result == str({"weather": "mostly sunny", "temperature": 7, "unit": "celsius"})
assert tool_call_result.origin == tool_call
def test_parallel_tool_calling_with_state_updates(self):
"""Test that parallel tool execution with state updates works correctly with the state lock."""
# Create a shared counter variable to simulate a state value that gets updated
execution_log = []
def function_1():
time.sleep(0.01)
execution_log.append("tool_1_executed")
return {"counter": 1, "tool_name": "tool_1"}
def function_2():
time.sleep(0.01)
execution_log.append("tool_2_executed")
return {"counter": 2, "tool_name": "tool_2"}
def function_3():
time.sleep(0.01)
execution_log.append("tool_3_executed")
return {"counter": 3, "tool_name": "tool_3"}
# Create tools that all update the same state key
tool_1 = Tool(
name="state_tool_1",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_1,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
tool_2 = Tool(
name="state_tool_2",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_2,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
tool_3 = Tool(
name="state_tool_3",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_3,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
# Create ToolInvoker with all three tools
invoker = ToolInvoker(tools=[tool_1, tool_2, tool_3], raise_on_failure=True)
state = State(schema={"counter": {"type": int}, "last_tool": {"type": str}})
tool_calls = [
ToolCall(tool_name="state_tool_1", arguments={}),
ToolCall(tool_name="state_tool_2", arguments={}),
ToolCall(tool_name="state_tool_3", arguments={}),
]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
_ = invoker.run(messages=[message], state=state)
# Verify that all three tools were executed
assert len(execution_log) == 3
assert "tool_1_executed" in execution_log
assert "tool_2_executed" in execution_log
assert "tool_3_executed" in execution_log
# Verify that the state was updated correctly
# Due to parallel execution, we can't predict which tool will be the last to update
assert state.has("counter")
assert state.has("last_tool")
assert state.get("counter") in [1, 2, 3] # Should be one of the tool values
assert state.get("last_tool") in ["tool_1", "tool_2", "tool_3"] # Should be one of the tool names
@pytest.mark.asyncio
async def test_async_parallel_tool_calling_with_state_updates(self):
"""Test that parallel tool execution with state updates works correctly with the state lock."""
# Create a shared counter variable to simulate a state value that gets updated
execution_log = []
def function_1():
time.sleep(0.01)
execution_log.append("tool_1_executed")
return {"counter": 1, "tool_name": "tool_1"}
def function_2():
time.sleep(0.01)
execution_log.append("tool_2_executed")
return {"counter": 2, "tool_name": "tool_2"}
def function_3():
time.sleep(0.01)
execution_log.append("tool_3_executed")
return {"counter": 3, "tool_name": "tool_3"}
# Create tools that all update the same state key
tool_1 = Tool(
name="state_tool_1",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_1,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
tool_2 = Tool(
name="state_tool_2",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_2,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
tool_3 = Tool(
name="state_tool_3",
description="A tool that updates state counter",
parameters={"type": "object", "properties": {}},
function=function_3,
outputs_to_state={"counter": {"source": "counter"}, "last_tool": {"source": "tool_name"}},
)
# Create ToolInvoker with all three tools
invoker = ToolInvoker(tools=[tool_1, tool_2, tool_3], raise_on_failure=True)
state = State(schema={"counter": {"type": int}, "last_tool": {"type": str}})
tool_calls = [
ToolCall(tool_name="state_tool_1", arguments={}),
ToolCall(tool_name="state_tool_2", arguments={}),
ToolCall(tool_name="state_tool_3", arguments={}),
]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
_ = await invoker.run_async(messages=[message], state=state)
# Verify that all three tools were executed
assert len(execution_log) == 3
assert "tool_1_executed" in execution_log
assert "tool_2_executed" in execution_log
assert "tool_3_executed" in execution_log
# Verify that the state was updated correctly
# Due to parallel execution, we can't predict which tool will be the last to update
assert state.has("counter")
assert state.has("last_tool")
assert state.get("counter") in [1, 2, 3] # Should be one of the tool values
assert state.get("last_tool") in ["tool_1", "tool_2", "tool_3"] # Should be one of the tool names
def test_call_invoker_two_subsequent_run_calls(self, invoker: ToolInvoker):
tool_calls = [
ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Paris"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Rome"}),
]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
streaming_callback_called = False
def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
# First call
result_1 = invoker.run(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result_1
assert len(result_1["tool_messages"]) == 3
# Second call
result_2 = invoker.run(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result_2
assert len(result_2["tool_messages"]) == 3
@pytest.mark.asyncio
async def test_call_invoker_two_subsequent_run_async_calls(self, invoker: ToolInvoker):
tool_calls = [
ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Paris"}),
ToolCall(tool_name="weather_tool", arguments={"location": "Rome"}),
]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
streaming_callback_called = False
async def streaming_callback(chunk: StreamingChunk) -> None:
nonlocal streaming_callback_called
streaming_callback_called = True
# First call
result_1 = await invoker.run_async(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result_1
assert len(result_1["tool_messages"]) == 3
# Second call
result_2 = await invoker.run_async(messages=[message], streaming_callback=streaming_callback)
assert "tool_messages" in result_2
assert len(result_2["tool_messages"]) == 3
def test_run_injects_state_object_into_tool(self):
received_state = {}
def function_with_state(city: str, state: State) -> str:
received_state["state"] = state
return f"Weather in {city}: sunny"
state_tool = Tool(
name="state_tool",
description="A tool that receives the live State object.",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
function=function_with_state,
)
invoker = ToolInvoker(tools=[state_tool])
state = State(schema={"city": {"type": str}})
tool_call = ToolCall(tool_name="state_tool", arguments={"city": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = invoker.run(messages=[message], state=state)
assert len(result["tool_messages"]) == 1
assert not result["tool_messages"][0].tool_call_results[0].error
assert received_state["state"] is state
@pytest.mark.asyncio
async def test_run_async_injects_state_object_into_tool(self):
received_state = {}
def function_with_state(city: str, state: State) -> str:
received_state["state"] = state
return f"Weather in {city}: sunny"
state_tool = Tool(
name="state_tool",
description="A tool that receives the live State object.",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
function=function_with_state,
)
invoker = ToolInvoker(tools=[state_tool])
state = State(schema={"city": {"type": str}})
tool_call = ToolCall(tool_name="state_tool", arguments={"city": "Berlin"})
message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = await invoker.run_async(messages=[message], state=state)
assert len(result["tool_messages"]) == 1
assert not result["tool_messages"][0].tool_call_results[0].error
assert received_state["state"] is state
class TestToolInvokerErrorHandling:
def test_tool_not_found_error(self, invoker):
tool_call = ToolCall(tool_name="non_existent_tool", arguments={"location": "Berlin"})
tool_call_message = ChatMessage.from_assistant(tool_calls=[tool_call])
with pytest.raises(ToolNotFoundException):
invoker.run(messages=[tool_call_message])
def test_tool_not_found_does_not_raise_exception(self, weather_tool):
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=False, convert_result_to_json_string=False)
tool_call = ToolCall(tool_name="non_existent_tool", arguments={"location": "Berlin"})
tool_call_message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = invoker.run(messages=[tool_call_message])
tool_message = result["tool_messages"][0]
assert tool_message.tool_call_results[0].error
assert "not found" in tool_message.tool_call_results[0].result
def test_tool_invocation_error(self, faulty_invoker):
tool_call = ToolCall(tool_name="faulty_tool", arguments={"location": "Berlin"})
tool_call_message = ChatMessage.from_assistant(tool_calls=[tool_call])
with pytest.raises(ToolInvocationError):
faulty_invoker.run(messages=[tool_call_message])
def test_tool_invocation_error_does_not_raise_exception(self, faulty_tool):
faulty_invoker = ToolInvoker(tools=[faulty_tool], raise_on_failure=False, convert_result_to_json_string=False)
tool_call = ToolCall(tool_name="faulty_tool", arguments={"location": "Berlin"})
tool_call_message = ChatMessage.from_assistant(tool_calls=[tool_call])
result = faulty_invoker.run(messages=[tool_call_message])
tool_message = result["tool_messages"][0]
assert tool_message.tool_call_results[0].error
assert "Failed to invoke" in tool_message.tool_call_results[0].result
def test_outputs_to_string_with_multiple_outputs(self):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
# Pass config that selects two of three outputs
outputs_to_string={"weather": {"source": "weather"}, "temp": {"source": "temperature"}},
)
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=True)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
tool_result = {"weather": "sunny", "temperature": 25, "unit": "celsius"}
chat_message = invoker._prepare_tool_result_message(
result=tool_result, tool_call=tool_call, tool_to_invoke=weather_tool
)
assert chat_message.tool_call_results[0].result == "{'weather': 'sunny', 'temp': '25'}"
def test_string_conversion_error(self):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
# Pass custom handler that will throw an error when trying to convert tool_result
outputs_to_string={"handler": json.dumps},
)
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=True)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
tool_result = datetime.datetime.now()
with pytest.raises(StringConversionError):
invoker._prepare_tool_result_message(result=tool_result, tool_call=tool_call, tool_to_invoke=weather_tool)
def test_string_conversion_error_does_not_raise_exception(self):
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
# Pass custom handler that will throw an error when trying to convert tool_result
outputs_to_string={"handler": json.dumps},
)
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=False)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
tool_result = datetime.datetime.now()
tool_message = invoker._prepare_tool_result_message(
result=tool_result, tool_call=tool_call, tool_to_invoke=weather_tool
)
assert tool_message.tool_call_results[0].error
assert "Failed to convert" in tool_message.tool_call_results[0].result
def test_result_conversion_error(self):
def handler(result):
raise ValueError("Handler error")
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
outputs_to_string={"handler": handler, "raw_result": True},
)
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=True)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
tool_result = "something"
with pytest.raises(ResultConversionError):
invoker._prepare_tool_result_message(result=tool_result, tool_call=tool_call, tool_to_invoke=weather_tool)
def test_result_conversion_error_does_not_raise_exception(self):
def handler(result):
raise ValueError("Handler error")
weather_tool = Tool(
name="weather_tool",
description="Provides weather information for a given location.",
parameters=weather_parameters,
function=weather_function,
outputs_to_string={"handler": handler, "raw_result": True},
)
invoker = ToolInvoker(tools=[weather_tool], raise_on_failure=False)
tool_call = ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})
tool_result = "something"
tool_message = invoker._prepare_tool_result_message(
result=tool_result, tool_call=tool_call, tool_to_invoke=weather_tool
)
assert tool_message.tool_call_results[0].error
assert "Failed to convert" in tool_message.tool_call_results[0].result
def test_run_state_merge_error_handled_gracefully(self, weather_tool_with_outputs_to_state):
class ProblematicState(State):
def set(self, key: str, value: Any, handler_override=None):
# Simulate a State error during merging
raise ValueError("State set operation failed")
state = ProblematicState(schema={"test_key": {"type": str}})
invoker = ToolInvoker(tools=[weather_tool_with_outputs_to_state], raise_on_failure=False)
tool_calls = [ToolCall(tool_name="weather_tool", arguments={"location": "Berlin"})]
message = ChatMessage.from_assistant(tool_calls=tool_calls)
result = invoker.run(messages=[message], state=state)
assert "tool_messages" in result
assert len(result["tool_messages"]) == 1
assert result["tool_messages"][0].tool_call_results[0].error is True
assert (
"Failed to merge tool outputs from tool weather_tool into State"
in result["tool_messages"][0].tool_call_results[0].result
)
def test_run_state_merge_error_raises_when_configured(self, weather_tool_with_outputs_to_state):
class ProblematicState(State):
def set(self, key: str, value: Any, handler_override=None):
# Simulate a State error during merging
raise ValueError("State set operation failed")