Skip to content

A programming framework for agentic AI

Fix: Auto-Convert Pydantic and Dataclass Arguments in AutoGen Tool Calls (#5737)

Muhammad Junaid0b9a622b5647
diff --git a/python/packages/autogen-core/src/autogen_core/tools/_function_tool.py b/python/packages/autogen-core/src/autogen_core/tools/_function_tool.py
index fe3f8fb75..048b26525 100644
--- a/python/packages/autogen-core/src/autogen_core/tools/_function_tool.py
+++ b/python/packages/autogen-core/src/autogen_core/tools/_function_tool.py
@@ -95,33 +95,37 @@ class FunctionTool(BaseTool[BaseModel, BaseModel], Component[FunctionToolConfig]
) -> None:
self._func = func
self._global_imports = global_imports
- signature = get_typed_signature(func)
+ self._signature = get_typed_signature(func)
func_name = name or func.func.__name__ if isinstance(func, functools.partial) else name or func.__name__
- args_model = args_base_model_from_signature(func_name + "args", signature)
- return_type = signature.return_annotation
- self._has_cancellation_support = "cancellation_token" in signature.parameters
+ args_model = args_base_model_from_signature(func_name + "args", self._signature)
+ self._has_cancellation_support = "cancellation_token" in self._signature.parameters
+ return_type = self._signature.return_annotation
super().__init__(args_model, return_type, func_name, description, strict)
async def run(self, args: BaseModel, cancellation_token: CancellationToken) -> Any:
+ kwargs = {}
+
+ for name in self._signature.parameters.keys():
+ if hasattr(args, name):
+ kwargs[name] = getattr(args, name)
+
if asyncio.iscoroutinefunction(self._func):
if self._has_cancellation_support:
- result = await self._func(**args.model_dump(), cancellation_token=cancellation_token)
+ result = await self._func(**kwargs, cancellation_token=cancellation_token)
else:
- result = await self._func(**args.model_dump())
+ result = await self._func(**kwargs)
else:
if self._has_cancellation_support:
result = await asyncio.get_event_loop().run_in_executor(
None,
functools.partial(
self._func,
- **args.model_dump(),
+ **kwargs,
cancellation_token=cancellation_token,
),
)
else:
- future = asyncio.get_event_loop().run_in_executor(
- None, functools.partial(self._func, **args.model_dump())
- )
+ future = asyncio.get_event_loop().run_in_executor(None, functools.partial(self._func, **kwargs))
cancellation_token.link_future(future)
result = await future
diff --git a/python/packages/autogen-core/tests/test_tools.py b/python/packages/autogen-core/tests/test_tools.py
index d0346c193..c2efed058 100644
--- a/python/packages/autogen-core/tests/test_tools.py
+++ b/python/packages/autogen-core/tests/test_tools.py
@@ -1,4 +1,5 @@
import inspect
+from dataclasses import dataclass
from functools import partial
from typing import Annotated, List
@@ -7,7 +8,7 @@ from autogen_core import CancellationToken
from autogen_core._function_utils import get_typed_signature
from autogen_core.tools import BaseTool, FunctionTool
from autogen_core.tools._base import ToolSchema
-from pydantic import BaseModel, Field, model_serializer
+from pydantic import BaseModel, Field, ValidationError, model_serializer
from pydantic_core import PydanticUndefined
@@ -527,3 +528,64 @@ def test_nested_tool_properties() -> None:
assert tool.args_type() == MyNestedArgs
assert tool.return_type() == MyResult
assert tool.state_type() is None
+
+
+# --- Define a sample Pydantic model and tool function ---
+
+
+class AddInput(BaseModel):
+ x: int
+ y: int
+
+
+def add_tool(input: AddInput) -> int:
+ return input.x + input.y
+
+
+async def test_func_tool_with_pydantic_model_conversion_success() -> None:
+ tool = FunctionTool(add_tool, description="Tool to add two numbers.")
+ test_input = {"input": {"x": 2, "y": 3}}
+ result = await tool.run_json(test_input, CancellationToken())
+
+ assert result == 5
+ assert tool.return_value_as_string(result) == "5"
+
+
+async def test_func_tool_with_pydantic_model_conversion_failure() -> None:
+ tool = FunctionTool(add_tool, description="Tool to add two numbers.")
+ test_input = {"input": {"x": 2}}
+
+ with pytest.raises(ValidationError, match="Field required"):
+ await tool.run_json(test_input, CancellationToken())
+
+
+# --- Additional test using a dataclass ---
+@dataclass
+class MultiplyInput:
+ a: int
+ b: int
+
+
+def multiply_tool(input: MultiplyInput) -> int:
+ return input.a * input.b
+
+
+async def test_func_tool_with_dataclass_conversion_success() -> None:
+ tool = FunctionTool(multiply_tool, description="Tool to multiply two numbers.")
+ test_input = {"input": {"a": 4, "b": 5}}
+ result = await tool.run_json(test_input, CancellationToken())
+ assert result == 20
+ assert tool.return_value_as_string(result) == "20"
+
+
+async def test_func_tool_with_dataclass_conversion_failure() -> None:
+ tool = FunctionTool(multiply_tool, description="Tool to multiply two numbers.")
+ # Missing field 'b'
+ test_input = {"input": {"a": 4}}
+
+ with pytest.raises(ValidationError, match="Field required"):
+ await tool.run_json(test_input, CancellationToken())