Support declarative configurations for FunctionTools #5036
Description
Enable declarative representation of tools
from typing import Literal
from autogen_core import CancellationToken
from autogen_core.tools import FunctionTool, ImportFromModule
async def calculate(
operation: Literal["add", "subtract", "multiply", "divide"],
x: float,
y: float,
) -> float:
"""Perform basic arithmetic operations on two numbers."""
if operation == "add":
return x + y
elif operation == "subtract":
return x - y
elif operation == "multiply":
return x * y
elif operation == "divide":
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
else:
raise ValueError(f"Unknown operation: {operation}")
# Create the calculator tool
calculator_tool = FunctionTool(
func=calculate,
description="A calculator that can add, subtract, multiply, or divide two numbers.",
global_imports=[
ImportFromModule("typing", ("Literal",)),
ImportFromModule("autogen_core", ("CancellationToken",)),
ImportFromModule("autogen_core.tools", ("FunctionTool",))
]
)
tool_config = calculator_tool.dump_component()
print(tool_config.model_dump())
{'provider': 'autogen_core.tools.FunctionTool', 'component_type': 'tool', 'version': 1, 'component_version': 1, 'description': None, 'config': {'source_code': 'async def calculate(\n operation: Literal["add", "subtract", "multiply", "divide"],\n x: float,\n y: float,\n) -> float:\n """Perform basic arithmetic operations on two numbers."""\n if operation == "add":\n return x + y\n elif operation == "subtract":\n return x - y\n elif operation == "multiply":\n return x * y\n elif operation == "divide":\n if y == 0:\n raise ValueError("Cannot divide by zero")\n return x [/](https://file+.vscode-resource.vscode-cdn.net/) y\n else:\n raise ValueError(f"Unknown operation: {operation}")\n', 'name': 'calculate', 'description': 'A calculator that can add, subtract, multiply, or divide two numbers.', 'global_imports': [{'module': 'typing', 'imports': ('Literal',)}, {'module': 'autogen_core', 'imports': ('CancellationToken',)}, {'module': 'autogen_core.tools', 'imports': ('FunctionTool',)}], 'has_cancellation_support': False}}
# load
loaded_calculator = FunctionTool.load_component(tool_config)