How to Build an AI Agent: A Minimal Tool Loop

Build a minimal AI agent in Python with a tool-use loop, check that it works, and find where it breaks, using Claude's Messages API docs as of 2026-11-21.

Updated · Markdown version

An AI agent is a loop: the model requests a tool, your code runs it, the result goes back to the model, and the cycle repeats until the model replies with text instead of another tool request. You can build the smallest working version in one Python file with the Messages API, then add the limits that stop it from running indefinitely.

Build the smallest loop

  1. Create a client with anthropic.Anthropic(), as the SDK examples in Anthropic's tool use docs do.
  2. Describe each tool with a name, a description, and an input_schema (a JSON Schema object). Claude reads the description to decide whether a request needs the tool.
  3. Send tools= and messages= in a messages.create call.
  4. Append response.content to messages as the assistant turn. Keep the tool_use blocks as returned; rebuilding them from text breaks the ids.
  5. If response.stop_reason is "tool_use", run each tool_use block and build a tool_result block with tool_use_id set to that block's id. Send all results in one user message.
  6. Repeat until the stop reason is anything else, with a hard cap on iterations.
import anthropic

client = anthropic.Anthropic()
MODEL = "<current-model-id>"  # check the Claude docs for current IDs
MAX_STEPS = 5

tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a given location.",
    "input_schema": {
        "type": "object",
        "properties": {"location": {"type": "string"}},
        "required": ["location"],
    },
}]

def run_tool(name, args):
    if name == "get_weather":
        return "15 degrees Celsius, partly cloudy"  # replace with a real lookup
    return f"Unknown tool: {name}"

messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]
for _ in range(MAX_STEPS):
    response = client.messages.create(
        model=MODEL, max_tokens=1024, tools=tools, messages=messages
    )
    messages.append({"role": "assistant", "content": response.content})
    if response.stop_reason != "tool_use":
        break
    results = [
        {"type": "tool_result", "tool_use_id": block.id,
         "content": run_tool(block.name, block.input)}
        for block in response.content if block.type == "tool_use"
    ]
    messages.append({"role": "user", "content": results})

print(response.content[-1].text if response.content[-1].type == "text" else response.content)

Check that it worked. Run the script as written. You should see one get_weather call and a text answer that uses the stub result. Then change the prompt to a question no tool covers, such as arithmetic. The model should answer without requesting a tool. If it does not, the tool description is probably too broad.

Pitfalls

  • Missing or mismatched ids. A tool_result with the wrong tool_use_id fails the next request. Pass block.id through unchanged.
  • Runaway loops. A model that keeps requesting tools never reaches a text reply. The MAX_STEPS cap is the guard; Anthropic's guidance also recommends stopping conditions for this reason.
  • Parallel calls you did not plan for. A single response can contain several tool_use blocks. The loop above answers all of them. If your tools must run one at a time, set disable_parallel_tool_use in tool_choice.
  • Silent tool failures. If run_tool raises an exception and you do not return it as a result, the loop stops with no explanation. Catch errors and return them as tool output so the model can react.
  • Cost growth. Each turn resends the full history, including tool definitions and results. A long tool output repeated across many turns costs input tokens every time. Truncate large results before returning them.

When to use a skill instead

A one-off agent can live in a single script like the one above. A reusable skill fits better when the same procedure, such as checking a tool's output format or following a fixed set of steps, has to run across many sessions. subagent-design helps when part of the work should go to a separate agent, since it covers what to delegate and how to write the brief. llm-eval-test-sets builds the test cases that show whether a change to the loop, its prompts or its tool descriptions made results worse. Ad-hoc prompting is enough for a single tool and a single task.

FAQ

How do I build an AI agent? Start with the loop: send tools with a request, run any tool_use block the response contains, return a tool_result, and repeat with a cap on iterations. Test with one tool before you add more.

How do I build skills for an AI agent? A skill packages a repeatable procedure; the loop itself does not need one. Write a skill when the same steps recur across tasks, and keep the loop code separate so the skill can change without touching it.

Does an agent need a skill to call tools? No. Tool calls depend only on the tool definitions you pass to the API. A skill helps with repeated procedures and is optional for a working agent.

Platform Score is our assessment under a published method. It is not a safety guarantee.

Terms this guide uses

This item is a worked example in the AI glossary for:

Next steps

  1. What Is an AI Agent? The Model, Tools and Memory Loop Read next.
  2. How to Use an AI Agent on a First Task You Can Check Read next.
  3. All guides by topic Browse everything.

Sources

This page is not offered to search engines yet: The content file does not mark this page indexable yet.