article thumbnail

Building an AI Agent: The Tool-Use Loop

Model, tool, result, repeat -- the 40-line loop behind every AI agent

12 min read
#ai, #agents, #claude, #llm, #python, #tools, #friday4

"AI agent" sounds like something that needs a framework, a vector database, and a venture round. It doesn't. Strip away the marketing and every agent -- from a coding assistant to a customer-support bot -- is the same small idea: give the model some tools, run it in a loop, and feed it the results of whatever it asks for. That's it. The loop is about forty lines of Python, and once you've written one, you'll understand every agent product you ever use.

In this article we'll build a real one: an agent that answers plain-English questions about a SQLite database by exploring the schema and writing its own queries. We'll write the loop by hand first so you see the machinery, then replace it with the SDK's built-in version. If you're new to the pieces, these earlier articles are good background: LLMs, MCP - The Model Context Protocol, and RAG -- Giving LLMs a Memory.


What Makes Something an Agent?

A plain LLM call is one question, one answer. The model can only use what it already knows and what you pasted into the prompt. An agent is a model that can act: it can decide it needs more information or needs to do something, ask your code to do it, see the result, and decide what to do next -- repeating until the job is done.

The cycle looks like this:

 you ask a question
        |
        v
 +-----------------+      "I need to call run_select"      +-------------------+
 |   the model     | ------------------------------------> |   YOUR code runs  |
 | (decides what   |                                       |   the tool and    |
 |  to do next)    | <------------------------------------ |   returns results |
 +-----------------+         tool result goes back         +-------------------+
        |
        v  (when no more tools are needed)
 final answer

The key point most people miss: the model never runs anything itself. It only asks. Your code is in charge of actually executing the tool, and of deciding whether to. That's where all the safety lives.


Step 1: The Tools

Our agent gets three tools, all backed by a SQLite database:

import json
import sqlite3

# Open the database READ-ONLY. This is the real safety guarantee --
# even if the model writes a destructive statement, SQLite refuses it.
db = sqlite3.connect("file:shop.db?mode=ro", uri=True)
db.row_factory = sqlite3.Row

def list_tables() -> list[str]:
    rows = db.execute(
        "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
    ).fetchall()
    return [r["name"] for r in rows]

def describe_table(table: str) -> list[dict]:
    if table not in list_tables():  # never trust a name from the model
        raise ValueError(f"Unknown table: {table}")
    return [dict(r) for r in db.execute(f'PRAGMA table_info("{table}")')]

def run_select(sql: str) -> list[dict]:
    if not sql.lstrip().lower().startswith("select"):
        raise ValueError("Only SELECT statements are allowed.")
    return [dict(r) for r in db.execute(sql).fetchmany(50)]  # cap the rows

Notice the habits: a read-only connection, validating the table name against a known list, and capping the rows returned so one careless SELECT * can't flood the model's context.

Step 2: Describe the Tools to the Model

The model can't see your Python. It sees only a name, a description, and a JSON schema for each tool. These descriptions are, in effect, the prompt for your agent -- write them carefully.

tools = [
    {
        "name": "list_tables",
        "description": "List every table in the database. Call this first to see what data exists.",
        "strict": True,
        "input_schema": {"type": "object", "properties": {}, "required": [], "additionalProperties": False},
    },
    {
        "name": "describe_table",
        "description": "Show the columns and types of one table. Use it before writing a query against that table.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {"table": {"type": "string", "description": "Exact table name from list_tables."}},
            "required": ["table"],
            "additionalProperties": False,
        },
    },
    {
        "name": "run_select",
        "description": "Run one read-only SQLite SELECT statement and return up to 50 rows as JSON.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {"sql": {"type": "string", "description": "A single SQLite SELECT statement."}},
            "required": ["sql"],
            "additionalProperties": False,
        },
    },
]

HANDLERS = {
    "list_tables": lambda args: list_tables(),
    "describe_table": lambda args: describe_table(args["table"]),
    "run_select": lambda args: run_select(args["sql"]),
}

"strict": True tells the API to guarantee the model's arguments match your schema exactly, so you won't get a missing field or a wrong type.

Step 3: The Loop

Here is the entire agent:

import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-opus-5-5"
SYSTEM = (
    "You answer questions about a shop's SQLite database. Explore the schema first, "
    "then write SELECT queries. Base every answer on query results, and say so if the "
    "data cannot answer the question."
)

def run_agent(question: str, max_turns: int = 10) -> str:
    messages = [{"role": "user", "content": question}]

    for _ in range(max_turns):
        response = client.messages.create(
            model=MODEL,
            max_tokens=16000,
            system=SYSTEM,
            tools=tools,
            messages=messages,
            output_config={"effort": "medium"},
        )

        # Always keep the model's full reply in the history, exactly as returned.
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason == "refusal":
            return "The model declined to answer this request."
        if response.stop_reason != "tool_use":
            # Done: the model has nothing more to ask for.
            return "".join(b.text for b in response.content if b.type == "text")

        # Run EVERY tool the model asked for, then send ALL results back together.
        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            try:
                output = HANDLERS[block.name](block.input)
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": json.dumps(output, default=str),
                })
            except Exception as exc:
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": f"Error: {exc}",
                    "is_error": True,
                })
        messages.append({"role": "user", "content": results})

    return "Stopped: the agent hit its turn limit before finishing."

print(run_agent("Which five customers spent the most, and how much did each spend?"))

Run it and the transcript behind the scenes goes something like this:

  1. The model calls list_tables -- sees customers, orders, order_items.
  2. It calls describe_table for orders and order_items (often both at once, in parallel).
  3. It writes a run_select with a JOIN and a GROUP BY.
  4. Maybe the first query has a typo -- your code returns Error: no such column ... with is_error: True, and the model reads the error and fixes its own query.
  5. It calls no more tools and writes the final answer.

No one scripted those steps. The model chose them. That is the whole difference between a workflow and an agent.


The Rules That Make It Work

1. Check stop_reason, not the text. "tool_use" means "I want you to run something." Anything else ("end_turn", "max_tokens", "refusal") means stop and look at what you got. Always check for "refusal" before reading the content.

2. Echo the model's reply back unchanged. Append response.content -- the whole list -- to the history. It can contain thinking blocks and tool_use blocks that the API needs to see on the next turn. Rebuilding the message yourself from just the text is a classic way to break an agent, or quietly make it worse.

3. Every tool_use needs a matching tool_result. The tool_use_id must match. When the model makes several calls in one turn, return all of the results together in one user message. Splitting them across messages teaches the model to stop calling tools in parallel.

4. Return errors; don't crash. A failed tool is information. Send the error back with is_error: True and the model will usually adapt. Letting an exception kill the loop throws away the agent's best feature: recovering.

5. Always cap the loop. max_turns is not optional. An agent can chase its own tail, and every turn costs money. A hard ceiling is cheap insurance.


The Shortcut: The SDK's Tool Runner

Once you understand the loop, you don't have to write it every time. The Anthropic Python SDK includes a tool runner (currently in beta) that handles the loop for you. You supply decorated functions, and it builds the schemas from your type hints and docstrings:

import json
import anthropic
from anthropic import beta_tool

client = anthropic.Anthropic()

@beta_tool
def list_tables() -> str:
    """List every table in the database. Call this first to see what data exists."""
    return json.dumps(list_tables_impl())

@beta_tool
def describe_table(table: str) -> str:
    """Show the columns and types of one table.

    Args:
        table: Exact table name from list_tables.
    """
    return json.dumps(describe_table_impl(table), default=str)

@beta_tool
def run_select(sql: str) -> str:
    """Run one read-only SQLite SELECT statement and return up to 50 rows as JSON.

    Args:
        sql: A single SQLite SELECT statement.
    """
    return json.dumps(run_select_impl(sql), default=str)

runner = client.beta.messages.tool_runner(
    model="claude-opus-5-5",
    max_tokens=16000,
    system=SYSTEM,
    tools=[list_tables, describe_table, run_select],
    messages=[{"role": "user", "content": "Which product category earns the most revenue?"}],
)

final = runner.until_done()
print("".join(b.text for b in final.content if b.type == "text"))

(Here *_impl are the plain functions from Step 1, renamed with an _impl suffix so the decorated tools can keep the short names -- remember to update the list_tables() call inside describe_table_impl too.) Same behavior, a fraction of the code. Use the runner for most projects; drop to the hand-written loop when you need to control something it doesn't expose.


Making It Production-Ready

The forty-line loop is the foundation. Before it faces real users, add:


When Not to Use an Agent

Agents are slower, costlier, and less predictable than a plain call. Reach for the simplest thing that works:

If the job is... Use
Classify, summarize, extract, translate A single API call
A fixed series of steps you can write down A workflow -- your code calls the model at each step
Open-ended, the steps depend on what's found, and mistakes are recoverable An agent

A good test: could you write the steps as a flowchart ahead of time? If yes, write the flowchart. If the right next step genuinely depends on what the last tool returned, that's an agent's job.


Your Takeaway

An agent is a loop: ask the model, run the tools it requests, return the results, repeat until it stops asking. The model supplies the judgment; your code supplies the hands, the limits, and the safety. Build the 40-line version once, by hand, and the rest of the AI agent world -- coding assistants, research bots, MCP servers -- stops being magic and starts being engineering.

Have a look at Getting Started with Claude CLI to see a polished agent that uses exactly this loop, then go build a small one of your own.

What did you learn?

Tell us what you learned from this article, or what you liked about it. We read every comment.

Comments appear after a quick review. Please no links.

Know someone who'd love it too?

Most covered topics