-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathtest_function_schema.py
More file actions
1016 lines (762 loc) · 36.2 KB
/
test_function_schema.py
File metadata and controls
1016 lines (762 loc) · 36.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
from collections.abc import Mapping
from enum import Enum
from typing import Annotated, Any, Literal
import pytest
from pydantic import BaseModel, Field, ValidationError
from typing_extensions import TypedDict
from agents import RunContextWrapper
from agents.exceptions import UserError
from agents.function_schema import function_schema
def no_args_function():
"""This function has no args."""
return "ok"
def test_no_args_function():
func_schema = function_schema(no_args_function)
assert func_schema.params_json_schema.get("title") == "no_args_function_args"
assert func_schema.description == "This function has no args."
assert not func_schema.takes_context
parsed = func_schema.params_pydantic_model()
args, kwargs_dict = func_schema.to_call_args(parsed)
result = no_args_function(*args, **kwargs_dict)
assert result == "ok"
def no_args_function_with_context(ctx: RunContextWrapper[str]):
return "ok"
def test_no_args_function_with_context() -> None:
func_schema = function_schema(no_args_function_with_context)
assert func_schema.takes_context
context = RunContextWrapper(context="test")
parsed = func_schema.params_pydantic_model()
args, kwargs_dict = func_schema.to_call_args(parsed)
result = no_args_function_with_context(context, *args, **kwargs_dict)
assert result == "ok"
def simple_function(a: int, b: int = 5):
"""
Args:
a: The first argument
b: The second argument
Returns:
The sum of a and b
"""
return a + b
def test_simple_function():
"""Test a function that has simple typed parameters and defaults."""
func_schema = function_schema(simple_function)
# Check that the JSON schema is a dictionary with title, type, etc.
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "simple_function_args"
assert (
func_schema.params_json_schema.get("properties", {}).get("a").get("description")
== "The first argument"
)
assert (
func_schema.params_json_schema.get("properties", {}).get("b").get("description")
== "The second argument"
)
assert not func_schema.takes_context
# Valid input
valid_input = {"a": 3}
parsed = func_schema.params_pydantic_model(**valid_input)
args_tuple, kwargs_dict = func_schema.to_call_args(parsed)
result = simple_function(*args_tuple, **kwargs_dict)
assert result == 8 # 3 + 5
# Another valid input
valid_input2 = {"a": 3, "b": 10}
parsed2 = func_schema.params_pydantic_model(**valid_input2)
args_tuple2, kwargs_dict2 = func_schema.to_call_args(parsed2)
result2 = simple_function(*args_tuple2, **kwargs_dict2)
assert result2 == 13 # 3 + 10
# Invalid input: 'a' must be int
with pytest.raises(ValidationError):
func_schema.params_pydantic_model(**{"a": "not an integer"})
def varargs_function(x: int, *numbers: float, flag: bool = False, **kwargs: Any):
return x, numbers, flag, kwargs
def test_varargs_function():
"""Test a function that uses *args and **kwargs."""
func_schema = function_schema(varargs_function, strict_json_schema=False)
# Check JSON schema structure
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "varargs_function_args"
# Valid input including *args in 'numbers' and **kwargs in 'kwargs'
valid_input = {
"x": 10,
"numbers": [1.1, 2.2, 3.3],
"flag": True,
"kwargs": {"extra1": "hello", "extra2": 42},
}
parsed = func_schema.params_pydantic_model(**valid_input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = varargs_function(*args, **kwargs_dict)
# result should be (10, (1.1, 2.2, 3.3), True, {"extra1": "hello", "extra2": 42})
assert result[0] == 10
assert result[1] == (1.1, 2.2, 3.3)
assert result[2] is True
assert result[3] == {"extra1": "hello", "extra2": 42}
# Missing 'x' should raise error
with pytest.raises(ValidationError):
func_schema.params_pydantic_model(**{"numbers": [1.1, 2.2]})
# 'flag' can be omitted because it has a default
valid_input_no_flag = {"x": 7, "numbers": [9.9], "kwargs": {"some_key": "some_value"}}
parsed2 = func_schema.params_pydantic_model(**valid_input_no_flag)
args2, kwargs_dict2 = func_schema.to_call_args(parsed2)
result2 = varargs_function(*args2, **kwargs_dict2)
# result2 should be (7, (9.9,), False, {'some_key': 'some_value'})
assert result2 == (7, (9.9,), False, {"some_key": "some_value"})
class Foo(TypedDict):
a: int
b: str
class InnerModel(BaseModel):
a: int
b: str
class OuterModel(BaseModel):
inner: InnerModel
foo: Foo
def complex_args_function(model: OuterModel) -> str:
return f"{model.inner.a}, {model.inner.b}, {model.foo['a']}, {model.foo['b']}"
def test_nested_data_function():
func_schema = function_schema(complex_args_function)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "complex_args_function_args"
# Valid input
model = OuterModel(inner=InnerModel(a=1, b="hello"), foo=Foo(a=2, b="world"))
valid_input = {
"model": model.model_dump(),
}
parsed = func_schema.params_pydantic_model(**valid_input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = complex_args_function(*args, **kwargs_dict)
assert result == "1, hello, 2, world"
def complex_args_and_docs_function(model: OuterModel, some_flag: int = 0) -> str:
"""
This function takes a model and a flag, and returns a string.
Args:
model: A model with an inner and foo field
some_flag: An optional flag with a default of 0
Returns:
A string with the values of the model and flag
"""
return f"{model.inner.a}, {model.inner.b}, {model.foo['a']}, {model.foo['b']}, {some_flag or 0}"
def test_complex_args_and_docs_function():
func_schema = function_schema(complex_args_and_docs_function)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "complex_args_and_docs_function_args"
# Check docstring is parsed correctly
properties = func_schema.params_json_schema.get("properties", {})
assert properties.get("model").get("description") == "A model with an inner and foo field"
assert properties.get("some_flag").get("description") == "An optional flag with a default of 0"
# Valid input
model = OuterModel(inner=InnerModel(a=1, b="hello"), foo=Foo(a=2, b="world"))
valid_input = {
"model": model.model_dump(),
}
parsed = func_schema.params_pydantic_model(**valid_input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = complex_args_and_docs_function(*args, **kwargs_dict)
assert result == "1, hello, 2, world, 0"
# Invalid input: 'some_flag' must be int
with pytest.raises(ValidationError):
func_schema.params_pydantic_model(
**{"model": model.model_dump(), "some_flag": "not an int"}
)
# Valid input: 'some_flag' can be omitted because it has a default
valid_input_no_flag = {"model": model.model_dump()}
parsed2 = func_schema.params_pydantic_model(**valid_input_no_flag)
args2, kwargs_dict2 = func_schema.to_call_args(parsed2)
result2 = complex_args_and_docs_function(*args2, **kwargs_dict2)
assert result2 == "1, hello, 2, world, 0"
def function_with_context(ctx: RunContextWrapper[str], a: int, b: int = 5):
return a + b
def test_function_with_context():
func_schema = function_schema(function_with_context)
assert func_schema.takes_context
context = RunContextWrapper(context="test")
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = function_with_context(context, *args, **kwargs_dict)
assert result == 3
class MyClass:
def foo(self, a: int, b: int = 5):
return a + b
def foo_ctx(self, ctx: RunContextWrapper[str], a: int, b: int = 5):
return a + b
@classmethod
def bar(cls, a: int, b: int = 5):
return a + b
@classmethod
def bar_ctx(cls, ctx: RunContextWrapper[str], a: int, b: int = 5):
return a + b
@staticmethod
def baz(a: int, b: int = 5):
return a + b
@staticmethod
def baz_ctx(ctx: RunContextWrapper[str], a: int, b: int = 5):
return a + b
def test_class_based_functions():
context = RunContextWrapper(context="test")
# Instance method
instance = MyClass()
func_schema = function_schema(instance.foo)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "foo_args"
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = instance.foo(*args, **kwargs_dict)
assert result == 3
# Instance method with context
func_schema = function_schema(instance.foo_ctx)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "foo_ctx_args"
assert func_schema.takes_context
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = instance.foo_ctx(context, *args, **kwargs_dict)
assert result == 3
# Class method
func_schema = function_schema(MyClass.bar)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "bar_args"
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = MyClass.bar(*args, **kwargs_dict)
assert result == 3
# Class method with context
func_schema = function_schema(MyClass.bar_ctx)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "bar_ctx_args"
assert func_schema.takes_context
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = MyClass.bar_ctx(context, *args, **kwargs_dict)
assert result == 3
# Static method
func_schema = function_schema(MyClass.baz)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "baz_args"
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = MyClass.baz(*args, **kwargs_dict)
assert result == 3
# Static method with context
func_schema = function_schema(MyClass.baz_ctx)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "baz_ctx_args"
assert func_schema.takes_context
input = {"a": 1, "b": 2}
parsed = func_schema.params_pydantic_model(**input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = MyClass.baz_ctx(context, *args, **kwargs_dict)
assert result == 3
class MyEnum(str, Enum):
FOO = "foo"
BAR = "bar"
BAZ = "baz"
def enum_and_literal_function(a: MyEnum, b: Literal["a", "b", "c"]) -> str:
return f"{a.value} {b}"
def test_enum_and_literal_function():
func_schema = function_schema(enum_and_literal_function)
assert isinstance(func_schema.params_json_schema, dict)
assert func_schema.params_json_schema.get("title") == "enum_and_literal_function_args"
# Check that the enum values are included in the JSON schema
assert func_schema.params_json_schema.get("$defs", {}).get("MyEnum", {}).get("enum") == [
"foo",
"bar",
"baz",
]
# Check that the enum is expressed as a def
assert (
func_schema.params_json_schema.get("properties", {}).get("a", {}).get("$ref")
== "#/$defs/MyEnum"
)
# Check that the literal values are included in the JSON schema
assert func_schema.params_json_schema.get("properties", {}).get("b", {}).get("enum") == [
"a",
"b",
"c",
]
# Valid input
valid_input = {"a": "foo", "b": "a"}
parsed = func_schema.params_pydantic_model(**valid_input)
args, kwargs_dict = func_schema.to_call_args(parsed)
result = enum_and_literal_function(*args, **kwargs_dict)
assert result == "foo a"
# Invalid input: 'a' must be a valid enum value
with pytest.raises(ValidationError):
func_schema.params_pydantic_model(**{"a": "not an enum value", "b": "a"})
# Invalid input: 'b' must be a valid literal value
with pytest.raises(ValidationError):
func_schema.params_pydantic_model(**{"a": "foo", "b": "not a literal value"})
def test_run_context_in_non_first_position_raises_value_error():
# When a parameter (after the first) is annotated as RunContextWrapper,
# function_schema() should raise a UserError.
def func(a: int, context: RunContextWrapper) -> None:
pass
with pytest.raises(UserError):
function_schema(func, use_docstring_info=False)
def test_var_positional_tuple_annotation():
# When a function has a var-positional parameter annotated with a tuple type,
# function_schema() should convert it into a field with type List[<tuple-element>].
def func(*args: tuple[int, ...]) -> int:
total = 0
for arg in args:
total += sum(arg)
return total
fs = function_schema(func, use_docstring_info=False)
properties = fs.params_json_schema.get("properties", {})
assert properties.get("args").get("type") == "array"
assert properties.get("args").get("items").get("type") == "integer"
def test_var_keyword_dict_annotation():
# Case 3:
# When a function has a var-keyword parameter annotated with a dict type,
# function_schema() should convert it into a field with type Dict[<key>, <value>].
def func(**kwargs: dict[str, int]):
return kwargs
fs = function_schema(func, use_docstring_info=False, strict_json_schema=False)
properties = fs.params_json_schema.get("properties", {})
# The name of the field is "kwargs", and it's a JSON object i.e. a dict.
assert properties.get("kwargs").get("type") == "object"
# The values in the dict are integers.
assert properties.get("kwargs").get("additionalProperties").get("type") == "integer"
def test_schema_with_mapping_raises_strict_mode_error():
"""A mapping type is not allowed in strict mode. Same for dicts. Ensure we raise a UserError."""
def func_with_mapping(test_one: Mapping[str, int]) -> str:
return "foo"
with pytest.raises(UserError):
function_schema(func_with_mapping)
def test_name_override_without_docstring() -> None:
"""name_override should be used even when not parsing docstrings."""
def foo(x: int) -> int:
return x
fs = function_schema(foo, use_docstring_info=False, name_override="custom")
assert fs.name == "custom"
assert fs.params_json_schema.get("title") == "custom_args"
def test_function_with_field_required_constraints():
"""Test function with required Field parameter that has constraints."""
def func_with_field_constraints(my_number: int = Field(..., gt=10, le=100)) -> int:
return my_number * 2
fs = function_schema(func_with_field_constraints, use_docstring_info=False)
# Check that the schema includes the constraints
properties = fs.params_json_schema.get("properties", {})
my_number_schema = properties.get("my_number", {})
assert my_number_schema.get("type") == "integer"
assert my_number_schema.get("exclusiveMinimum") == 10 # gt=10
assert my_number_schema.get("maximum") == 100 # le=100
# Valid input should work
valid_input = {"my_number": 50}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_field_constraints(*args, **kwargs_dict)
assert result == 100
# Invalid input: too small (should violate gt=10)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"my_number": 5})
# Invalid input: too large (should violate le=100)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"my_number": 150})
def test_function_with_field_optional_with_default():
"""Test function with optional Field parameter that has default and constraints."""
def func_with_optional_field(
required_param: str,
optional_param: float = Field(default=5.0, ge=0.0),
) -> str:
return f"{required_param}: {optional_param}"
fs = function_schema(func_with_optional_field, use_docstring_info=False)
# Check that the schema includes the constraints and description
properties = fs.params_json_schema.get("properties", {})
optional_schema = properties.get("optional_param", {})
assert optional_schema.get("type") == "number"
assert optional_schema.get("minimum") == 0.0 # ge=0.0
assert optional_schema.get("default") == 5.0
# Valid input with default
valid_input = {"required_param": "test"}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_optional_field(*args, **kwargs_dict)
assert result == "test: 5.0"
# Valid input with explicit value
valid_input2 = {"required_param": "test", "optional_param": 10.5}
parsed2 = fs.params_pydantic_model(**valid_input2)
args2, kwargs_dict2 = fs.to_call_args(parsed2)
result2 = func_with_optional_field(*args2, **kwargs_dict2)
assert result2 == "test: 10.5"
# Invalid input: negative value (should violate ge=0.0)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"required_param": "test", "optional_param": -1.0})
def test_function_uses_annotated_descriptions_without_docstring() -> None:
"""Test that Annotated metadata populates parameter descriptions when docstrings are ignored."""
def add(
a: Annotated[int, "First number to add"],
b: Annotated[int, "Second number to add"],
) -> int:
return a + b
fs = function_schema(add, use_docstring_info=False)
properties = fs.params_json_schema.get("properties", {})
assert properties["a"].get("description") == "First number to add"
assert properties["b"].get("description") == "Second number to add"
def test_function_prefers_docstring_descriptions_over_annotated_metadata() -> None:
"""Test that docstring parameter descriptions take precedence over Annotated metadata."""
def add(
a: Annotated[int, "Annotated description for a"],
b: Annotated[int, "Annotated description for b"],
) -> int:
"""Adds two integers.
Args:
a: Docstring provided description.
"""
return a + b
fs = function_schema(add)
properties = fs.params_json_schema.get("properties", {})
assert properties["a"].get("description") == "Docstring provided description."
assert properties["b"].get("description") == "Annotated description for b"
def test_function_with_field_description_merge():
"""Test that Field descriptions are merged with docstring descriptions."""
def func_with_field_and_docstring(
param_with_field_desc: int = Field(..., description="Field description"),
param_with_both: str = Field(default="hello", description="Field description"),
) -> str:
"""
Function with both field and docstring descriptions.
Args:
param_with_field_desc: Docstring description
param_with_both: Docstring description
"""
return f"{param_with_field_desc}: {param_with_both}"
fs = function_schema(func_with_field_and_docstring, use_docstring_info=True)
# Check that docstring description takes precedence when both exist
properties = fs.params_json_schema.get("properties", {})
param1_schema = properties.get("param_with_field_desc", {})
param2_schema = properties.get("param_with_both", {})
# The docstring description should be used when both are present
assert param1_schema.get("description") == "Docstring description"
assert param2_schema.get("description") == "Docstring description"
def func_with_field_desc_only(
param_with_field_desc: int = Field(..., description="Field description only"),
param_without_desc: str = Field(default="hello"),
) -> str:
return f"{param_with_field_desc}: {param_without_desc}"
def test_function_with_field_description_only():
"""Test that Field descriptions are used when no docstring info."""
fs = function_schema(func_with_field_desc_only)
# Check that field description is used when no docstring
properties = fs.params_json_schema.get("properties", {})
param1_schema = properties.get("param_with_field_desc", {})
param2_schema = properties.get("param_without_desc", {})
assert param1_schema.get("description") == "Field description only"
assert param2_schema.get("description") is None
def test_function_with_field_string_constraints():
"""Test function with Field parameter that has string-specific constraints."""
def func_with_string_field(
name: str = Field(..., min_length=3, max_length=20, pattern=r"^[A-Za-z]+$"),
) -> str:
return f"Hello, {name}!"
fs = function_schema(func_with_string_field, use_docstring_info=False)
# Check that the schema includes string constraints
properties = fs.params_json_schema.get("properties", {})
name_schema = properties.get("name", {})
assert name_schema.get("type") == "string"
assert name_schema.get("minLength") == 3
assert name_schema.get("maxLength") == 20
assert name_schema.get("pattern") == r"^[A-Za-z]+$"
# Valid input
valid_input = {"name": "Alice"}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_string_field(*args, **kwargs_dict)
assert result == "Hello, Alice!"
# Invalid input: too short
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "Al"})
# Invalid input: too long
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "A" * 25})
# Invalid input: doesn't match pattern (contains numbers)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "Alice123"})
def test_function_with_field_multiple_constraints():
"""Test function with multiple Field parameters having different constraint types."""
def func_with_multiple_field_constraints(
score: int = Field(..., ge=0, le=100, description="Score from 0 to 100"),
name: str = Field(default="Unknown", min_length=1, max_length=50),
factor: float = Field(default=1.0, gt=0.0, description="Positive multiplier"),
) -> str:
final_score = score * factor
return f"{name} scored {final_score}"
fs = function_schema(func_with_multiple_field_constraints, use_docstring_info=False)
# Check schema structure
properties = fs.params_json_schema.get("properties", {})
# Check score field
score_schema = properties.get("score", {})
assert score_schema.get("type") == "integer"
assert score_schema.get("minimum") == 0
assert score_schema.get("maximum") == 100
assert score_schema.get("description") == "Score from 0 to 100"
# Check name field
name_schema = properties.get("name", {})
assert name_schema.get("type") == "string"
assert name_schema.get("minLength") == 1
assert name_schema.get("maxLength") == 50
assert name_schema.get("default") == "Unknown"
# Check factor field
factor_schema = properties.get("factor", {})
assert factor_schema.get("type") == "number"
assert factor_schema.get("exclusiveMinimum") == 0.0
assert factor_schema.get("default") == 1.0
assert factor_schema.get("description") == "Positive multiplier"
# Valid input with defaults
valid_input = {"score": 85}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_multiple_field_constraints(*args, **kwargs_dict)
assert result == "Unknown scored 85.0"
# Valid input with all parameters
valid_input2 = {"score": 90, "name": "Alice", "factor": 1.5}
parsed2 = fs.params_pydantic_model(**valid_input2)
args2, kwargs_dict2 = fs.to_call_args(parsed2)
result2 = func_with_multiple_field_constraints(*args2, **kwargs_dict2)
assert result2 == "Alice scored 135.0"
# Test various validation errors
with pytest.raises(ValidationError): # score too high
fs.params_pydantic_model(**{"score": 150})
with pytest.raises(ValidationError): # empty name
fs.params_pydantic_model(**{"score": 50, "name": ""})
with pytest.raises(ValidationError): # zero factor
fs.params_pydantic_model(**{"score": 50, "factor": 0.0})
# --- Annotated + Field: same behavior as Field as default ---
def test_function_with_annotated_field_required_constraints():
"""Test function with required Annotated[int, Field(...)] parameter that has constraints."""
def func_with_annotated_field_constraints(
my_number: Annotated[int, Field(..., gt=10, le=100)],
) -> int:
return my_number * 2
fs = function_schema(func_with_annotated_field_constraints, use_docstring_info=False)
# Check that the schema includes the constraints
properties = fs.params_json_schema.get("properties", {})
my_number_schema = properties.get("my_number", {})
assert my_number_schema.get("type") == "integer"
assert my_number_schema.get("exclusiveMinimum") == 10 # gt=10
assert my_number_schema.get("maximum") == 100 # le=100
# Valid input should work
valid_input = {"my_number": 50}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_annotated_field_constraints(*args, **kwargs_dict)
assert result == 100
# Invalid input: too small (should violate gt=10)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"my_number": 5})
# Invalid input: too large (should violate le=100)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"my_number": 150})
def test_function_with_annotated_field_optional_with_default():
"""Optional Annotated[float, Field(...)] param with default and constraints."""
def func_with_annotated_optional_field(
required_param: str,
optional_param: Annotated[float, Field(default=5.0, ge=0.0)],
) -> str:
return f"{required_param}: {optional_param}"
fs = function_schema(func_with_annotated_optional_field, use_docstring_info=False)
# Check that the schema includes the constraints and description
properties = fs.params_json_schema.get("properties", {})
optional_schema = properties.get("optional_param", {})
assert optional_schema.get("type") == "number"
assert optional_schema.get("minimum") == 0.0 # ge=0.0
assert optional_schema.get("default") == 5.0
# Valid input with default
valid_input = {"required_param": "test"}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_annotated_optional_field(*args, **kwargs_dict)
assert result == "test: 5.0"
# Valid input with explicit value
valid_input2 = {"required_param": "test", "optional_param": 10.5}
parsed2 = fs.params_pydantic_model(**valid_input2)
args2, kwargs_dict2 = fs.to_call_args(parsed2)
result2 = func_with_annotated_optional_field(*args2, **kwargs_dict2)
assert result2 == "test: 10.5"
# Invalid input: negative value (should violate ge=0.0)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"required_param": "test", "optional_param": -1.0})
def test_function_with_annotated_field_string_constraints():
"""Annotated[str, Field(...)] parameter with string constraints (min/max length, pattern)."""
def func_with_annotated_string_field(
name: Annotated[
str,
Field(..., min_length=3, max_length=20, pattern=r"^[A-Za-z]+$"),
],
) -> str:
return f"Hello, {name}!"
fs = function_schema(func_with_annotated_string_field, use_docstring_info=False)
# Check that the schema includes string constraints
properties = fs.params_json_schema.get("properties", {})
name_schema = properties.get("name", {})
assert name_schema.get("type") == "string"
assert name_schema.get("minLength") == 3
assert name_schema.get("maxLength") == 20
assert name_schema.get("pattern") == r"^[A-Za-z]+$"
# Valid input
valid_input = {"name": "Alice"}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_annotated_string_field(*args, **kwargs_dict)
assert result == "Hello, Alice!"
# Invalid input: too short
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "Al"})
# Invalid input: too long
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "A" * 25})
# Invalid input: doesn't match pattern (contains numbers)
with pytest.raises(ValidationError):
fs.params_pydantic_model(**{"name": "Alice123"})
def test_function_with_annotated_field_multiple_constraints():
"""Test function with multiple Annotated params with Field having different constraint types."""
def func_with_annotated_multiple_field_constraints(
score: Annotated[
int,
Field(..., ge=0, le=100, description="Score from 0 to 100"),
],
name: Annotated[str, Field(default="Unknown", min_length=1, max_length=50)],
factor: Annotated[float, Field(default=1.0, gt=0.0, description="Positive multiplier")],
) -> str:
final_score = score * factor
return f"{name} scored {final_score}"
fs = function_schema(func_with_annotated_multiple_field_constraints, use_docstring_info=False)
# Check schema structure
properties = fs.params_json_schema.get("properties", {})
# Check score field
score_schema = properties.get("score", {})
assert score_schema.get("type") == "integer"
assert score_schema.get("minimum") == 0
assert score_schema.get("maximum") == 100
assert score_schema.get("description") == "Score from 0 to 100"
# Check name field
name_schema = properties.get("name", {})
assert name_schema.get("type") == "string"
assert name_schema.get("minLength") == 1
assert name_schema.get("maxLength") == 50
assert name_schema.get("default") == "Unknown"
# Check factor field
factor_schema = properties.get("factor", {})
assert factor_schema.get("type") == "number"
assert factor_schema.get("exclusiveMinimum") == 0.0
assert factor_schema.get("default") == 1.0
assert factor_schema.get("description") == "Positive multiplier"
# Valid input with defaults
valid_input = {"score": 85}
parsed = fs.params_pydantic_model(**valid_input)
args, kwargs_dict = fs.to_call_args(parsed)
result = func_with_annotated_multiple_field_constraints(*args, **kwargs_dict)
assert result == "Unknown scored 85.0"
# Valid input with all parameters
valid_input2 = {"score": 90, "name": "Alice", "factor": 1.5}
parsed2 = fs.params_pydantic_model(**valid_input2)
args2, kwargs_dict2 = fs.to_call_args(parsed2)
result2 = func_with_annotated_multiple_field_constraints(*args2, **kwargs_dict2)
assert result2 == "Alice scored 135.0"
# Test various validation errors
with pytest.raises(ValidationError): # score too high
fs.params_pydantic_model(**{"score": 150})
with pytest.raises(ValidationError): # empty name
fs.params_pydantic_model(**{"score": 50, "name": ""})
with pytest.raises(ValidationError): # zero factor
fs.params_pydantic_model(**{"score": 50, "factor": 0.0})
def test_bound_method_self_not_in_schema():
"""Test that bound methods work normally (Python already strips self)."""
class MyTools:
def greet(self, name: str) -> str:
return f"Hello, {name}"
obj = MyTools()
fs = function_schema(obj.greet, use_docstring_info=False)
props = fs.params_json_schema.get("properties", {})
assert "self" not in props
assert "name" in props
assert fs.params_json_schema.get("required") == ["name"]
def test_unbound_cls_param_skipped():
"""Test that unbound classmethods with unannotated cls have cls skipped."""
# Simulate a function whose first param is named cls with no annotation
code = compile("def greet(cls, name: str) -> str: ...", "<test>", "exec")
ns: dict[str, Any] = {}
exec(code, ns) # noqa: S102
fn = ns["greet"]
fn.__annotations__ = {"name": str, "return": str}
fs = function_schema(fn, use_docstring_info=False)
props = fs.params_json_schema.get("properties", {})
assert "cls" not in props
assert "name" in props
assert fs.self_or_cls_skipped is True
assert "cls" not in fs.signature.parameters
def test_bound_method_with_context_second_param():
"""Test that bound methods with RunContextWrapper as second param work correctly."""
class MyTools:
def greet(self, ctx: RunContextWrapper[None], name: str) -> str:
return f"Hello, {name}"
obj = MyTools()
fs = function_schema(obj.greet, use_docstring_info=False)
props = fs.params_json_schema.get("properties", {})
# self is already stripped by Python for bound methods
assert "self" not in props
assert "ctx" not in props
assert "name" in props
assert fs.takes_context is True
def test_method_context_not_immediately_after_self_raises():
"""Test that RunContextWrapper at position 3+ (not immediately after self) raises UserError."""
class MyTools:
def greet(self, name: str, ctx: RunContextWrapper[None]) -> str:
return f"Hello, {name}"
obj = MyTools()
with pytest.raises(UserError, match="non-first position"):
function_schema(obj.greet, use_docstring_info=False)
def test_unbound_method_self_skipped_with_context():
"""Test that unbound methods with self+context have self skipped and context recognized."""
# Simulate an unbound method with self as first param
code = compile(
"def greet(self, ctx, name: str) -> str: ...", "<test>", "exec"
)
ns: dict[str, Any] = {}
exec(code, ns) # noqa: S102
fn = ns["greet"]
fn.__annotations__ = {"ctx": RunContextWrapper[None], "name": str, "return": str}
fs = function_schema(fn, use_docstring_info=False)
props = fs.params_json_schema.get("properties", {})
assert "self" not in props
assert "ctx" not in props
assert "name" in props
assert fs.self_or_cls_skipped is True
assert fs.takes_context is True
assert "self" not in fs.signature.parameters
def test_unbound_method_to_call_args_alignment():
"""Test that to_call_args produces correct args when self was skipped."""
code = compile("def greet(self, name: str, count: int = 1) -> str: ...", "<test>", "exec")
ns: dict[str, Any] = {}
exec(code, ns) # noqa: S102
fn = ns["greet"]
fn.__annotations__ = {"name": str, "count": int, "return": str}
fs = function_schema(fn, use_docstring_info=False)
assert fs.self_or_cls_skipped is True
parsed = fs.params_pydantic_model(name="world", count=3)
args, kwargs = fs.to_call_args(parsed)
assert args == ["world", 3]
assert kwargs == {}
def test_decorator_pattern_does_not_raise():
"""Test that function_schema works on unbound methods (decorator pattern)."""
# This simulates @function_tool applied at class definition time
class MyTools:
def search(self, query: str) -> str:
return query
# At decoration time, MyTools.search is unbound