> ## Documentation Index
> Fetch the complete documentation index at: https://pythonaisdk.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool-calling agents

> Let the model call real Python functions to answer user queries.

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.

<Steps>
  <Step title="Define the tool">
    ```python theme={null}
    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,
    )
    ```
  </Step>

  <Step title="Using the Agent class (Recommended)">
    The **Agent** class provides a more convenient interface with persistent state and better organization:

    ```python theme={null}
    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."
    ```

    <Note>
      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.
    </Note>
  </Step>

  <Step title="Low-level approach (Advanced)">
    For advanced use cases, you can use the lower-level `generate_text` function directly:

    ```python theme={null}
    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)
    ```
  </Step>
</Steps>

<Tip>
  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.
</Tip>
