Debian Codegraph @

tests/lib/tools/test_functions.py

raw
1 from __future__ import annotations
2
3 from typing import Any, cast
4 from contextlib import contextmanager, asynccontextmanager
5 from collections.abc import Callable, Iterator, Awaitable, AsyncIterator
6
7 import pytest
8 from pydantic import BaseModel
9
10 from anthropic import beta_tool
11 from anthropic._compat import PYDANTIC_V1
12 from anthropic.lib.tools._beta_functions import BaseFunctionTool
13 from anthropic.types.beta.beta_tool_param import InputSchema
14
15
16 @pytest.mark.skipif(PYDANTIC_V1, reason="only applicable in pydantic v2")
17 class TestFunctionTool:
18 def test_basic_function_schema_conversion(self) -> None:
19 """Test basic function schema conversion with simple types."""
20
21 def get_weather(location: str, unit: str = "celsius") -> str:
22 """Get the weather for a specific location."""
23 return f"Weather in {location} is 20 degrees {unit}"
24
25 function_tool = beta_tool(get_weather)
26
27 assert function_tool.name == "get_weather"
28 assert function_tool.description == "Get the weather for a specific location."
29 assert function_tool.input_schema == {
30 "additionalProperties": False,
31 "type": "object",
32 "properties": {
33 "location": {"title": "Location", "type": "string"},
34 "unit": {"title": "Unit", "type": "string", "default": "celsius"},
35 },
36 "required": ["location"],
37 }
38 assert function_tool(location="CA") == "Weather in CA is 20 degrees celsius"
39
40 # invalid types should be allowed because __call__ should just be the original function
41 assert function_tool(location=cast(Any, 1)) == "Weather in 1 is 20 degrees celsius"
42
43 def test_function_with_multiple_types(self) -> None:
44 """Test function schema conversion with various Python types."""
45
46 def simple_function(
47 name: str,
48 age: int,
49 ) -> str:
50 """A simple function with basic parameter types."""
51 return f"Person: {name}, {age} years old"
52
53 function_tool = beta_tool(simple_function)
54
55 assert function_tool.name == "simple_function"
56 assert function_tool.description == "A simple function with basic parameter types."
57
58 result = function_tool.call(
59 {
60 "name": "John",
61 "age": 25,
62 }
63 )
64 assert result == "Person: John, 25 years old"
65
66 expected_schema = {
67 "additionalProperties": False,
68 "type": "object",
69 "properties": {
70 "name": {"title": "Name", "type": "string"},
71 "age": {"title": "Age", "type": "integer"},
72 },
73 "required": ["name", "age"],
74 }
75
76 assert function_tool.input_schema == expected_schema
77
78 def test_function_call_with_valid_input(self) -> None:
79 def add_numbers(a: int, b: int) -> str:
80 """Add two numbers together."""
81 return str(a + b)
82
83 function_tool = beta_tool(add_numbers)
84 result = function_tool.call({"a": 5, "b": 3})
85
86 assert result == "8"
87
88 @pytest.mark.parametrize(
89 "input_data, expected_error_type, expected_error_msg",
90 [
91 pytest.param(
92 {"a": "not a number", "b": 3},
93 ValueError,
94 "Invalid arguments for function add_numbers",
95 id="invalid_argument_type",
96 ),
97 pytest.param(
98 {"b": 3},
99 ValueError,
100 "Invalid arguments for function add_numbers",
101 id="missing_required_argument",
102 ),
103 pytest.param(
104 None,
105 TypeError,
106 "Input must be a dictionary, got NoneType",
107 id="invalid_input_object",
108 ),
109 ],
110 )
111 def test_function_call_with_invalid_input(
112 self, input_data: dict[str, Any], expected_error_type: type[BaseException], expected_error_msg: str
113 ) -> None:
114 def add_numbers(a: int, b: int) -> str:
115 return str(a + b)
116
117 function_tool = beta_tool(add_numbers)
118
119 with pytest.raises(expected_error_type, match=expected_error_msg):
120 function_tool.call(input_data)
121
122 def test_custom_name_and_description(self) -> None:
123 def some_function(x: int) -> str:
124 """Original description."""
125 return str(x * 2)
126
127 function_tool = beta_tool(some_function, name="custom_name", description="Custom description")
128
129 assert function_tool.name == "custom_name"
130 assert function_tool.description == "Custom description"
131
132 def test_custom_input_schema_with_dict(self) -> None:
133 def some_function(x: int) -> str:
134 return str(x * 2)
135
136 custom_schema: InputSchema = {
137 "additionalProperties": False,
138 "type": "object",
139 "properties": {"x": {"type": "number", "description": "A number to double"}},
140 "required": ["x"],
141 }
142
143 function_tool = beta_tool(some_function, input_schema=custom_schema)
144
145 assert function_tool.input_schema == custom_schema
146
147 def test_custom_input_schema_with_pydantic_model(self) -> None:
148 class WeatherInput(BaseModel):
149 location: str
150 unit: str = "celsius"
151
152 def get_weather(location: str, unit: str = "celsius") -> str: # noqa: ARG001
153 return f"Weather in {location}"
154
155 # Pass the Pydantic model class directly as input_schema
156 function_tool = beta_tool(get_weather, input_schema=WeatherInput)
157
158 # Pydantic model schemas include additional metadata
159 schema = function_tool.input_schema
160
161 assert schema == {
162 "title": "WeatherInput",
163 "type": "object",
164 "properties": {
165 "location": {"title": "Location", "type": "string"},
166 "unit": {"title": "Unit", "type": "string", "default": "celsius"},
167 },
168 "required": ["location"],
169 }
170
171 def test_to_dict_method(self) -> None:
172 def simple_func(message: str) -> str:
173 """A simple function."""
174 return message
175
176 function_tool = beta_tool(simple_func)
177 tool_param = function_tool.to_dict()
178
179 assert tool_param == {
180 "name": "simple_func",
181 "description": "A simple function.",
182 "input_schema": {
183 "additionalProperties": False,
184 "type": "object",
185 "properties": {"message": {"title": "Message", "type": "string"}},
186 "required": ["message"],
187 },
188 }
189
190 def test_function_without_docstring(self) -> None:
191 def no_docs(x: int) -> str: # noqa: ARG001
192 return ""
193
194 function_tool = beta_tool(no_docs)
195
196 assert function_tool.description == ""
197
198 def test_function_without_type_hints(self) -> None:
199 def no_types(x, y=10): # pyright: ignore[reportUnknownParameterType, reportMissingParameterType]
200 return x + y # pyright: ignore[reportUnknownVariableType]
201
202 function_tool = beta_tool(no_types) # type: ignore
203
204 # Should still create a schema, though less precise (uses Any type)
205 assert function_tool.input_schema == {
206 "additionalProperties": False,
207 "type": "object",
208 "properties": {
209 "x": {"title": "X"}, # Any type gets title but no type
210 "y": {"title": "Y", "default": 10},
211 },
212 "required": ["x"],
213 }
214
215 @pytest.mark.parametrize(
216 "docstring",
217 [
218 pytest.param(
219 (
220 """Get detailed weather information for a location.
221
222 This function retrieves current weather conditions and optionally
223 includes a forecast for the specified location.
224
225 Args:
226 location: The city or location to get weather for.
227 unit: Temperature unit, either 'celsius' or 'fahrenheit'.
228 include_forecast: Whether to include forecast data.
229
230 Returns:
231 Weather information as a formatted string
232
233 Examples:
234 >>> get_weather_detailed("London")
235 "London: 15°C, partly cloudy"
236
237 >>> get_weather_detailed("New York", "fahrenheit", True)
238 "New York: 59°F, sunny. Tomorrow: 62°F, cloudy"
239 """
240 ),
241 id="google_style_docstring",
242 ),
243 pytest.param(
244 (
245 """Get detailed weather information for a location.
246
247 This function retrieves current weather conditions and optionally
248 includes a forecast for the specified location.
249
250 :param location: The city or location to get weather for.
251 :type location: str
252 :param unit: Temperature unit, either 'celsius' or 'fahrenheit'.
253 :type unit: str
254 :param include_forecast: Whether to include forecast data.
255 :type include_forecast: bool
256
257 :returns: Weather information as a formatted string.
258 :rtype: str
259
260 :example:
261 >>> get_weather_detailed("London")
262 "London: 15°C, partly cloudy"
263
264 >>> get_weather_detailed("New York", "fahrenheit", True)
265 "New York: 59°F, sunny. Tomorrow: 62°F, cloudy
266 """
267 ),
268 id="rest_style_docstring",
269 ),
270 pytest.param(
271 (
272 """Get detailed weather information for a location.
273
274 This function retrieves current weather conditions and optionally
275 includes a forecast for the specified location.
276
277 Parameters
278 ----------
279 location : str
280 The city or location to get weather for.
281 unit : str
282 Temperature unit, either 'celsius' or 'fahrenheit'.
283 include_forecast : bool
284 Whether to include forecast data.
285
286 Returns
287 -------
288 str
289 Weather information as a formatted string.
290
291 Examples
292 --------
293 >>> get_weather_detailed("London")
294 "London: 15°C, partly cloudy"
295
296 >>> get_weather_detailed("New York", "fahrenheit", True)
297 "New York: 59°F, sunny. Tomorrow: 62°F, cloudy"
298 """
299 ),
300 id="numpy_style_docstring",
301 ),
302 pytest.param(
303 (
304 """Get detailed weather information for a location.
305
306 This function retrieves current weather conditions and optionally
307 includes a forecast for the specified location.
308
309 @param location: The city or location to get weather for.
310 @type location: str
311 @param unit: Temperature unit, either 'celsius' or 'fahrenheit'.
312 @type unit: str
313 @param include_forecast: Whether to include forecast data.
314 @type include_forecast: bool
315
316 @return: Weather information as a formatted string.
317 @rtype: str
318
319 @example:
320 >>> get_weather_detailed("London")
321 "London: 15°C, partly cloudy"
322
323 >>> get_weather_detailed("New York", "fahrenheit", True)
324 "New York: 59°F, sunny. Tomorrow: 62°F, cloudy"
325 """
326 ),
327 id="epydoc_style_docstring",
328 ),
329 ],
330 )
331 def test_docstring_parsing_with_parameters(self, docstring: str) -> None:
332 def get_weather_detailed(location: str, unit: str = "celsius", include_forecast: bool = False) -> str: # noqa: ARG001
333 return f"Weather for {location}"
334
335 get_weather_detailed.__doc__ = docstring
336
337 function_tool = beta_tool(get_weather_detailed)
338
339 expected_description = (
340 "Get detailed weather information for a location.\n\n"
341 "This function retrieves current weather conditions and optionally\n"
342 "includes a forecast for the specified location."
343 )
344 expected_schema = {
345 "additionalProperties": False,
346 "type": "object",
347 "properties": {
348 "location": {
349 "title": "Location",
350 "type": "string",
351 "description": "The city or location to get weather for.",
352 },
353 "unit": {
354 "title": "Unit",
355 "type": "string",
356 "default": "celsius",
357 "description": "Temperature unit, either 'celsius' or 'fahrenheit'.",
358 },
359 "include_forecast": {
360 "title": "Include Forecast",
361 "type": "boolean",
362 "default": False,
363 "description": "Whether to include forecast data.",
364 },
365 },
366 "required": ["location"],
367 }
368 assert function_tool.description == expected_description
369 assert function_tool.input_schema == expected_schema
370
371 def test_decorator_without_parentheses(self) -> None:
372 """Test using @function_tool decorator without parentheses."""
373
374 @beta_tool
375 def multiply(x: int, y: int) -> str:
376 """Multiply two numbers."""
377 return str(x * y)
378
379 assert multiply.name == "multiply"
380 assert multiply.description == "Multiply two numbers."
381 assert multiply.call({"x": 3, "y": 4}) == "12"
382
383 expected_schema = {
384 "additionalProperties": False,
385 "type": "object",
386 "properties": {
387 "x": {"title": "X", "type": "integer"},
388 "y": {"title": "Y", "type": "integer"},
389 },
390 "required": ["x", "y"],
391 }
392 assert multiply.input_schema == expected_schema
393
394 def test_decorator_with_parentheses(self) -> None:
395 """Test using @function_tool() decorator with parentheses."""
396
397 @beta_tool()
398 def divide(a: float, b: float) -> str:
399 """Divide two numbers."""
400 return str(a / b)
401
402 assert divide.name == "divide"
403 assert divide.description == "Divide two numbers."
404 assert divide.call({"a": 10.0, "b": 2.0}) == "5.0"
405
406 def test_decorator_with_custom_parameters(self) -> None:
407 """Test using @function_tool() decorator with custom name and description."""
408
409 @beta_tool(name="custom_calculator", description="A custom calculator function")
410 def calculate(value: int) -> str:
411 """Original description that should be overridden."""
412 return str(value * 2)
413
414 assert calculate.name == "custom_calculator"
415 assert calculate.description == "A custom calculator function"
416 assert calculate.call({"value": 5}) == "10"
417
418 def test_docstring_parsing_simple(self) -> None:
419 """Test that simple docstrings still work correctly."""
420
421 def simple_add(a: int, b: int) -> str:
422 """Add two numbers together."""
423 return str(a + b)
424
425 function_tool = beta_tool(simple_add)
426
427 assert function_tool.description == "Add two numbers together."
428 assert _get_parameters_info(function_tool) == {}
429
430 # Schema should not have descriptions for parameters
431 expected_schema = {
432 "additionalProperties": False,
433 "type": "object",
434 "properties": {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "integer"}},
435 "required": ["a", "b"],
436 }
437
438 assert function_tool.input_schema == expected_schema
439
440
441 def _get_parameters_info(fn: BaseFunctionTool[Any]) -> dict[str, str]:
442 param_info: dict[str, str] = {}
443 for param in fn._parsed_docstring.params:
444 if param.description:
445 param_info[param.arg_name] = param.description.strip()
446 return param_info
447
448
449 @pytest.mark.skipif(PYDANTIC_V1, reason="tool functions need pydantic v2")
450 class TestContextManagerTool:
451 """`@beta_tool` / `@beta_async_tool` over an (async) context manager that
452 yields the tool callable: the decorator enters it to obtain the callable and
453 drives its `__exit__` / `__aexit__` on the cleanup path.
454
455 The `cast(Any, ...)` call form mirrors how the SDK's own `beta_bash_tool`
456 adopts this; bare decorator syntax works the same at runtime.
457 """
458
459 def test_sync_context_manager_tool(self) -> None:
460 import anyio
461
462 from anthropic.lib.tools._beta_functions import aclose_runnable_tool
463
464 seen: list[str] = []
465
466 @contextmanager
467 def adder_cm() -> Iterator[Callable[[int, int], str]]:
468 seen.append("enter")
469
470 def add(a: int, b: int) -> str:
471 """Add two numbers."""
472 return str(a + b)
473
474 try:
475 yield add
476 finally:
477 seen.append("exit")
478
479 adder = beta_tool(cast(Any, adder_cm))
480
481 # Entered eagerly; schema/description inferred from the yielded callable.
482 assert seen == ["enter"]
483 assert adder.name == "add"
484 assert adder.description == "Add two numbers."
485 assert adder.input_schema == {
486 "additionalProperties": False,
487 "type": "object",
488 "properties": {"a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "integer"}},
489 "required": ["a", "b"],
490 }
491 assert adder.call({"a": 2, "b": 3}) == "5"
492
493 anyio.run(aclose_runnable_tool, adder)
494 assert seen == ["enter", "exit"]
495
496 async def test_async_context_manager_tool_lazy_enter_and_cleanup(self) -> None:
497 from anthropic.lib.tools._beta_functions import beta_async_tool, aclose_runnable_tool
498
499 seen: list[str] = []
500 schema: InputSchema = {
501 "type": "object",
502 "properties": {"value": {"type": "string"}},
503 "required": ["value"],
504 }
505
506 @asynccontextmanager
507 async def echo_cm() -> AsyncIterator[Callable[[str], Awaitable[str]]]:
508 """Echo the value."""
509 seen.append("enter")
510
511 async def echo(value: str) -> str:
512 return f"echo:{value}"
513
514 try:
515 yield echo
516 finally:
517 seen.append("exit")
518
519 echo_tool = beta_async_tool(name="echo", input_schema=schema)(cast(Any, echo_cm))
520
521 # Name/description/schema are available without entering (the runner
522 # reads them before any tool call).
523 assert echo_tool.name == "echo"
524 assert echo_tool.description == "Echo the value."
525 assert echo_tool.to_dict()["input_schema"] == schema
526 assert seen == []
527
528 assert await echo_tool.call({"value": "hi"}) == "echo:hi"
529 assert seen == ["enter"]
530
531 await aclose_runnable_tool(echo_tool)
532 assert seen == ["enter", "exit"]
533
534 def test_wrong_decorator_raises(self) -> None:
535 from anthropic.lib.tools._beta_functions import beta_async_tool
536
537 @asynccontextmanager
538 async def an_async_cm() -> AsyncIterator[Callable[[], str]]:
539 yield lambda: "x"
540
541 @contextmanager
542 def a_sync_cm() -> Iterator[Callable[[], str]]:
543 yield lambda: "x"
544
545 with pytest.raises(TypeError, match="use @beta_async_tool"):
546 beta_tool(cast(Any, an_async_cm))
547
548 with pytest.raises(TypeError, match="use @beta_tool"):
549 beta_async_tool(name="bad2")(cast(Any, a_sync_cm))
550
551 def test_async_context_manager_requires_input_schema(self) -> None:
552 from anthropic.lib.tools._beta_functions import beta_async_tool
553
554 @asynccontextmanager
555 async def noschema_cm() -> AsyncIterator[Callable[[int], Awaitable[str]]]:
556 async def fn(x: int) -> str:
557 return str(x)
558
559 yield fn
560
561 with pytest.raises(TypeError, match="needs an explicit input_schema"):
562 beta_async_tool(name="noschema")(cast(Any, noschema_cm))