-
Notifications
You must be signed in to change notification settings - Fork 21.5k
Expand file tree
/
Copy pathtest_tools.py
More file actions
3735 lines (2981 loc) · 110 KB
/
test_tools.py
File metadata and controls
3735 lines (2981 loc) · 110 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
"""Test the base tool implementation."""
import inspect
import json
import logging
import sys
import textwrap
import threading
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from functools import partial
from typing import (
Annotated,
Any,
ClassVar,
Generic,
Literal,
Protocol,
TypeVar,
cast,
get_type_hints,
)
import pytest
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from pydantic.v1 import BaseModel as BaseModelV1
from pydantic.v1 import ValidationError as ValidationErrorV1
from typing_extensions import TypedDict, override
from langchain_core import tools
from langchain_core.callbacks import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain_core.callbacks.manager import (
CallbackManagerForRetrieverRun,
)
from langchain_core.documents import Document
from langchain_core.messages import ToolCall, ToolMessage
from langchain_core.messages.tool import ToolOutputMixin
from langchain_core.retrievers import BaseRetriever
from langchain_core.runnables import (
RunnableConfig,
RunnableLambda,
ensure_config,
)
from langchain_core.tools import (
BaseTool,
StructuredTool,
Tool,
ToolException,
tool,
)
from langchain_core.tools.base import (
TOOL_MESSAGE_BLOCK_TYPES,
ArgsSchema,
InjectedToolArg,
InjectedToolCallId,
SchemaAnnotationError,
_DirectlyInjectedToolArg,
_is_message_content_block,
_is_message_content_type,
get_all_basemodel_annotations,
)
from langchain_core.utils.function_calling import (
convert_to_openai_function,
convert_to_openai_tool,
)
from langchain_core.utils.pydantic import (
_create_subset_model,
create_model_v2,
)
from tests.unit_tests.fake.callbacks import FakeCallbackHandler
from tests.unit_tests.pydantic_utils import _normalize_schema, _schema
try:
from langgraph.prebuilt import ToolRuntime # type: ignore[import-not-found]
HAS_LANGGRAPH = True
except ImportError:
HAS_LANGGRAPH = False
def _get_tool_call_json_schema(tool: BaseTool) -> dict[str, Any]:
tool_schema = tool.tool_call_schema
if isinstance(tool_schema, dict):
return tool_schema
if issubclass(tool_schema, BaseModel):
return tool_schema.model_json_schema()
if issubclass(tool_schema, BaseModelV1):
return tool_schema.schema()
return {}
def test_unnamed_decorator() -> None:
"""Test functionality with unnamed decorator."""
@tool
def search_api(query: str) -> str:
"""Search the API for the query."""
return "API result"
assert isinstance(search_api, BaseTool)
assert search_api.name == "search_api"
assert not search_api.return_direct
assert search_api.invoke("test") == "API result"
class _MockSchema(BaseModel):
"""Return the arguments directly."""
arg1: int
arg2: bool
arg3: dict | None = None
class _MockStructuredTool(BaseTool):
name: str = "structured_api"
args_schema: type[BaseModel] = _MockSchema
description: str = "A Structured Tool"
@override
def _run(self, *, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
async def _arun(self, *, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
raise NotImplementedError
def test_structured_args() -> None:
"""Test functionality with structured arguments."""
structured_api = _MockStructuredTool()
assert isinstance(structured_api, BaseTool)
assert structured_api.name == "structured_api"
expected_result = "1 True {'foo': 'bar'}"
args = {"arg1": 1, "arg2": True, "arg3": {"foo": "bar"}}
assert structured_api.run(args) == expected_result
def test_misannotated_base_tool_raises_error() -> None:
"""Test that a BaseTool with the incorrect typehint raises an exception."""
with pytest.raises(SchemaAnnotationError):
class _MisAnnotatedTool(BaseTool):
name: str = "structured_api"
# This would silently be ignored without the custom metaclass
args_schema: BaseModel = _MockSchema # type: ignore[assignment]
description: str = "A Structured Tool"
@override
def _run(self, *, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
async def _arun(
self, *, arg1: int, arg2: bool, arg3: dict | None = None
) -> str:
raise NotImplementedError
def test_forward_ref_annotated_base_tool_accepted() -> None:
"""Test that a using forward ref annotation syntax is accepted."""
class _ForwardRefAnnotatedTool(BaseTool):
name: str = "structured_api"
args_schema: "type[BaseModel]" = _MockSchema
description: str = "A Structured Tool"
@override
def _run(self, *, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
async def _arun(
self, *, arg1: int, arg2: bool, arg3: dict | None = None
) -> str:
raise NotImplementedError
def test_subclass_annotated_base_tool_accepted() -> None:
"""Test BaseTool child w/ custom schema isn't overwritten."""
class _ForwardRefAnnotatedTool(BaseTool):
name: str = "structured_api"
args_schema: type[_MockSchema] = _MockSchema
description: str = "A Structured Tool"
@override
def _run(self, *, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
async def _arun(
self, *, arg1: int, arg2: bool, arg3: dict | None = None
) -> str:
raise NotImplementedError
assert issubclass(_ForwardRefAnnotatedTool, BaseTool)
tool = _ForwardRefAnnotatedTool()
assert tool.args_schema == _MockSchema
def test_decorator_with_specified_schema() -> None:
"""Test that manually specified schemata are passed through to the tool."""
@tool(args_schema=_MockSchema)
def tool_func(*, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
assert isinstance(tool_func, BaseTool)
assert tool_func.args_schema == _MockSchema
@pytest.mark.skipif(
sys.version_info >= (3, 14),
reason="pydantic.v1 namespace not supported with Python 3.14+",
)
def test_decorator_with_specified_schema_pydantic_v1() -> None:
"""Test that manually specified schemata are passed through to the tool."""
class _MockSchemaV1(BaseModelV1):
"""Return the arguments directly."""
arg1: int
arg2: bool
arg3: dict | None = None
@tool(args_schema=cast("ArgsSchema", _MockSchemaV1))
def tool_func_v1(*, arg1: int, arg2: bool, arg3: dict | None = None) -> str:
return f"{arg1} {arg2} {arg3}"
assert isinstance(tool_func_v1, BaseTool)
assert tool_func_v1.args_schema == cast("ArgsSchema", _MockSchemaV1)
def test_decorated_function_schema_equivalent() -> None:
"""Test that a BaseTool without a schema meets expectations."""
@tool
def structured_tool_input(
*, arg1: int, arg2: bool, arg3: dict | None = None
) -> str:
"""Return the arguments directly."""
return f"{arg1} {arg2} {arg3}"
assert isinstance(structured_tool_input, BaseTool)
assert structured_tool_input.args_schema is not None
assert (
_schema(structured_tool_input.args_schema)["properties"]
== _schema(_MockSchema)["properties"]
== _normalize_schema(structured_tool_input.args)
)
def test_args_kwargs_filtered() -> None:
class _SingleArgToolWithKwargs(BaseTool):
name: str = "single_arg_tool"
description: str = "A single arged tool with kwargs"
@override
def _run(
self,
some_arg: str,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> str:
return "foo"
async def _arun(
self,
some_arg: str,
run_manager: AsyncCallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> str:
raise NotImplementedError
tool = _SingleArgToolWithKwargs()
assert tool.is_single_input
class _VarArgToolWithKwargs(BaseTool):
name: str = "single_arg_tool"
description: str = "A single arged tool with kwargs"
@override
def _run(
self,
*args: Any,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> str:
return "foo"
async def _arun(
self,
*args: Any,
run_manager: AsyncCallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> str:
raise NotImplementedError
tool2 = _VarArgToolWithKwargs()
assert tool2.is_single_input
def test_structured_args_decorator_no_infer_schema() -> None:
"""Test functionality with structured arguments parsed as a decorator."""
@tool(infer_schema=False)
def structured_tool_input(
arg1: int, arg2: float | datetime, opt_arg: dict | None = None
) -> str:
"""Return the arguments directly."""
return f"{arg1}, {arg2}, {opt_arg}"
assert isinstance(structured_tool_input, BaseTool)
assert structured_tool_input.name == "structured_tool_input"
args = {"arg1": 1, "arg2": 0.001, "opt_arg": {"foo": "bar"}}
with pytest.raises(ToolException):
assert structured_tool_input.run(args)
def test_structured_single_str_decorator_no_infer_schema() -> None:
"""Test functionality with structured arguments parsed as a decorator."""
@tool(infer_schema=False)
def unstructured_tool_input(tool_input: str) -> str:
"""Return the arguments directly."""
assert isinstance(tool_input, str)
return f"{tool_input}"
assert isinstance(unstructured_tool_input, BaseTool)
assert unstructured_tool_input.args_schema is None
assert unstructured_tool_input.run("foo") == "foo"
def test_structured_tool_types_parsed() -> None:
"""Test the non-primitive types are correctly passed to structured tools."""
class SomeEnum(Enum):
A = "a"
B = "b"
class SomeBaseModel(BaseModel):
foo: str
@tool
def structured_tool(
some_enum: SomeEnum,
some_base_model: SomeBaseModel,
) -> dict:
"""Return the arguments directly."""
return {
"some_enum": some_enum,
"some_base_model": some_base_model,
}
assert isinstance(structured_tool, StructuredTool)
args = {
"some_enum": SomeEnum.A.value,
"some_base_model": SomeBaseModel(foo="bar").model_dump(),
}
result = structured_tool.run(json.loads(json.dumps(args)))
expected = {
"some_enum": SomeEnum.A,
"some_base_model": SomeBaseModel(foo="bar"),
}
assert result == expected
@pytest.mark.skipif(
sys.version_info >= (3, 14),
reason="pydantic.v1 namespace not supported with Python 3.14+",
)
def test_structured_tool_types_parsed_pydantic_v1() -> None:
"""Test the non-primitive types are correctly passed to structured tools."""
class SomeBaseModel(BaseModelV1):
foo: str
class AnotherBaseModel(BaseModelV1):
bar: str
@tool
def structured_tool(some_base_model: SomeBaseModel) -> AnotherBaseModel:
"""Return the arguments directly."""
return AnotherBaseModel(bar=some_base_model.foo)
assert isinstance(structured_tool, StructuredTool)
expected = AnotherBaseModel(bar="baz")
for arg in [
SomeBaseModel(foo="baz"),
SomeBaseModel(foo="baz").dict(),
]:
args = {"some_base_model": arg}
result = structured_tool.run(args)
assert result == expected
def test_structured_tool_types_parsed_pydantic_mixed() -> None:
"""Test handling of tool with mixed Pydantic version arguments."""
class SomeBaseModel(BaseModelV1):
foo: str
class AnotherBaseModel(BaseModel):
bar: str
with pytest.raises(NotImplementedError):
@tool
def structured_tool(
some_base_model: SomeBaseModel, another_base_model: AnotherBaseModel
) -> None:
"""Return the arguments directly."""
def test_base_tool_inheritance_base_schema() -> None:
"""Test schema is correctly inferred when inheriting from BaseTool."""
class _MockSimpleTool(BaseTool):
name: str = "simple_tool"
description: str = "A Simple Tool"
@override
def _run(self, tool_input: str) -> str:
return f"{tool_input}"
@override
async def _arun(self, tool_input: str) -> str:
raise NotImplementedError
simple_tool = _MockSimpleTool()
assert simple_tool.args_schema is None
expected_args = {"tool_input": {"title": "Tool Input", "type": "string"}}
assert simple_tool.args == expected_args
def test_tool_lambda_args_schema() -> None:
"""Test args schema inference when the tool argument is a lambda function."""
tool = Tool(
name="tool",
description="A tool",
func=lambda tool_input: tool_input,
)
assert tool.args_schema is None
expected_args = {"tool_input": {"type": "string"}}
assert tool.args == expected_args
def test_structured_tool_from_function_docstring() -> None:
"""Test that structured tools can be created from functions."""
def foo(bar: int, baz: str) -> str:
"""Docstring.
Args:
bar: the bar value
baz: the baz value
"""
raise NotImplementedError
structured_tool = StructuredTool.from_function(foo)
assert structured_tool.name == "foo"
assert structured_tool.args == {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
}
assert _schema(structured_tool.args_schema) == {
"properties": {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
},
"description": inspect.getdoc(foo),
"title": "foo",
"type": "object",
"required": ["bar", "baz"],
}
assert foo.__doc__ is not None
assert structured_tool.description == textwrap.dedent(foo.__doc__.strip())
def test_structured_tool_from_function_docstring_complex_args() -> None:
"""Test that structured tools can be created from functions."""
def foo(bar: int, baz: list[str]) -> str:
"""Docstring.
Args:
bar: int
baz: list[str]
"""
raise NotImplementedError
structured_tool = StructuredTool.from_function(foo)
assert structured_tool.name == "foo"
assert structured_tool.args == {
"bar": {"title": "Bar", "type": "integer"},
"baz": {
"title": "Baz",
"type": "array",
"items": {"type": "string"},
},
}
assert _schema(structured_tool.args_schema) == {
"properties": {
"bar": {"title": "Bar", "type": "integer"},
"baz": {
"title": "Baz",
"type": "array",
"items": {"type": "string"},
},
},
"description": inspect.getdoc(foo),
"title": "foo",
"type": "object",
"required": ["bar", "baz"],
}
assert foo.__doc__ is not None
assert structured_tool.description == textwrap.dedent(foo.__doc__).strip()
def test_structured_tool_lambda_multi_args_schema() -> None:
"""Test args schema inference when the tool argument is a lambda function."""
tool = StructuredTool.from_function(
name="tool",
description="A tool",
func=lambda tool_input, other_arg: f"{tool_input}{other_arg}",
)
assert tool.args_schema is not None
expected_args = {
"tool_input": {"title": "Tool Input"},
"other_arg": {"title": "Other Arg"},
}
assert tool.args == expected_args
def test_tool_partial_function_args_schema() -> None:
"""Test args schema inference when the tool argument is a partial function."""
def func(tool_input: str, other_arg: str) -> str:
assert isinstance(tool_input, str)
assert isinstance(other_arg, str)
return tool_input + other_arg
tool = Tool(
name="tool",
description="A tool",
func=partial(func, other_arg="foo"),
)
assert tool.run("bar") == "barfoo"
def test_empty_args_decorator() -> None:
"""Test inferred schema of decorated fn with no args."""
@tool
def empty_tool_input() -> str:
"""Return a constant."""
return "the empty result"
assert isinstance(empty_tool_input, BaseTool)
assert empty_tool_input.name == "empty_tool_input"
assert empty_tool_input.args == {}
assert empty_tool_input.run({}) == "the empty result"
def test_tool_from_function_with_run_manager() -> None:
"""Test run of tool when using run_manager."""
def foo(bar: str, callbacks: CallbackManagerForToolRun | None = None) -> str: # noqa: D417
"""Docstring.
Args:
bar: str.
"""
assert callbacks is not None
return "foo" + bar
handler = FakeCallbackHandler()
tool = Tool.from_function(foo, name="foo", description="Docstring")
assert tool.run(tool_input={"bar": "bar"}, run_manager=[handler]) == "foobar"
assert tool.run("baz", run_manager=[handler]) == "foobaz"
def test_structured_tool_from_function_with_run_manager() -> None:
"""Test args and schema of structured tool when using callbacks."""
def foo( # noqa: D417
bar: int, baz: str, callbacks: CallbackManagerForToolRun | None = None
) -> str:
"""Docstring.
Args:
bar: int
baz: str
"""
assert callbacks is not None
return str(bar) + baz
handler = FakeCallbackHandler()
structured_tool = StructuredTool.from_function(foo)
assert structured_tool.args == {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
}
assert _schema(structured_tool.args_schema) == {
"properties": {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
},
"description": inspect.getdoc(foo),
"title": "foo",
"type": "object",
"required": ["bar", "baz"],
}
assert (
structured_tool.run(
tool_input={"bar": "10", "baz": "baz"}, run_manger=[handler]
)
== "10baz"
)
def test_structured_tool_from_parameterless_function() -> None:
"""Test parameterless function of structured tool."""
def foo() -> str:
"""Docstring."""
return "invoke foo"
structured_tool = StructuredTool.from_function(foo)
assert structured_tool.run({}) == "invoke foo"
assert structured_tool.run("") == "invoke foo"
def test_named_tool_decorator() -> None:
"""Test functionality when arguments are provided as input to decorator."""
@tool("search")
def search_api(query: str) -> str:
"""Search the API for the query."""
assert isinstance(query, str)
return f"API result - {query}"
assert isinstance(search_api, BaseTool)
assert search_api.name == "search"
assert not search_api.return_direct
assert search_api.run({"query": "foo"}) == "API result - foo"
def test_named_tool_decorator_return_direct() -> None:
"""Test functionality when arguments and return direct are provided as input."""
@tool("search", return_direct=True)
def search_api(query: str, *args: Any) -> str:
"""Search the API for the query."""
return "API result"
assert isinstance(search_api, BaseTool)
assert search_api.name == "search"
assert search_api.return_direct
assert search_api.run({"query": "foo"}) == "API result"
def test_unnamed_tool_decorator_return_direct() -> None:
"""Test functionality when only return direct is provided."""
@tool(return_direct=True)
def search_api(query: str) -> str:
"""Search the API for the query."""
assert isinstance(query, str)
return "API result"
assert isinstance(search_api, BaseTool)
assert search_api.name == "search_api"
assert search_api.return_direct
assert search_api.run({"query": "foo"}) == "API result"
def test_tool_with_kwargs() -> None:
"""Test functionality when only return direct is provided."""
@tool(return_direct=True)
def search_api(
arg_0: str,
arg_1: float = 4.3,
ping: str = "hi",
) -> str:
"""Search the API for the query."""
return f"arg_0={arg_0}, arg_1={arg_1}, ping={ping}"
assert isinstance(search_api, BaseTool)
result = search_api.run(
tool_input={
"arg_0": "foo",
"arg_1": 3.2,
"ping": "pong",
}
)
assert result == "arg_0=foo, arg_1=3.2, ping=pong"
result = search_api.run(
tool_input={
"arg_0": "foo",
}
)
assert result == "arg_0=foo, arg_1=4.3, ping=hi"
# For backwards compatibility, we still accept a single str arg
result = search_api.run("foobar")
assert result == "arg_0=foobar, arg_1=4.3, ping=hi"
def test_missing_docstring() -> None:
"""Test error is raised when docstring is missing."""
# expect to throw a value error if there's no docstring
with pytest.raises(ValueError, match="Function must have a docstring"):
@tool
def search_api(query: str) -> str:
return "API result"
@tool
class MyTool(BaseModel):
foo: str
assert not MyTool.description # type: ignore[attr-defined]
def test_create_tool_positional_args() -> None:
"""Test that positional arguments are allowed."""
test_tool = Tool("test_name", lambda x: x, "test_description")
assert test_tool.invoke("foo") == "foo"
assert test_tool.name == "test_name"
assert test_tool.description == "test_description"
assert test_tool.is_single_input
def test_create_tool_keyword_args() -> None:
"""Test that keyword arguments are allowed."""
test_tool = Tool(name="test_name", func=lambda x: x, description="test_description")
assert test_tool.is_single_input
assert test_tool.invoke("foo") == "foo"
assert test_tool.name == "test_name"
assert test_tool.description == "test_description"
async def test_create_async_tool() -> None:
"""Test that async tools are allowed."""
async def _test_func(x: str) -> str:
return x
test_tool = Tool(
name="test_name",
func=lambda x: x,
description="test_description",
coroutine=_test_func,
)
assert test_tool.is_single_input
assert test_tool.invoke("foo") == "foo"
assert test_tool.name == "test_name"
assert test_tool.description == "test_description"
assert test_tool.coroutine is not None
assert await test_tool.arun("foo") == "foo"
class _FakeExceptionTool(BaseTool):
name: str = "exception"
description: str = "an exception-throwing tool"
exception: Exception = ToolException()
def _run(self) -> str:
raise self.exception
async def _arun(self) -> str:
raise self.exception
def test_exception_handling_bool() -> None:
tool_ = _FakeExceptionTool(handle_tool_error=True)
expected = "Tool execution error"
actual = tool_.run({})
assert expected == actual
def test_exception_handling_str() -> None:
expected = "foo bar"
tool_ = _FakeExceptionTool(handle_tool_error=expected)
actual = tool_.run({})
assert expected == actual
def test_exception_handling_callable() -> None:
expected = "foo bar"
def handling(e: ToolException) -> str:
return expected
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = tool_.run({})
assert expected == actual
def test_exception_handling_non_tool_exception() -> None:
tool_ = _FakeExceptionTool(exception=ValueError("some error"))
with pytest.raises(ValueError, match="some error"):
tool_.run({})
async def test_async_exception_handling_bool() -> None:
tool_ = _FakeExceptionTool(handle_tool_error=True)
expected = "Tool execution error"
actual = await tool_.arun({})
assert expected == actual
async def test_async_exception_handling_str() -> None:
expected = "foo bar"
tool_ = _FakeExceptionTool(handle_tool_error=expected)
actual = await tool_.arun({})
assert expected == actual
async def test_async_exception_handling_callable() -> None:
expected = "foo bar"
def handling(e: ToolException) -> str:
return expected
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = await tool_.arun({})
assert expected == actual
async def test_async_exception_handling_non_tool_exception() -> None:
tool_ = _FakeExceptionTool(exception=ValueError("some error"))
with pytest.raises(ValueError, match="some error"):
await tool_.arun({})
def test_structured_tool_from_function() -> None:
"""Test that structured tools can be created from functions."""
def foo(bar: int, baz: str) -> str:
"""Docstring thing.
Args:
bar: the bar value
baz: the baz value
"""
raise NotImplementedError
structured_tool = StructuredTool.from_function(foo)
assert structured_tool.name == "foo"
assert structured_tool.args == {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
}
assert _schema(structured_tool.args_schema) == {
"title": "foo",
"type": "object",
"description": inspect.getdoc(foo),
"properties": {
"bar": {"title": "Bar", "type": "integer"},
"baz": {"title": "Baz", "type": "string"},
},
"required": ["bar", "baz"],
}
assert foo.__doc__ is not None
assert structured_tool.description == textwrap.dedent(foo.__doc__.strip())
def test_validation_error_handling_bool() -> None:
"""Test that validation errors are handled correctly."""
expected = "Tool input validation error"
tool_ = _MockStructuredTool(handle_validation_error=True)
actual = tool_.run({})
assert expected == actual
def test_validation_error_handling_str() -> None:
"""Test that validation errors are handled correctly."""
expected = "foo bar"
tool_ = _MockStructuredTool(handle_validation_error=expected)
actual = tool_.run({})
assert expected == actual
def test_validation_error_handling_callable() -> None:
"""Test that validation errors are handled correctly."""
expected = "foo bar"
def handling(e: ValidationError | ValidationErrorV1) -> str:
return expected
tool_ = _MockStructuredTool(handle_validation_error=handling)
actual = tool_.run({})
assert expected == actual
@pytest.mark.parametrize(
"handler",
[
True,
"foo bar",
lambda _: "foo bar",
],
)
def test_validation_error_handling_non_validation_error(
*,
handler: bool | str | Callable[[ValidationError | ValidationErrorV1], str],
) -> None:
"""Test that validation errors are handled correctly."""
class _RaiseNonValidationErrorTool(BaseTool):
name: str = "raise_non_validation_error_tool"
description: str = "A tool that raises a non-validation error"
def _parse_input(
self,
tool_input: str | dict,
tool_call_id: str | None,
) -> str | dict[str, Any]:
raise NotImplementedError
@override
def _run(self) -> str:
return "dummy"
@override
async def _arun(self) -> str:
return "dummy"
tool_ = _RaiseNonValidationErrorTool(handle_validation_error=handler)
with pytest.raises(NotImplementedError):
tool_.run({})
async def test_async_validation_error_handling_bool() -> None:
"""Test that validation errors are handled correctly."""
expected = "Tool input validation error"
tool_ = _MockStructuredTool(handle_validation_error=True)
actual = await tool_.arun({})
assert expected == actual
async def test_async_validation_error_handling_str() -> None:
"""Test that validation errors are handled correctly."""
expected = "foo bar"
tool_ = _MockStructuredTool(handle_validation_error=expected)
actual = await tool_.arun({})
assert expected == actual
async def test_async_validation_error_handling_callable() -> None:
"""Test that validation errors are handled correctly."""
expected = "foo bar"
def handling(e: ValidationError | ValidationErrorV1) -> str:
return expected
tool_ = _MockStructuredTool(handle_validation_error=handling)
actual = await tool_.arun({})
assert expected == actual
@pytest.mark.parametrize(
"handler",
[
True,
"foo bar",
lambda _: "foo bar",
],
)
async def test_async_validation_error_handling_non_validation_error(
*,
handler: bool | str | Callable[[ValidationError | ValidationErrorV1], str],
) -> None:
"""Test that validation errors are handled correctly."""
class _RaiseNonValidationErrorTool(BaseTool):
name: str = "raise_non_validation_error_tool"
description: str = "A tool that raises a non-validation error"
def _parse_input(
self,
tool_input: str | dict,
tool_call_id: str | None,