Skip to content

Agent Tools and Run Method Examples#

Open In Colab Open on GitHub

export const quartoRawHtml = [`

Method Registration Time Flexibility Use Case
Static (functions parameter) Agent initialization Fixed set of tools Specialized agents with consistent capabilities
Dynamic (tools parameter) Runtime/per conversation Flexible tool assignment General-purpose agents with varying needs
Hybrid Both Best of both worlds Agents with core capabilities + situational tools

`];

This notebook demonstrates two ways to add tools/functions to an agent and shows how to use the run() method for standalone agent chat.

Two Methods for Adding Tools:#

  1. Static Registration: Pass functions during agent initialization using the functions parameter
  2. Dynamic Registration: Pass tools at runtime using the tools parameter in the run() method

Both approaches allow agents to call functions/tools during conversation.

from typing import Annotated

import autogen
from autogen import ConversableAgent
from autogen.tools import tool

# Load LLM configuration
llm_config = autogen.LLMConfig.from_json(path="OAI_CONFIG_LIST", cache_seed=42).where(model=["gpt-4o-mini"])

Define Sample Tools#

Let’s create some simple tools that our agents can use:

@tool(description="Calculate the square of a number")
def calculate_square(number: Annotated[int, "The number to square"]) -> int:
    """Calculate the square of a number."""
    result = number**2
    print(f"Calculating square: {number}² = {result}")
    return result

@tool(description="Get weather information for a city")
def get_weather(city: Annotated[str, "The city name"]) -> str:
    """Get weather information for a city (mock function)."""
    weather_data = {
        "new york": "Sunny, 72°F",
        "london": "Cloudy, 15°C",
        "tokyo": "Rainy, 18°C",
        "paris": "Partly cloudy, 20°C",
    }
    result = weather_data.get(city.lower(), f"Weather data not available for {city}")
    print(f"Weather lookup for {city}: {result}")
    return result

@tool(description="Count the number of words in a text")
def count_words(text: Annotated[str, "The text to count words in"]) -> int:
    """Count the number of words in a text."""
    word_count = len(text.split())
    print(f"Counting words in: '{text[:50]}{'...' if len(text) > 50 else ''}' = {word_count} words")
    return word_count

Method 1: Static Tool Registration#

Register tools during agent initialization using the functions parameter. These tools become permanently available to the agent.

# Create agent with pre-registered functions
math_agent = ConversableAgent(
    name="math_assistant",
    llm_config=llm_config,
    system_message="You are a helpful math assistant. Use the available tools to help with calculations.",
    functions=[calculate_square, count_words],  # Static registration
)

print("Math agent created with pre-registered tools:")
print(f"Available tools: {[tool.name for tool in math_agent.tools]}")

Using the agent with pre-registered tools:#

# Use run() method with pre-registered tools
chat_result = math_agent.run(
    message="Calculate the square of 15 and then count the words in this sentence: 'The quick brown fox jumps over the lazy dog.'",
    max_turns=2,
)
chat_result.process()

print(chat_result.messages)

Method 2: Dynamic Tool Registration#

Register tools at runtime using the tools parameter in the run() method. This allows for flexible tool assignment per conversation.

# Create agent without pre-registered tools
flexible_agent = ConversableAgent(
    name="flexible_assistant",
    llm_config=llm_config,
    system_message="You are a helpful assistant. Use any available tools to help answer questions.",
    # No functions parameter - tools will be provided dynamically
)

print("Flexible agent created without pre-registered tools:")
print(f"Available tools: {[tool.name for tool in flexible_agent.tools] if flexible_agent.tools else 'None'}")

Using the agent with dynamically provided tools:#

# Use run() method with dynamic tool registration
chat_result = flexible_agent.run(
    message="What's the weather like in Tokyo and London?",
    tools=[get_weather],  # Dynamic registration - tools provided at runtime
    max_turns=2,
)

chat_result.process()

print(chat_result.messages)

Another conversation with different tools:#

# Same agent, different tools for this conversation
chat_result = flexible_agent.run(
    message="Calculate the square of 8 and count words in 'AG2 is an amazing multi-agent framework for Python'",
    tools=[calculate_square, count_words],  # Different tools this time
    max_turns=2,
)

chat_result.process()

print(chat_result.messages)

Combining Both Methods#

You can combine both approaches - have some tools pre-registered and add more dynamically:

# Agent with some pre-registered tools
hybrid_agent = ConversableAgent(
    name="hybrid_assistant",
    llm_config=llm_config,
    system_message="You are a versatile assistant with both built-in and dynamic capabilities.",
    functions=[calculate_square],  # Pre-registered tool
)

print(f"Hybrid agent pre-registered tools: {[tool.name for tool in hybrid_agent.tools]}")

# Add more tools dynamically
chat_result = hybrid_agent.run(
    message="Calculate square of 12, get weather for Paris, and count words in 'Multi-agent systems are the future'",
    tools=[get_weather, count_words],  # Additional dynamic tools
    max_turns=3,
)

chat_result.process()

print(chat_result.messages)

Key Differences Summary#

When to use each approach:#

  • Static Registration: When you have agents with well-defined roles (e.g., a math agent always needs calculation tools)
  • Dynamic Registration: When you want to reuse the same agent for different types of tasks
  • Hybrid: When you have core tools that are always needed plus situational tools

The run() method makes it easy to have standalone agent conversations while supporting both tool registration approaches seamlessly.