How to Build an AI Agent with Claude, Step by Step

Build a working AI agent with the Claude API: define tools, write the agent loop, handle tool errors and add the guardrails you need before real users touch it.

Short answer: an AI agent is a loop. You give Claude a goal and a set of tools described as JSON schemas. Claude replies either with an answer or with a request to call a tool; your code runs the tool, sends the result back, and repeats until Claude says it is done. This guide builds that loop step by step with the Claude API in Python.

Chatbot vs agent

A chatbot answers from what it already knows. An agent can act: look up an order, read a file, create a ticket, then decide what to do next based on the result. The model chooses which tool to call and when; your code decides which tools exist and what they are allowed to do.

Step 1: Define a tool

A tool has a name, a description and an input schema. The description is what Claude reads to decide when to use it, so write it like documentation for a new teammate.

tools = [
    {
        "name": "get_order_status",
        "description": "Look up the shipping status of a customer order by its order ID. Use this whenever the customer asks where their order is.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_id": {"type": "string", "description": "The order ID, e.g. A-1042"}
            },
            "required": ["order_id"],
        },
    }
]

def get_order_status(order_id: str) -> str:
    # Replace with a real database or API call.
    return f"Order {order_id} shipped yesterday and arrives Friday."

Step 2: Write the agent loop

Call the API with the tools. If the reply’s stop_reason is tool_use, run each requested tool, send the results back as tool_result blocks, and call again. Stop when Claude finishes.

import anthropic

client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Where is my order A-1042?"}]

while True:
    response = client.messages.create(
        model="claude-opus-5-5",
        max_tokens=4096,
        system="You are a support agent for an online store. Use tools to check facts before answering.",
        tools=tools,
        messages=messages,
    )
    messages.append({"role": "assistant", "content": response.content})

    if response.stop_reason != "tool_use":
        break

    results = []
    for block in response.content:
        if block.type == "tool_use":
            if block.name == "get_order_status":
                output = get_order_status(**block.input)
            else:
                output = f"Unknown tool: {block.name}"
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
    messages.append({"role": "user", "content": results})

print(next(b.text for b in response.content if b.type == "text"))

Three details matter here. Each tool_result must carry the tool_use_id of the call it answers. Claude can request several tools in one reply, so handle every tool_use block, not just the first. And the whole history, including tool calls and results, goes back on every turn.

The Python and TypeScript SDKs also include a tool runner (currently in beta) that runs this loop for you from decorated functions. Writing the loop once by hand is still the best way to understand what the runner does.

Step 3: Handle errors as results, not crashes

When a tool fails, return the error to Claude as the tool result, with "is_error": true, instead of raising an exception. Claude can then retry with different input or explain the problem to the user.

results.append({
    "type": "tool_result",
    "tool_use_id": block.id,
    "content": "Order not found. Ask the customer to check the ID.",
    "is_error": True,
})

Step 4: Add guardrails before real users

  • Cap the loop. Stop after a fixed number of turns (for example 10) so a confused agent cannot run up cost.
  • Separate read and write tools. Let the agent read freely, but require confirmation, or a human, before tools that send email, charge money or delete data.
  • Validate tool input in code. Never trust the model to stay inside limits you can check yourself, such as refund amounts or allowed IDs.
  • Log every tool call. When something goes wrong, the tool-call log is how you find out why.
  • Test with real cases. Run 20 to 30 real requests on every change and check both the final answer and which tools were called.

Designing good tools

  • Prefer a few focused tools over one tool with a dozen modes.
  • Return short, structured results. Dumping a whole database row wastes tokens and confuses the model.
  • Say in the description when not to use the tool, as well as when to use it.
  • Name inputs the way your users talk (“order_id”, not “oid”).

From one agent to real integrations

Writing a tool definition for every system gets repetitive. The Model Context Protocol (MCP) packages tools for systems like GitHub, Jira or Slack as reusable servers that any MCP client can use. Read MCP explained next. If you are new to the API itself, start with the Claude API tutorial.

Designing agents, connecting them to Jira, Confluence, Slack and GitHub, and testing them with quality gates are weeks 2 to 4 of the live cohort, where you build an agent for your own product.

FAQ

What is the difference between tool use and function calling?

They are the same idea. Anthropic calls it tool use: you describe functions, the model asks to call them, and your code runs them.

Does Claude run my tools itself?

No. For tools you define, Claude only asks for a call with specific inputs; your code runs the function and returns the result. Anthropic also offers server tools, such as web search, that run on its side.

How many tools can an agent have?

There is no small fixed limit, but quality drops when many similar tools compete. Start with the few tools the task needs and add more only when tests show a gap.

Which Claude model is best for agents?

Use the most capable model, currently Claude Opus 5.5, while you build and test. Once your tests pass, try a cheaper model for simpler agents and keep it only if the tests still pass.

Start building your AI product

Five weeks from now you could have a working AI product with real users. Join the next live cohort, or start the self-paced course today.

Join the live cohortStart self-paced today