How to Build an AI Agent (2026): From a Simple Loop to Tools and Review Steps

How to build an AI agent: start with one model call, add a loop, give it tools, set stop rules, then add a review step. Code included, plus what's hard.

How to build an AI agent, in one line: put a language model in a loop, give it a few well-described tools, stop it after a set number of turns, and check its work before you trust the result. That's a working agent in about 70 lines of Python. The hard part is everything after the first demo.

An AI agent is a program where the model decides its own next step. You give it a goal. It picks a tool, reads the result, and picks again until it's done. Anthropic describes agents as systems where models "dynamically direct their own processes and tool usage," as opposed to workflows that follow fixed code paths (Anthropic, Building effective agents, Dec 2024).

This guide is for developers and technical founders. We start with the smallest thing that works and add one piece at a time. At each step we say what it fixes and what it costs.

The Short Answer

  1. Pick one job. A narrow task with a clear "done."
  2. Start with one model call. If a single good prompt does the job, stop there.
  3. Add the loop. Call the model, run the tool it asks for, send back the result, repeat.
  4. Add tools carefully. Two or three, read-only first, with clear descriptions.
  5. Set stop rules. A turn limit, and a human check before anything risky.
  6. Add a review step. A second pass that checks the answer against the task.
  7. Test it on real cases. Keep a small set of tasks with known good answers.
StepWhat you addWhat it fixesWhat it costs
One callA clear promptMost simple tasksAlmost nothing
The loopRepeat until doneTasks with unknown stepsLatency and tokens
ToolsFunctions the model can callAccess to real data and actionsTool design and error handling
Stop rulesTurn limits, approval gatesRunaway loops, risky actionsSome autonomy
Review stepA second check on the outputConfident wrong answersOne more model call
Test setReal tasks with known answers"It worked once"Time to build and maintain

The five-rung agent ladder, from one model call to a review step

Step 1: Pick One Job (and Check You Need an Agent)

Start with the job, not the framework. "Answer questions about our docs." "Triage new support tickets." "Find the setup steps a new hire needs." One job, one clear finish line.

Then ask whether you need an agent at all. Anthropic's advice is to find the simplest solution and only add complexity when it's needed. Agents "trade latency and cost for better task performance," and for many apps a single well-built model call is enough (Anthropic).

OpenAI's guide makes the same point from the other side. It says agents fit tasks that involve complex decisions, unstructured data, or brittle rule-based systems. Otherwise "a deterministic solution may suffice" (OpenAI, A practical guide to building agents, 2025).

A quick test: if you can write the steps down in advance, build a workflow (fixed code that calls the model at set points). If the steps depend on what the model finds along the way, build an agent.

Step 2: Build the Loop

Every agent runs the same loop:

  1. Send the model the task and the list of tools.
  2. If the model asks for a tool, run it.
  3. Send the result back.
  4. Repeat until the model answers without asking for a tool.

The agent loop: model, tool call, result, repeat until done

With Anthropic's API, the model signals a tool request with stop_reason: "tool_use" and one or more tool_use blocks. Your code runs each one and replies with a tool_result block that carries the matching tool_use_id (Claude tool use docs). OpenAI's API has the same shape under a different name, function calling.

Here's a complete agent that reads a folder of docs and answers a question about them. It's Python with Anthropic's SDK (pip install anthropic).

from pathlib import Path
import anthropic

client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY
MODEL = "claude-opus-5-5"        # check Anthropic's models page for current IDs
MAX_TURNS = 10                   # stop rule: never loop forever

# 1. Put only documents you intend to share in ./docs.
docs = Path("./docs")
FILES = {
    p.name: p for p in docs.iterdir()
    if not p.is_symlink() and p.is_file() and p.suffix in {".txt", ".md"}
}

def list_files() -> str:
    return "\n".join(sorted(FILES))

def read_file(path: str) -> str:
    with FILES[path].open(encoding="utf-8") as source:
        return source.read(5000)

TOOLS = {"list_files": list_files, "read_file": read_file}

# 2. The tool descriptions the model reads
TOOL_SPECS = [
    {
        "name": "list_files",
        "description": "List the available document names. Use one of these names with read_file.",
        "input_schema": {
            "type": "object",
            "properties": {},
        },
    },
    {
        "name": "read_file",
        "description": "Read a text file. Returns at most 5,000 characters.",
        "input_schema": {
            "type": "object",
            "properties": {"path": {"type": "string", "description": "An exact document name from list_files"}},
            "required": ["path"],
        },
    },
]

# 3. The loop
def run_agent(task: str) -> str:
    messages = [{"role": "user", "content": task}]
    for _ in range(MAX_TURNS):
        response = client.messages.create(
            model=MODEL, max_tokens=2048, tools=TOOL_SPECS, messages=messages
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":   # no tool requested: it's done
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            try:
                output = TOOLS[block.name](**block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
            except Exception as e:   # errors go back to the model, phrased as a fix
                results.append({
                    "type": "tool_result", "tool_use_id": block.id, "is_error": True,
                    "content": f"Error: {e}. Check the path with list_files and try again.",
                })
        messages.append({"role": "user", "content": results})

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

print(run_agent("Read the files in ./docs and list every setup step a new developer needs."))

That's the whole pattern. Three things in it matter more than they look:

  • The turn limit. Without MAX_TURNS, a confused model can loop until your bill stops it. Anthropic notes it's common to add stopping conditions "such as a maximum number of iterations" to keep control.
  • Errors go back to the model. A crash stops the agent. An error message that says what to try next lets it recover.
  • The output is capped. Dumping a 2 MB file into the conversation is the fastest way to confuse a model and burn tokens.

Model choice: OpenAI's guide suggests prototyping with the most capable model to set a baseline, then trying smaller models to see where they still hold up. That's good advice whichever provider you use.

Step 3: Add Tools (Fewer and Better)

Tools are where agents get useful and where most of the work goes. A tool is just a function plus a description. The model only sees the description, so that's what you're really designing.

Anthropic's engineering team calls this the agent-computer interface and says it deserves as much care as a human UI. Their guide to writing tools for agents (Sept 2025) boils down to a few rules:

  • Build a few tools for real workflows. Don't wrap every API endpoint. "More tools don't always lead to better outcomes."
  • Write descriptions like you're onboarding a new teammate. Say when to use the tool, what the inputs mean, and what comes back. Use clear names like user_id, not user.
  • Return what the agent needs, not everything. Paginate, filter, or truncate big results.
  • Make errors actionable. "File not found. Use list_files to see valid paths" beats a stack trace.
  • Make mistakes hard. In Building effective agents, Anthropic describes switching a tool to require absolute file paths, which stopped a whole class of path mistakes in its coding agent.

Start read-only. Tools that look things up can't break anything. Add tools that write, send, pay, or delete only after the read-only version works, and put a human check in front of them.

Don't build every connector yourself. The Model Context Protocol (MCP) is an open standard for connecting AI apps to tools and data. Its docs describe it as "a USB-C port for AI applications." If an MCP server already exists for the system you need, your agent can use it instead of a custom tool. We explain how it works in What Is an MCP and Why Do Coding Agents Need It?

Step 4: Set Stop Rules and Human Checks

An agent that can act needs limits on how it acts. OpenAI's guide names two triggers for handing control back to a person (OpenAI):

  • Too many failures. Set limits on retries or actions. Past the limit, escalate.
  • High-risk actions. Anything "sensitive, irreversible, or [with] high stakes" should get a human check "until confidence in the agent's reliability grows." Their examples are canceling orders, large refunds, and payments.

In code, that's simple. Keep a list of risky tools. When the model asks for one, pause and ask a person before running it. Log every tool call so you can see what happened later.

Watch what your tools read, too. If your agent reads web pages, emails, or user uploads, that text can contain instructions aimed at the model. OWASP lists prompt injection as the top risk for LLM apps (OWASP LLM01). The practical defense is to limit what the agent can do, not just what it reads. An agent that can only read can't be talked into deleting anything.

Step 5: Add a Review Step

Agents fail in a specific way. They finish with a confident answer that's wrong. A review step catches a lot of that.

For a first check, give a second model the task and the answer. Ask it to flag any part of the request the answer skipped. This checks coverage. To verify facts, compare the answer with the source documents.

def review(task: str, answer: str) -> str:
    check = client.messages.create(
        model=MODEL, max_tokens=500,
        messages=[{"role": "user", "content":
            f"Task: {task}\n\nAnswer: {answer}\n\n"
            "Does the answer address each part of the task? Grade coverage only. "
            "Reply PASS or FAIL, then one line on why."}],
    )
    return check.content[0].text

If it fails, send the reason back to the agent and let it try again, with a limit. Anthropic calls this pattern evaluator-optimizer: one model generates, another critiques, in a loop.

A real check beats a model's opinion. If the agent writes code, run the tests. If it fills a form, validate the fields. If it answers from documents, check that the quotes appear in the source. Use a model reviewer for the things you can't check with code. We go deeper on this in how to set up quality gates for AI-generated code.

Step 6: Test It on Real Tasks

"It worked when I tried it" isn't a test. Write down 10 to 20 real tasks with answers you know are right. Run the agent on all of them every time you change a prompt, a tool, or the model.

Anthropic's tool-writing guide recommends realistic, multi-step test tasks with answers you can verify, and tracking accuracy, tool calls, runtime, and errors. Then read the transcripts. The transcript shows where the agent got lost, which a pass/fail score won't tell you.

What's Actually Hard

The loop is the easy part. Here's where teams spend their time.

What makes AI agents hard, and the fix for each

  • Knowing when it's done. The model decides when to stop. Without a clear finish line in the task, it stops too early or wanders.
  • Errors that compound. A small mistake on step 2 becomes a wrong answer on step 9. Anthropic flags compounding errors as a core risk of agents and recommends testing in sandboxed environments.
  • Context that fills up. Every tool result stays in the conversation. Long runs get slow, expensive, and less focused. Cap tool output and summarize old steps.
  • Tool design. Most "the model is dumb" bugs turn out to be a vague tool description or a confusing result.
  • Cost and speed. Each loop turn is another API call. A task that takes 15 turns costs roughly 15 calls, each carrying the growing conversation.
  • Trust. Giving an agent write access is a product decision, not just a code change. Earn it one tool at a time.

Frameworks: Do You Need One?

Not to start. Anthropic recommends calling the model API directly first, because frameworks add layers that "obscure the underlying prompts and responses," which makes debugging harder. If you use one, know what it does underneath (Anthropic).

When you outgrow the simple version, the main options are:

OptionWhat it gives youGood fit when
Raw API + your own loopFull control, nothing hiddenLearning, simple agents, custom needs
Claude Agent SDKThe same tools, agent loop, and context management that run Claude Code, in Python and TypeScriptAgents that work with files, code, and commands
OpenAI Agents SDKOpenAI's Python framework with tools, handoffs between agents, guardrails, and tracingTeams building on OpenAI models

Feature sets change fast, so check each one's docs before you pick. And start with one agent. OpenAI's guide recommends getting the most out of a single agent with tools before splitting work across several.

Where Unstoppable Code Fits

If the agent you want to build does software work in your own repos, like planning a change, writing code, running tests, and reviewing the result, you may not need to build it from scratch. That's what Unstoppable Code does.

Unstoppable Code runs Claude, Codex, and local Ollama models as coding agents on your Mac, each in its own git worktree so parallel agents don't overwrite each other. The pieces in this guide are built in:

  • The loop and the tools. Each chat is a full coding agent that reads files, runs commands, and edits code.
  • Human checks. You approve the agent's plan before it writes code, then review the diff and revert file by file.
  • Review steps. Pipelines chain agent steps with checks. They include an agent-and-shell-check loop, a quality gate that scores work against criteria and fails below a threshold, a step that pauses for human input, and retry and iteration limits. The bundled Code Review pipelines give every change a second look.
  • Your own accounts. Sign in with your Anthropic subscription or API key, and your ChatGPT login or OpenAI key.

And if you are building your own agent from scratch, it's a good place to build it. Run one agent on the tool code and another on the test set, in separate worktrees. If you're new to the vocabulary, start with What Is Agentic AI?


Frequently Asked Questions

How do I build an AI agent? Put a language model in a loop with a few tools. Send it the task, run any tool it asks for, send the result back, and repeat until it answers. Add a turn limit, a human check before risky actions, and a review step that checks the final answer.

Can I build an AI agent without a framework? Yes. A basic agent is a loop around the model API and a few Python or TypeScript functions, often under 100 lines. Anthropic recommends starting with the API directly so you can see every prompt and response.

What's the difference between an AI agent and a workflow? A workflow follows steps you wrote in code and calls the model at fixed points. An agent decides its own next step based on what it finds. Use a workflow when you can list the steps in advance, and an agent when you can't.

What programming language should I use to build an AI agent? Python and TypeScript have the most examples and official SDKs. Anthropic and OpenAI both publish SDKs in several languages, and any language that can make HTTP calls can run an agent loop.

How many tools should an AI agent have? Start with two or three that cover one workflow. Anthropic's engineering team notes that more tools don't always lead to better results, and overlapping tools can confuse the model.

How do I stop an AI agent from doing something dangerous? Limit what it can do. Start with read-only tools, require human approval before any action that writes, sends, pays, or deletes, cap the number of turns, and log every tool call.

What is MCP and do I need it to build an agent? MCP, the Model Context Protocol, is an open standard for connecting AI apps to tools and data. You don't need it for a simple agent, but it lets your agent use existing connectors instead of custom tool code.

How do I know if my AI agent is working? Build a small test set of real tasks with known good answers. Run it after every change, track how many pass, and read the transcripts of the failures.

Sources

Building effective agents, Anthropic, Dec 19, 2024. Writing effective tools for agents, Anthropic, Sept 11, 2025. Tool use with Claude, Anthropic docs. Agent SDK overview, Anthropic docs. A practical guide to building agents, OpenAI, 2025. OpenAI Agents SDK, OpenAI. What is the Model Context Protocol?, MCP docs. LLM01: Prompt Injection, OWASP GenAI Security Project. Docs accessed Nov 10, 2026.

Cookie preferences

We use optional cookies to improve the site