How to Build an AI Agent with Claude
How to Build an AI Agent with Claude
An AI agent is a program that uses a model like Claude not just to answer a question once, but to decide what to do next — call a function, fetch data, write a file, ask a follow-up — and keep doing that until a task is finished. Building one with Claude means wiring together three things: a loop that repeatedly calls the model, a set of tools Claude can invoke, and a way to track state across turns.
This is different from a chatbot, where the model just replies to messages. An agent has a goal, takes actions, observes the results of those actions, and decides whether to continue or stop. Claude is well suited to this because it supports structured tool use, long context windows, and reliable instruction-following, but the agent "brain" — the loop and the decision logic — is something you build around the API.
The Core Agent Loop
Every Claude-based agent follows the same basic pattern:
- Send the user's goal and conversation history to Claude.
- Claude responds with either a final answer or a request to use a tool.
- If it's a tool request, your code executes the tool and returns the result to Claude.
- Claude sees the result and decides what to do next — another tool call, or a final answer.
- Repeat until the task is done or you hit a safety limit (max turns, timeout, cost cap).
This loop is the entire architecture. Everything else — prompts, tool definitions, memory — feeds into it.
async function runAgent(goal) {
let messages = [{ role: "user", content: goal }];
for (let turn = 0; turn < 10; turn++) {
const response = await callClaude(messages);
if (response.stopReason === "tool_use") {
const result = await executeTool(response.toolCall);
messages.push({ role: "assistant", content: response.content });
messages.push({ role: "user", content: toolResultMessage(result) });
} else {
return response.content; // final answer
}
}
}
The callClaude function is where you hit the API. If you're using the raw Claude API, you need your own API key, SDK, and billing setup. If you're using SubToAPI, you point this call at https://api.subtoapi.app/v1/messages with a sub_live_ key instead, which is useful if you want agent usage tracked separately from your normal Claude account or shared across a team.
Defining Tools
An agent is only as useful as the actions it can take. Tools are JSON schemas describing a function name, a description, and input parameters. Claude decides when to call them based on the conversation and the tool descriptions — it never executes anything itself, it just tells you what it wants to run.
{
"name": "search_orders",
"description": "Look up a customer order by ID",
"input_schema": {
"type": "object",
"properties": {
"order_id": { "type": "string" }
},
"required": ["order_id"]
}
}
Keep tool descriptions specific. Vague descriptions lead to Claude calling the wrong tool or guessing parameters. If you're new to this, the tool use docs cover the request/response shape in detail, and it's worth reading before you write your first agent loop, since tool-calling bugs are usually schema problems, not model problems.
A few practical rules for tool design:
- One job per tool. A tool that "searches and updates" is harder for the model to use correctly than two separate tools.
- Return structured results. JSON back to Claude, not prose — it reasons about structured data more reliably.
- Fail loudly. If a tool errors, return the error as the tool result so Claude can adapt, rather than crashing the loop.
Managing State and Memory
Claude has no memory between API calls — your code is responsible for passing the full conversation history, including every tool call and result, on every request. For short tasks this is simple: just append to an array. For longer-running agents, you need to think about:
- Context length. Long tool-use chains can blow past context limits. Summarize or truncate older turns once you're several steps deep.
- Persistent memory. If an agent needs to remember facts across separate sessions (not just within one run), store them outside the model — a database row, a file, a vector store — and inject relevant pieces back into the prompt.
- Stopping conditions. Always cap the number of loop iterations and set a timeout. An agent that keeps calling tools without making progress will burn API calls indefinitely.
Streaming for Responsive Agents
If your agent has a UI, streaming the response token-by-token makes it feel responsive instead of frozen while Claude reasons through a multi-step task. This matters more for agents than chatbots because agent turns often take longer — there's a tool call, a wait for the tool result, then another model call. See streaming for the event format if you're building this on top of SubToAPI, where streaming works the same way as the standard Messages API.
Running Agents in Production
A few things separate a demo agent from one you can trust in production:
- Rate limits and retries. Agent loops make multiple API calls per task, so you hit rate limits faster than single-turn apps. Build retry logic with backoff.
- Per-task usage tracking. Know how many tokens and tool calls a given agent run consumed — this is how you catch runaway loops before they get expensive.
- Separate credentials per environment. Don't share one API key between your dev agent and production agent. If you're running Claude through SubToAPI, each team member or environment can get its own
sub_live_key, with usage visible per key in the dashboard — handy when multiple agents or multiple developers are hitting the same underlying Claude access. - Guardrails on actions. If a tool can write data or spend money, add a confirmation step or a dry-run mode before letting the agent execute it unattended.
Start small: one tool, a three-step loop, a hardcoded goal. Get that working end to end before adding more tools or longer chains. Most agent bugs come from unclear tool schemas or missing stopping conditions, not from the model itself.
Questions
Do I need a special "agent" API from Claude? No. Claude exposes a single Messages API with tool use support. The "agent" is the loop and tool logic you write around that API — there's no separate agent endpoint.
How many tools should an agent have? Start with as few as the task requires — often one or two. More tools increase the chance Claude picks the wrong one. Add tools only when the current set can't complete the task.
What's the main difference between a chatbot and an agent? A chatbot replies to messages. An agent takes actions via tools, observes results, and decides the next step on its own until the goal is met or it hits a stopping condition.