Tools extend agent capabilities beyond LLM generation. Agents can call tools to interact with external systems, execute code, search the web, and more.
The simplest way to add tools is using Python functions:
from autogen_agentchat.agents import AssistantAgentfrom autogen_ext.models.openai import OpenAIChatCompletionClientdef get_weather(city: str) -> str: """Get the weather for a city. Args: city: The city name Returns: Weather description """ # Simulated weather lookup return f"The weather in {city} is sunny, 72°F"model_client = OpenAIChatCompletionClient(model="gpt-4o")agent = AssistantAgent( "assistant", model_client=model_client, tools=[get_weather] # Pass function directly)result = await agent.run(task="What's the weather in Paris?")
The function docstring and type hints are used to generate the tool schema for the LLM.
import aiohttpasync def fetch_url(url: str) -> str: """Fetch content from a URL. Args: url: The URL to fetch """ async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text()agent = AssistantAgent( "web_fetcher", model_client=model_client, tools=[fetch_url])
from autogen_agentchat.tools import AgentTool# Create specialized agentsmath_agent = AssistantAgent( "math_expert", model_client=model_client, system_message="You are a math expert.")chemistry_agent = AssistantAgent( "chemistry_expert", model_client=model_client, system_message="You are a chemistry expert.")# Wrap as toolsmath_tool = AgentTool(math_agent, return_value_as_last_message=True)chem_tool = AgentTool(chemistry_agent, return_value_as_last_message=True)# Main agent can delegate to expertsmain_agent = AssistantAgent( "assistant", model_client=model_client, tools=[math_tool, chem_tool])result = await main_agent.run(task="What is the molecular weight of water?")
Clear descriptions - Write detailed docstrings. The LLM uses them to understand when to call the tool.
Type hints - Always use type hints. They’re used to generate the tool schema.
Error handling - Handle errors gracefully in your tools:
def get_weather(city: str) -> str: """Get weather for a city.""" try: # API call return result except Exception as e: return f"Error fetching weather: {str(e)}"