Skip to main content
This example shows how to equip agents with custom tools that extend their capabilities beyond text generation.

What You’ll Learn

  • How to create custom tool functions
  • How to register tools with agents
  • How agents automatically decide when to use tools
  • How to handle tool results

Prerequisites

1

Install AutoGen

2

Set your OpenAI API key

Code Example

Create a weather assistant that can fetch weather data:

Run the Example

Expected Output

How It Works

  1. Tool Definition: Functions are defined with type hints and docstrings
  2. Registration: Tools are passed to the agent via the tools parameter
  3. Automatic Selection: The LLM decides when and which tools to use based on the task
  4. Execution: The agent calls the tool, receives the result, and incorporates it into the response

Tool Requirements

Function Signature

Key Requirements

  • Type Hints: All parameters must have type annotations
  • Annotated: Use Annotated to provide parameter descriptions
  • Docstring: Required - helps the LLM understand the tool’s purpose
  • Return Type: Should return a string or serializable type

Advanced Tool Example

Here’s a more complex tool that performs calculations:

Key Concepts

Tool Function

A Python function that extends agent capabilities with specific actions.

Annotated Types

Provides parameter descriptions to help the LLM use tools correctly.

Docstrings

Explains the tool’s purpose so the LLM knows when to use it.

Tool Selection

The LLM automatically decides which tool to use based on context.

Best Practices

  1. Clear Descriptions: Write detailed docstrings and parameter descriptions
  2. Error Handling: Always handle errors gracefully and return meaningful messages
  3. Type Safety: Use proper type hints to prevent runtime errors
  4. Tool Limits: Set max_tool_iterations to prevent infinite loops
  5. Security: Validate inputs and avoid executing arbitrary code

Next Steps

Web Browsing

Use MCP servers to add web browsing capabilities

Code Execution

Execute Python code safely in agent workflows