You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_tools.py 22 kB

Fix: Auto-Convert Pydantic and Dataclass Arguments in AutoGen Tool Calls (#5737) AutoGen was passing raw dictionaries to functions instead of constructing Pydantic model or dataclass instances. If a tool function’s parameter was a Pydantic BaseModel or a dataclass, the function would receive a dict and likely throw an error or behave incorrectly (since it expected an object of that type). This PR addresses problem in AutoGen where tool functions expecting structured inputs (Pydantic models or dataclasses) were receiving raw dictionaries. It ensures that structured inputs are automatically validated and instantiated before function calls. Complete details are in Issue #5736 [Reproducible Example Code - Failing Case](https://colab.research.google.com/drive/1hgoP-cGdSZ1-OqQLpwYmlmcExgftDqlO?usp=sharing) <!-- Please give a short summary of the change and the problem this solves. --> ## Changes Made: - Inspect function signatures for Pydantic BaseModel and dataclass annotations. - Convert input dictionaries into properly instantiated objects using BaseModel.model_validate() for Pydantic models or standard instantiation for dataclasses. - Raise descriptive errors when validation or instantiation fails. - Unit tests have been added to cover all scenarios Now structured inputs are automatically validated and instantiated before function calls. - **Updated Conversion Logic:** In the `run()` method, we now inspect the function’s signature and convert input dictionaries to structured objects. For parameters annotated with a Pydantic model, we use `model_validate()` to create an instance; for those annotated with a dataclass, we instantiate the object using the dataclass constructor. For example: ```python # Get the function signature. sig = inspect.signature(self._func) raw_kwargs = args.model_dump() kwargs = {} # Iterate over the parameters expected by the function. for name, param in sig.parameters.items(): if name in raw_kwargs: expected_type = param.annotation value = raw_kwargs[name] # If expected type is a subclass of BaseModel, perform conversion. if inspect.isclass(expected_type) and issubclass(expected_type, BaseModel): try: kwargs[name] = expected_type.model_validate(value) except ValidationError as e: raise ValueError( f"Error validating parameter '{name}' for function '{self._func.__name__}': {e}" ) from e # If it's a dataclass, instantiate it. elif is_dataclass(expected_type): try: cls = expected_type if isinstance(expected_type, type) else type(expected_type) kwargs[name] = cls(**value) except Exception as e: raise ValueError( f"Error instantiating dataclass parameter '{name}' for function '{self._func.__name__}': {e}" ) from e else: kwargs[name] = value ``` - **Error Handling Improvements:** Conversion steps are wrapped in try/except blocks to raise descriptive errors when instantiation fails, aiding in debugging invalid inputs. - **Testing:** Unit tests have been added to simulate tool calls (e.g., an `add` tool) to ensure that with input like: ```json {"input": {"x": 2, "y": 3}} ``` The tool function receives an instance of the expected type and returns the correct result. ## Related issue number Closes #5736 ## Checks - [x] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [x] I've made sure all auto checks have passed.
1 year ago
Fix: Auto-Convert Pydantic and Dataclass Arguments in AutoGen Tool Calls (#5737) AutoGen was passing raw dictionaries to functions instead of constructing Pydantic model or dataclass instances. If a tool function’s parameter was a Pydantic BaseModel or a dataclass, the function would receive a dict and likely throw an error or behave incorrectly (since it expected an object of that type). This PR addresses problem in AutoGen where tool functions expecting structured inputs (Pydantic models or dataclasses) were receiving raw dictionaries. It ensures that structured inputs are automatically validated and instantiated before function calls. Complete details are in Issue #5736 [Reproducible Example Code - Failing Case](https://colab.research.google.com/drive/1hgoP-cGdSZ1-OqQLpwYmlmcExgftDqlO?usp=sharing) <!-- Please give a short summary of the change and the problem this solves. --> ## Changes Made: - Inspect function signatures for Pydantic BaseModel and dataclass annotations. - Convert input dictionaries into properly instantiated objects using BaseModel.model_validate() for Pydantic models or standard instantiation for dataclasses. - Raise descriptive errors when validation or instantiation fails. - Unit tests have been added to cover all scenarios Now structured inputs are automatically validated and instantiated before function calls. - **Updated Conversion Logic:** In the `run()` method, we now inspect the function’s signature and convert input dictionaries to structured objects. For parameters annotated with a Pydantic model, we use `model_validate()` to create an instance; for those annotated with a dataclass, we instantiate the object using the dataclass constructor. For example: ```python # Get the function signature. sig = inspect.signature(self._func) raw_kwargs = args.model_dump() kwargs = {} # Iterate over the parameters expected by the function. for name, param in sig.parameters.items(): if name in raw_kwargs: expected_type = param.annotation value = raw_kwargs[name] # If expected type is a subclass of BaseModel, perform conversion. if inspect.isclass(expected_type) and issubclass(expected_type, BaseModel): try: kwargs[name] = expected_type.model_validate(value) except ValidationError as e: raise ValueError( f"Error validating parameter '{name}' for function '{self._func.__name__}': {e}" ) from e # If it's a dataclass, instantiate it. elif is_dataclass(expected_type): try: cls = expected_type if isinstance(expected_type, type) else type(expected_type) kwargs[name] = cls(**value) except Exception as e: raise ValueError( f"Error instantiating dataclass parameter '{name}' for function '{self._func.__name__}': {e}" ) from e else: kwargs[name] = value ``` - **Error Handling Improvements:** Conversion steps are wrapped in try/except blocks to raise descriptive errors when instantiation fails, aiding in debugging invalid inputs. - **Testing:** Unit tests have been added to simulate tool calls (e.g., an `add` tool) to ensure that with input like: ```json {"input": {"x": 2, "y": 3}} ``` The tool function receives an instance of the expected type and returns the correct result. ## Related issue number Closes #5736 ## Checks - [x] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [x] I've made sure all auto checks have passed.
1 year ago
Fix: Auto-Convert Pydantic and Dataclass Arguments in AutoGen Tool Calls (#5737) AutoGen was passing raw dictionaries to functions instead of constructing Pydantic model or dataclass instances. If a tool function’s parameter was a Pydantic BaseModel or a dataclass, the function would receive a dict and likely throw an error or behave incorrectly (since it expected an object of that type). This PR addresses problem in AutoGen where tool functions expecting structured inputs (Pydantic models or dataclasses) were receiving raw dictionaries. It ensures that structured inputs are automatically validated and instantiated before function calls. Complete details are in Issue #5736 [Reproducible Example Code - Failing Case](https://colab.research.google.com/drive/1hgoP-cGdSZ1-OqQLpwYmlmcExgftDqlO?usp=sharing) <!-- Please give a short summary of the change and the problem this solves. --> ## Changes Made: - Inspect function signatures for Pydantic BaseModel and dataclass annotations. - Convert input dictionaries into properly instantiated objects using BaseModel.model_validate() for Pydantic models or standard instantiation for dataclasses. - Raise descriptive errors when validation or instantiation fails. - Unit tests have been added to cover all scenarios Now structured inputs are automatically validated and instantiated before function calls. - **Updated Conversion Logic:** In the `run()` method, we now inspect the function’s signature and convert input dictionaries to structured objects. For parameters annotated with a Pydantic model, we use `model_validate()` to create an instance; for those annotated with a dataclass, we instantiate the object using the dataclass constructor. For example: ```python # Get the function signature. sig = inspect.signature(self._func) raw_kwargs = args.model_dump() kwargs = {} # Iterate over the parameters expected by the function. for name, param in sig.parameters.items(): if name in raw_kwargs: expected_type = param.annotation value = raw_kwargs[name] # If expected type is a subclass of BaseModel, perform conversion. if inspect.isclass(expected_type) and issubclass(expected_type, BaseModel): try: kwargs[name] = expected_type.model_validate(value) except ValidationError as e: raise ValueError( f"Error validating parameter '{name}' for function '{self._func.__name__}': {e}" ) from e # If it's a dataclass, instantiate it. elif is_dataclass(expected_type): try: cls = expected_type if isinstance(expected_type, type) else type(expected_type) kwargs[name] = cls(**value) except Exception as e: raise ValueError( f"Error instantiating dataclass parameter '{name}' for function '{self._func.__name__}': {e}" ) from e else: kwargs[name] = value ``` - **Error Handling Improvements:** Conversion steps are wrapped in try/except blocks to raise descriptive errors when instantiation fails, aiding in debugging invalid inputs. - **Testing:** Unit tests have been added to simulate tool calls (e.g., an `add` tool) to ensure that with input like: ```json {"input": {"x": 2, "y": 3}} ``` The tool function receives an instance of the expected type and returns the correct result. ## Related issue number Closes #5736 ## Checks - [x] I've included any doc changes needed for <https://microsoft.github.io/autogen/>. See <https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to build and test documentation locally. - [x] I've added tests (if relevant) corresponding to the changes introduced in this PR. - [x] I've made sure all auto checks have passed.
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. import inspect
  2. from dataclasses import dataclass
  3. from functools import partial
  4. from typing import Annotated, List
  5. import pytest
  6. from autogen_core import CancellationToken
  7. from autogen_core._function_utils import get_typed_signature
  8. from autogen_core.tools import BaseTool, FunctionTool
  9. from autogen_core.tools._base import ToolSchema
  10. from pydantic import BaseModel, Field, ValidationError, model_serializer
  11. from pydantic_core import PydanticUndefined
  12. class MyArgs(BaseModel):
  13. query: str = Field(description="The description.")
  14. class MyNestedArgs(BaseModel):
  15. arg: MyArgs = Field(description="The nested description.")
  16. class MyResult(BaseModel):
  17. result: str = Field(description="The other description.")
  18. class MyTool(BaseTool[MyArgs, MyResult]):
  19. def __init__(self) -> None:
  20. super().__init__(
  21. args_type=MyArgs,
  22. return_type=MyResult,
  23. name="TestTool",
  24. description="Description of test tool.",
  25. )
  26. self.called_count = 0
  27. async def run(self, args: MyArgs, cancellation_token: CancellationToken) -> MyResult:
  28. self.called_count += 1
  29. return MyResult(result="value")
  30. class MyNestedTool(BaseTool[MyNestedArgs, MyResult]):
  31. def __init__(self) -> None:
  32. super().__init__(
  33. args_type=MyNestedArgs,
  34. return_type=MyResult,
  35. name="TestNestedTool",
  36. description="Description of test nested tool.",
  37. )
  38. self.called_count = 0
  39. async def run(self, args: MyNestedArgs, cancellation_token: CancellationToken) -> MyResult:
  40. self.called_count += 1
  41. return MyResult(result="value")
  42. def test_tool_schema_generation() -> None:
  43. schema = MyTool().schema
  44. assert schema["name"] == "TestTool"
  45. assert "description" in schema
  46. assert schema["description"] == "Description of test tool."
  47. assert "parameters" in schema
  48. assert schema["parameters"]["type"] == "object"
  49. assert "properties" in schema["parameters"]
  50. assert schema["parameters"]["properties"]["query"]["description"] == "The description."
  51. assert schema["parameters"]["properties"]["query"]["type"] == "string"
  52. assert "required" in schema["parameters"]
  53. assert schema["parameters"]["required"] == ["query"]
  54. assert len(schema["parameters"]["properties"]) == 1
  55. def test_func_tool_schema_generation() -> None:
  56. def my_function(arg: str, other: Annotated[int, "int arg"], nonrequired: int = 5) -> MyResult:
  57. return MyResult(result="test")
  58. tool = FunctionTool(my_function, description="Function tool.")
  59. schema = tool.schema
  60. assert schema["name"] == "my_function"
  61. assert "description" in schema
  62. assert schema["description"] == "Function tool."
  63. assert "parameters" in schema
  64. assert schema["parameters"]["type"] == "object"
  65. assert schema["parameters"]["properties"].keys() == {"arg", "other", "nonrequired"}
  66. assert schema["parameters"]["properties"]["arg"]["type"] == "string"
  67. assert schema["parameters"]["properties"]["arg"]["description"] == "arg"
  68. assert schema["parameters"]["properties"]["other"]["type"] == "integer"
  69. assert schema["parameters"]["properties"]["other"]["description"] == "int arg"
  70. assert schema["parameters"]["properties"]["nonrequired"]["type"] == "integer"
  71. assert schema["parameters"]["properties"]["nonrequired"]["description"] == "nonrequired"
  72. assert "required" in schema["parameters"]
  73. assert schema["parameters"]["required"] == ["arg", "other"]
  74. assert len(schema["parameters"]["properties"]) == 3
  75. def test_func_tool_schema_generation_strict() -> None:
  76. def my_function1(arg: str, other: Annotated[int, "int arg"], nonrequired: int = 5) -> MyResult:
  77. return MyResult(result="test")
  78. with pytest.raises(ValueError, match="Strict mode is enabled"):
  79. tool = FunctionTool(my_function1, description="Function tool.", strict=True)
  80. schema = tool.schema
  81. def my_function2(arg: str, other: Annotated[int, "int arg"]) -> MyResult:
  82. return MyResult(result="test")
  83. tool = FunctionTool(my_function2, description="Function tool.", strict=True)
  84. schema = tool.schema
  85. assert schema["name"] == "my_function2"
  86. assert "description" in schema
  87. assert schema["description"] == "Function tool."
  88. assert "parameters" in schema
  89. assert schema["parameters"]["type"] == "object"
  90. assert schema["parameters"]["properties"].keys() == {"arg", "other"}
  91. assert schema["parameters"]["properties"]["arg"]["type"] == "string"
  92. assert schema["parameters"]["properties"]["arg"]["description"] == "arg"
  93. assert schema["parameters"]["properties"]["other"]["type"] == "integer"
  94. assert schema["parameters"]["properties"]["other"]["description"] == "int arg"
  95. assert "required" in schema["parameters"]
  96. assert schema["parameters"]["required"] == ["arg", "other"]
  97. assert len(schema["parameters"]["properties"]) == 2
  98. assert "additionalProperties" in schema["parameters"]
  99. assert schema["parameters"]["additionalProperties"] is False
  100. def test_func_tool_schema_generation_only_default_arg() -> None:
  101. def my_function(arg: str = "default") -> MyResult:
  102. return MyResult(result="test")
  103. tool = FunctionTool(my_function, description="Function tool.")
  104. schema = tool.schema
  105. assert schema["name"] == "my_function"
  106. assert "description" in schema
  107. assert schema["description"] == "Function tool."
  108. assert "parameters" in schema
  109. assert len(schema["parameters"]["properties"]) == 1
  110. assert schema["parameters"]["properties"]["arg"]["type"] == "string"
  111. assert schema["parameters"]["properties"]["arg"]["description"] == "arg"
  112. assert "required" in schema["parameters"]
  113. assert schema["parameters"]["required"] == []
  114. def test_func_tool_schema_generation_only_default_arg_strict() -> None:
  115. def my_function(arg: str = "default") -> MyResult:
  116. return MyResult(result="test")
  117. with pytest.raises(ValueError, match="Strict mode is enabled"):
  118. tool = FunctionTool(my_function, description="Function tool.", strict=True)
  119. _ = tool.schema
  120. def test_func_tool_with_partial_positional_arguments_schema_generation() -> None:
  121. """Test correct schema generation for a partial function with positional arguments."""
  122. def get_weather(country: str, city: str) -> str:
  123. return f"The temperature in {city}, {country} is 75°"
  124. partial_function = partial(get_weather, "Germany")
  125. tool = FunctionTool(partial_function, description="Partial function tool.")
  126. schema = tool.schema
  127. assert schema["name"] == "get_weather"
  128. assert "description" in schema
  129. assert schema["description"] == "Partial function tool."
  130. assert "parameters" in schema
  131. assert schema["parameters"]["type"] == "object"
  132. assert schema["parameters"]["properties"].keys() == {"city"}
  133. assert schema["parameters"]["properties"]["city"]["type"] == "string"
  134. assert schema["parameters"]["properties"]["city"]["description"] == "city"
  135. assert "required" in schema["parameters"]
  136. assert schema["parameters"]["required"] == ["city"]
  137. assert "country" not in schema["parameters"]["properties"] # check country not in schema params
  138. assert len(schema["parameters"]["properties"]) == 1
  139. def test_func_call_tool_with_kwargs_schema_generation() -> None:
  140. """Test correct schema generation for a partial function with kwargs."""
  141. def get_weather(country: str, city: str) -> str:
  142. return f"The temperature in {city}, {country} is 75°"
  143. partial_function = partial(get_weather, country="Germany")
  144. tool = FunctionTool(partial_function, description="Partial function tool.")
  145. schema = tool.schema
  146. assert schema["name"] == "get_weather"
  147. assert "description" in schema
  148. assert schema["description"] == "Partial function tool."
  149. assert "parameters" in schema
  150. assert schema["parameters"]["type"] == "object"
  151. assert schema["parameters"]["properties"].keys() == {"country", "city"}
  152. assert schema["parameters"]["properties"]["city"]["type"] == "string"
  153. assert schema["parameters"]["properties"]["country"]["type"] == "string"
  154. assert "required" in schema["parameters"]
  155. assert schema["parameters"]["required"] == ["city"] # only city is required
  156. assert len(schema["parameters"]["properties"]) == 2
  157. @pytest.mark.asyncio
  158. async def test_run_func_call_tool_with_kwargs_and_args() -> None:
  159. """Test run partial function with kwargs and args."""
  160. def get_weather(country: str, city: str, unit: str = "Celsius") -> str:
  161. return f"The temperature in {city}, {country} is 75° {unit}"
  162. partial_function = partial(get_weather, "Germany", unit="Fahrenheit")
  163. tool = FunctionTool(partial_function, description="Partial function tool.")
  164. result = await tool.run_json({"city": "Berlin"}, CancellationToken())
  165. assert isinstance(result, str)
  166. assert result == "The temperature in Berlin, Germany is 75° Fahrenheit"
  167. @pytest.mark.asyncio
  168. async def test_tool_run() -> None:
  169. tool = MyTool()
  170. result = await tool.run_json({"query": "test"}, CancellationToken())
  171. assert isinstance(result, MyResult)
  172. assert result.result == "value"
  173. assert tool.called_count == 1
  174. result = await tool.run_json({"query": "test"}, CancellationToken())
  175. result = await tool.run_json({"query": "test"}, CancellationToken())
  176. assert tool.called_count == 3
  177. def test_tool_properties() -> None:
  178. tool = MyTool()
  179. assert tool.name == "TestTool"
  180. assert tool.description == "Description of test tool."
  181. assert tool.args_type() == MyArgs
  182. assert tool.return_type() == MyResult
  183. assert tool.state_type() is None
  184. def test_get_typed_signature() -> None:
  185. def my_function() -> str:
  186. return "result"
  187. sig = get_typed_signature(my_function)
  188. assert isinstance(sig, inspect.Signature)
  189. assert len(sig.parameters) == 0
  190. assert sig.return_annotation is str
  191. def test_get_typed_signature_annotated() -> None:
  192. def my_function() -> Annotated[str, "The return type"]:
  193. return "result"
  194. sig = get_typed_signature(my_function)
  195. assert isinstance(sig, inspect.Signature)
  196. assert len(sig.parameters) == 0
  197. assert sig.return_annotation == Annotated[str, "The return type"]
  198. def test_get_typed_signature_string() -> None:
  199. def my_function() -> "str":
  200. return "result"
  201. sig = get_typed_signature(my_function)
  202. assert isinstance(sig, inspect.Signature)
  203. assert len(sig.parameters) == 0
  204. assert sig.return_annotation is str
  205. def test_get_typed_signature_params() -> None:
  206. def my_function(arg: str) -> None:
  207. return None
  208. sig = get_typed_signature(my_function)
  209. assert isinstance(sig, inspect.Signature)
  210. assert sig.return_annotation is type(None)
  211. assert len(sig.parameters) == 1
  212. assert sig.parameters["arg"].annotation is str
  213. def test_get_typed_signature_two_params() -> None:
  214. def my_function(arg: str, arg2: int) -> None:
  215. return None
  216. sig = get_typed_signature(my_function)
  217. assert isinstance(sig, inspect.Signature)
  218. assert len(sig.parameters) == 2
  219. assert sig.parameters["arg"].annotation is str
  220. assert sig.parameters["arg2"].annotation is int
  221. def test_get_typed_signature_param_str() -> None:
  222. def my_function(arg: "str") -> None:
  223. return None
  224. sig = get_typed_signature(my_function)
  225. assert isinstance(sig, inspect.Signature)
  226. assert len(sig.parameters) == 1
  227. assert sig.parameters["arg"].annotation is str
  228. def test_get_typed_signature_param_annotated() -> None:
  229. def my_function(arg: Annotated[str, "An arg"]) -> None:
  230. return None
  231. sig = get_typed_signature(my_function)
  232. assert isinstance(sig, inspect.Signature)
  233. assert len(sig.parameters) == 1
  234. assert sig.parameters["arg"].annotation == Annotated[str, "An arg"]
  235. def test_func_tool() -> None:
  236. def my_function() -> str:
  237. return "result"
  238. tool = FunctionTool(my_function, description="Function tool.")
  239. assert tool.name == "my_function"
  240. assert tool.description == "Function tool."
  241. assert issubclass(tool.args_type(), BaseModel)
  242. assert issubclass(tool.return_type(), str)
  243. assert tool.state_type() is None
  244. def test_func_tool_annotated_arg() -> None:
  245. def my_function(my_arg: Annotated[str, "test description"]) -> str:
  246. return "result"
  247. tool = FunctionTool(my_function, description="Function tool.")
  248. assert tool.name == "my_function"
  249. assert tool.description == "Function tool."
  250. assert issubclass(tool.args_type(), BaseModel)
  251. assert issubclass(tool.return_type(), str)
  252. assert tool.args_type().model_fields["my_arg"].description == "test description"
  253. assert tool.args_type().model_fields["my_arg"].annotation is str
  254. assert tool.args_type().model_fields["my_arg"].is_required() is True
  255. assert tool.args_type().model_fields["my_arg"].default is PydanticUndefined
  256. assert len(tool.args_type().model_fields) == 1
  257. assert tool.return_type() is str
  258. assert tool.state_type() is None
  259. def test_func_tool_return_annotated() -> None:
  260. def my_function() -> Annotated[str, "test description"]:
  261. return "result"
  262. tool = FunctionTool(my_function, description="Function tool.")
  263. assert tool.name == "my_function"
  264. assert tool.description == "Function tool."
  265. assert issubclass(tool.args_type(), BaseModel)
  266. assert tool.return_type() is str
  267. assert tool.state_type() is None
  268. def test_func_tool_no_args() -> None:
  269. def my_function() -> str:
  270. return "result"
  271. tool = FunctionTool(my_function, description="Function tool.")
  272. assert tool.name == "my_function"
  273. assert tool.description == "Function tool."
  274. assert issubclass(tool.args_type(), BaseModel)
  275. assert len(tool.args_type().model_fields) == 0
  276. assert tool.return_type() is str
  277. assert tool.state_type() is None
  278. def test_func_tool_return_none() -> None:
  279. def my_function() -> None:
  280. return None
  281. tool = FunctionTool(my_function, description="Function tool.")
  282. assert tool.name == "my_function"
  283. assert tool.description == "Function tool."
  284. assert issubclass(tool.args_type(), BaseModel)
  285. assert tool.return_type() is type(None)
  286. assert tool.state_type() is None
  287. def test_func_tool_return_base_model() -> None:
  288. def my_function() -> MyResult:
  289. return MyResult(result="value")
  290. tool = FunctionTool(my_function, description="Function tool.")
  291. assert tool.name == "my_function"
  292. assert tool.description == "Function tool."
  293. assert issubclass(tool.args_type(), BaseModel)
  294. assert tool.return_type() is MyResult
  295. assert tool.state_type() is None
  296. @pytest.mark.asyncio
  297. async def test_func_call_tool() -> None:
  298. def my_function() -> str:
  299. return "result"
  300. tool = FunctionTool(my_function, description="Function tool.")
  301. result = await tool.run_json({}, CancellationToken())
  302. assert result == "result"
  303. @pytest.mark.asyncio
  304. async def test_func_call_tool_base_model() -> None:
  305. def my_function() -> MyResult:
  306. return MyResult(result="value")
  307. tool = FunctionTool(my_function, description="Function tool.")
  308. result = await tool.run_json({}, CancellationToken())
  309. assert isinstance(result, MyResult)
  310. assert result.result == "value"
  311. @pytest.mark.asyncio
  312. async def test_func_call_tool_with_arg_base_model() -> None:
  313. def my_function(arg: str) -> MyResult:
  314. return MyResult(result="value")
  315. tool = FunctionTool(my_function, description="Function tool.")
  316. result = await tool.run_json({"arg": "test"}, CancellationToken())
  317. assert isinstance(result, MyResult)
  318. assert result.result == "value"
  319. @pytest.mark.asyncio
  320. async def test_func_str_res() -> None:
  321. def my_function(arg: str) -> str:
  322. return "test"
  323. tool = FunctionTool(my_function, description="Function tool.")
  324. result = await tool.run_json({"arg": "test"}, CancellationToken())
  325. assert tool.return_value_as_string(result) == "test"
  326. @pytest.mark.asyncio
  327. async def test_func_base_model_res() -> None:
  328. def my_function(arg: str) -> MyResult:
  329. return MyResult(result="test")
  330. tool = FunctionTool(my_function, description="Function tool.")
  331. result = await tool.run_json({"arg": "test"}, CancellationToken())
  332. assert tool.return_value_as_string(result) == '{"result": "test"}'
  333. @pytest.mark.asyncio
  334. async def test_func_base_model_custom_dump_res() -> None:
  335. class MyResultCustomDump(BaseModel):
  336. result: str = Field(description="The other description.")
  337. @model_serializer
  338. def ser_model(self) -> str:
  339. return "custom: " + self.result
  340. def my_function(arg: str) -> MyResultCustomDump:
  341. return MyResultCustomDump(result="test")
  342. tool = FunctionTool(my_function, description="Function tool.")
  343. result = await tool.run_json({"arg": "test"}, CancellationToken())
  344. assert tool.return_value_as_string(result) == "custom: test"
  345. @pytest.mark.asyncio
  346. async def test_func_int_res() -> None:
  347. def my_function(arg: int) -> int:
  348. return arg
  349. tool = FunctionTool(my_function, description="Function tool.")
  350. result = await tool.run_json({"arg": 5}, CancellationToken())
  351. assert tool.return_value_as_string(result) == "5"
  352. @pytest.mark.asyncio
  353. async def test_func_tool_return_list() -> None:
  354. def my_function() -> List[int]:
  355. return [1, 2]
  356. tool = FunctionTool(my_function, description="Function tool.")
  357. result = await tool.run_json({}, CancellationToken())
  358. assert isinstance(result, list)
  359. assert result == [1, 2]
  360. assert tool.return_value_as_string(result) == "[1, 2]"
  361. def test_nested_tool_schema_generation() -> None:
  362. schema: ToolSchema = MyNestedTool().schema
  363. assert "description" in schema
  364. assert "parameters" in schema
  365. assert "type" in schema["parameters"]
  366. assert "arg" in schema["parameters"]["properties"]
  367. assert "type" in schema["parameters"]["properties"]["arg"]
  368. assert "title" in schema["parameters"]["properties"]["arg"]
  369. assert "properties" in schema["parameters"]["properties"]["arg"]
  370. assert "query" in schema["parameters"]["properties"]["arg"]["properties"]
  371. assert "type" in schema["parameters"]["properties"]["arg"]["properties"]["query"]
  372. assert "description" in schema["parameters"]["properties"]["arg"]["properties"]["query"]
  373. assert "required" in schema["parameters"]
  374. assert schema["description"] == "Description of test nested tool."
  375. assert schema["parameters"]["type"] == "object"
  376. assert schema["parameters"]["properties"]["arg"]["type"] == "object"
  377. assert schema["parameters"]["properties"]["arg"]["title"] == "MyArgs"
  378. assert schema["parameters"]["properties"]["arg"]["properties"]["query"]["type"] == "string"
  379. assert schema["parameters"]["properties"]["arg"]["properties"]["query"]["description"] == "The description."
  380. assert schema["parameters"]["properties"]["arg"]["required"] == ["query"]
  381. assert schema["parameters"]["required"] == ["arg"]
  382. assert len(schema["parameters"]["properties"]) == 1
  383. @pytest.mark.asyncio
  384. async def test_nested_tool_run() -> None:
  385. tool = MyNestedTool()
  386. result = await tool.run_json({"arg": {"query": "test"}}, CancellationToken())
  387. assert isinstance(result, MyResult)
  388. assert result.result == "value"
  389. assert tool.called_count == 1
  390. result = await tool.run_json({"arg": {"query": "test"}}, CancellationToken())
  391. result = await tool.run_json({"arg": {"query": "test"}}, CancellationToken())
  392. assert tool.called_count == 3
  393. def test_nested_tool_properties() -> None:
  394. tool = MyNestedTool()
  395. assert tool.name == "TestNestedTool"
  396. assert tool.description == "Description of test nested tool."
  397. assert tool.args_type() == MyNestedArgs
  398. assert tool.return_type() == MyResult
  399. assert tool.state_type() is None
  400. # --- Define a sample Pydantic model and tool function ---
  401. class AddInput(BaseModel):
  402. x: int
  403. y: int
  404. def add_tool(input: AddInput) -> int:
  405. return input.x + input.y
  406. @pytest.mark.asyncio
  407. async def test_func_tool_with_pydantic_model_conversion_success() -> None:
  408. tool = FunctionTool(add_tool, description="Tool to add two numbers.")
  409. test_input = {"input": {"x": 2, "y": 3}}
  410. result = await tool.run_json(test_input, CancellationToken())
  411. assert result == 5
  412. assert tool.return_value_as_string(result) == "5"
  413. @pytest.mark.asyncio
  414. async def test_func_tool_with_pydantic_model_conversion_failure() -> None:
  415. tool = FunctionTool(add_tool, description="Tool to add two numbers.")
  416. test_input = {"input": {"x": 2}}
  417. with pytest.raises(ValidationError, match="Field required"):
  418. await tool.run_json(test_input, CancellationToken())
  419. # --- Additional test using a dataclass ---
  420. @dataclass
  421. class MultiplyInput:
  422. a: int
  423. b: int
  424. def multiply_tool(input: MultiplyInput) -> int:
  425. return input.a * input.b
  426. @pytest.mark.asyncio
  427. async def test_func_tool_with_dataclass_conversion_success() -> None:
  428. tool = FunctionTool(multiply_tool, description="Tool to multiply two numbers.")
  429. test_input = {"input": {"a": 4, "b": 5}}
  430. result = await tool.run_json(test_input, CancellationToken())
  431. assert result == 20
  432. assert tool.return_value_as_string(result) == "20"
  433. @pytest.mark.asyncio
  434. async def test_func_tool_with_dataclass_conversion_failure() -> None:
  435. tool = FunctionTool(multiply_tool, description="Tool to multiply two numbers.")
  436. # Missing field 'b'
  437. test_input = {"input": {"a": 4}}
  438. with pytest.raises(ValidationError, match="Field required"):
  439. await tool.run_json(test_input, CancellationToken())