Skip to main content
This example shows how to create agents that can call real Python functions. We’ll demonstrate both the low-level approach and the preferred Agent class approach.
1

Define the tool

from ai_sdk import tool

add = tool(
    name="add",
    description="Add two numbers and return the sum.",
    parameters={
        "type": "object",
        "properties": {
            "a": {"type": "integer"},
            "b": {"type": "integer"},
        },
        "required": ["a", "b"],
    },
    execute=lambda a, b: a + b,
)
2

Using the Agent class (Recommended)

The Agent class provides a more convenient interface with persistent state and better organization:
from ai_sdk import Agent, openai
from tools import add

model = openai("gpt-4.1-mini", temperature=0)
agent = Agent(
    name="Math Assistant",
    model=model,
    system="You are a helpful math assistant.",
    tools=[add]
)

response = agent.run("What is 21 + 21?")
print(response)  # "The result is 42."
The Agent class is the recommended approach for most use cases. It provides persistent state, better error handling, and a cleaner interface for multi-turn conversations.
3

Low-level approach (Advanced)

For advanced use cases, you can use the lower-level generate_text function directly:
from ai_sdk import openai, generate_text
from tools import add  # assume above code lives in tools.py

model = openai("gpt-4.1-mini", temperature=0)

res = generate_text(
    model=model,
    prompt="What is 21 + 21?",
    tools=[add],
)
print(res.text) # "The result is 42."
print(res.tool_calls) # introspection
print(res.tool_results)
The SDK automatically loops until the model stops requesting tools (max 8 iterations by default). Each tool result is appended as a tool message so the model can reference previous calls.