← Blog

How to Build an AI Agent with Claude API

2026-11-10 · 5 min read · SubToAPI Team

Building an AI agent with Claude API means wiring up a loop: the model decides what to do, calls a tool if needed, gets the result back, and keeps going until the task is done. Unlike a simple chatbot that answers one message at a time, an agent can take multiple steps on its own — search a database, call an external API, run calculations — before giving you a final answer.

This guide walks through the actual mechanics: how the agent loop works, how to define tools Claude can call, how to manage conversation state across turns, and the mistakes that trip up most first attempts. By the end you'll have a working pattern you can extend into a real product.

What "agent" actually means here

An agent built on Claude API is not a different API or a special mode — it's a design pattern on top of the normal Messages endpoint. The pattern has three parts:

Claude doesn't execute anything itself. It returns a tool_use block saying "call this function with these arguments," and your code is responsible for actually running that function and feeding the result back.

Step 1: Define your tools

Each tool needs a name, a description Claude can reason about, and a JSON schema for inputs. Be specific in the description — vague descriptions lead to Claude picking the wrong tool or guessing at arguments.

{
  "name": "get_weather",
  "description": "Get current weather for a city. Use this whenever the user asks about weather conditions.",
  "input_schema": {
    "type": "object",
    "properties": {
      "city": { "type": "string" },
      "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
    },
    "required": ["city"]
  }
}

Keep the tool list small and focused. Agents with 15 overlapping tools call the wrong one more often than agents with 3 well-defined ones.

Step 2: Build the agent loop

The loop is the core of any agent. Pseudocode first, then real code:

  1. Send messages + tools to Claude
  2. If the response contains text only → done, return it
  3. If the response contains a tool_use block → run the matching function
  4. Append the tool result to the conversation as a tool_result
  5. Go back to step 1
async function runAgent(userMessage, tools, toolHandlers) {
  let messages = [{ role: "user", content: userMessage }];

  while (true) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      tools,
      messages,
    });

    const toolUse = response.content.find(b => b.type === "tool_use");

    if (!toolUse) {
      return response.content.find(b => b.type === "text").text;
    }

    const result = await toolHandlers[toolUse.name](toolUse.input);

    messages.push({ role: "assistant", content: response.content });
    messages.push({
      role: "user",
      content: [{
        type: "tool_result",
        tool_use_id: toolUse.id,
        content: JSON.stringify(result),
      }],
    });
  }
}

That's the whole pattern. Everything else — memory, retries, guardrails — is layered on top of this loop.

Step 3: Manage state and context

Every turn in the loop resends the full message history, including prior tool calls and results. Two practical issues show up fast:

const MAX_STEPS = 12;
let steps = 0;

while (steps++ < MAX_STEPS) {
  // ... loop body
}

Step 4: Handle errors inside the loop, not around it

A common mistake is wrapping the whole agent run in a try/catch and giving up on the first tool error. Instead, feed errors back to Claude as part of the tool result so it can retry or choose a different approach:

try {
  result = await toolHandlers[toolUse.name](toolUse.input);
} catch (err) {
  result = { error: err.message };
}

Claude will often self-correct — retry with different arguments, pick another tool, or explain the failure to the user — if you give it the error instead of crashing the loop.

Where API access management fits in

Once the agent logic works, the next problem is operational: issuing API keys per environment, streaming responses to a frontend, and tracking usage per customer or team member. This is where a layer like SubToAPI is useful — it turns your Claude access into a standard HTTPS API with sub_live_... keys, streaming support, and per-key usage metadata, so you're not building key rotation and billing tracking from scratch. Check the quickstart for setup and the tool use docs if you're running agent loops like the one above through it.

For teams shipping multiple agents, having usage broken down by key (not just by account) makes it much easier to see which agent or customer is driving cost — something worth planning for before you scale past a prototype.

A minimal checklist before shipping

Get these five right and most "my agent gets stuck" or "my agent hallucinates tool calls" issues disappear.

Questions

Do I need a special "agent API" from Claude? No. Agents are built using the standard Messages API with tools enabled. The agent behavior comes from your loop code, not a separate endpoint.

How many tools can an agent have? There's no hard technical limit, but accuracy drops as tool count and overlap increase. Most well-functioning agents use 3–8 clearly differentiated tools rather than a large generic toolkit.

What's the difference between a chatbot and an agent here? A chatbot responds once per user message. An agent can take multiple internal steps — calling tools, reading results, deciding next actions — before producing a final response, all within a single user-facing turn.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →