Almost every agent tutorial starts with the framework: install this, import that, declare three agents with fancy roles. It works in the demo and breaks on the first real case, because nobody understood what happens underneath.
This article goes the other way. We build an agent step by step, from scratch, and each step solves a problem the previous one left behind. By the end you know what each piece does, when a framework helps, and what has to be in place before you let the agent act on its own.
If the terms (loop, harnessStructure around the model in an agent: the run loop, tools, permissions, hooks and checks that turn answers into reliable work., guardrail, eval) still feel loose, the map of agentic AI concepts gives you the big picture. If the question is whether you really need an agent, start with AI agent or chatbot. Here the focus is hands-on.
An Analogy to Start
Think of an intern on their first day.
- You can ask a question and they answer. That's a model call.
- You can ask them to fill out a form instead of writing free text. That's structured output.
- You can give them access to a spreadsheet. That's a tool.
- You can say "handle this ticket and let me know when you're done". Now they decide the steps on their own: open the spreadsheet, check it, ask the system, try again. That's the agent.
And, like any intern, they need rules: no approving refunds above a certain amount without talking to you, no emailing customers without a review, and you check a sample of their work every week. Those rules are the guardrails, the human in the loop and the evals.

The Step-by-step Roadmap
Each step comes in only when the previous one isn't enough. Skipping steps is the most common way to end up with an expensive system nobody can debug.
| Step | What it solves | Sign you need the next one |
|---|---|---|
| 1. One model call | Text task with clear input and output | The answer comes back in an unpredictable format |
| 2. Structured output | An answer your code can read without breaking | The model needs data that isn't in the prompt |
| 3. One tool | Fetching data or taking a single action | You can't know up front how many steps the task has |
| 4. The loop | Open-ended task, with steps chosen by the model | The conversation gets long or needs to remember the user |
| 5. Memory and state | Continuity across turns and sessions | The agent can do something expensive or irreversible |
| 6. Guardrails and human in the loop | A limit on what the agent can do alone | You tweak the prompt and can't tell if it got better or worse |
| 7. Evals and observability | Measure, compare, find the cause of a failure | Only then think about multiple agents |
Anthropic's agents guide sums up the stance: find the simplest solution possible and only add complexity when needed. OpenAI's practical guide points the same way and recommends maximizing a single agent's capabilities before splitting the work.
Step 1: One Model Call
It sounds obvious, but a lot of what gets sold as an "agent" is just this: text goes in, the model processes it, text comes out. Summarizing a ticket, classifying an email, translating a product description.
If your task fits here, stop here. It's cheaper, faster and predictable. Put care into the prompt and understand how much it costs in tokens, because that cost multiplies at every step that follows.
Step 2: Structured Output
The trouble with free text shows up when your code has to use the answer. "Classify the ticket priority" can come back as "High", "high.", "Priority: high" or a whole paragraph. Your if breaks.
Structured output fixes that: you hand over a JSON Schema and the provider guarantees the answer follows it. OpenAI calls it Structured Outputs; Anthropic calls it structured outputs and explains that the guarantee comes from constrained decoding, meaning the model literally can't generate a token outside the format.
{
"type": "object",
"properties": {
"prioridade": { "type": "string", "enum": ["baixa", "media", "alta"] },
"motivo": { "type": "string" },
"precisa_humano": { "type": "boolean" }
},
"required": ["prioridade", "motivo", "precisa_humano"]
}Notice the precisa_humano field (needs a human). From step 2 on, the model can flag that it shouldn't decide alone. That idea comes back in step 6.
Step 3: One Tool
Now the model needs something that isn't in the prompt: an order's status, a customer's balance, the weather forecast. You declare a tool (also called function calling): name, description and parameter schema.
The point that confuses almost everyone: the model doesn't run the tool. It returns a request ("call buscar_pedido with id 4821") and stops. Your code runs it and sends the result back in the next message.
That's good news for security: every action goes through your code, where you validate parameters, check permissions and log what happened. If the tool calls another service, the same rules apply as for any integration: timeout, careful retries and idempotency, which I covered in resilience patterns.
A lesson from the Anthropic team: in the agent they built for the SWE-bench benchmark, they spent more time optimizing the tools than the overall prompt. The model got relative file paths wrong; they changed the tool to require absolute paths and the error went away. A tool's description and format are prompt too.
Step 4: The Loop
With one tool, the application still decides when to call the model again. The agent is born when you hand that decision to the model: as long as it asks for tools, your code runs them and sends the results back; when it answers without asking for anything, it's done.
Simon Willison put it in one sentence: an LLMAI model trained on large amounts of text to predict the next word, which lets it chat, summarize, translate and write code. agent runs tools in a loop to achieve a goal. The pattern has an academic name, ReAct (Yao et al., 2022): the model alternates reasoning and acting, and each tool result informs the next step.
The whole loop, in Python with no framework, using the Anthropic APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON. as an example (OpenAI's has the same shape):
import anthropic
client = anthropic.Anthropic()
FERRAMENTAS = [{
"name": "buscar_pedido",
"description": "Fetches the status and items of an order by its numeric id.",
"input_schema": {
"type": "object",
"properties": {"pedido_id": {"type": "integer"}},
"required": ["pedido_id"],
},
}]
EXECUTORES = {"buscar_pedido": lambda pedido_id: banco.pedido(pedido_id)}
MAX_PASSOS = 8
def rodar_agente(pergunta: str) -> str:
mensagens = [{"role": "user", "content": pergunta}]
for passo in range(MAX_PASSOS):
resp = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
system="You are the order support agent. Use the tools before stating any status.",
tools=FERRAMENTAS, messages=mensagens,
)
mensagens.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
resultados = []
for bloco in resp.content:
if bloco.type == "tool_use":
saida = EXECUTORES[bloco.name](**bloco.input)
resultados.append({"type": "tool_result", "tool_use_id": bloco.id, "content": str(saida)})
mensagens.append({"role": "user", "content": resultados})
return "I couldn't finish in time. I'll hand this over to a support agent."Three details that make a difference:
MAX_PASSOS(max steps): without it, a confused agent spins forever and burns money. Anthropic lists stopping conditions, such as a maximum number of iterations, as common practice.- The honest exit at the end: when it hits the limit, the agent hands the task to a person instead of making up an answer.
- The history grows with every turn. Each step resends everything, so the cost climbs fast. That's the topic of the next step.

Step 5: Memory and State
The model doesn't remember anything between calls. All "memory" is something your code stores and puts back into the context. In practice there are two kinds:
- Short term (conversation state): the message history and tool results of a session. The LangGraph docs call it thread memory and persist it with a checkpointer in a database, which lets you pause and resume.
- Long term: facts that hold across sessions, like user preferences or past decisions. They live in a separate store, organized by user or by topic, and enter the context only when relevant.
When the conversation grows too much, the model gets worse: Anthropic calls this context rot, where the ability to recall information from the context drops as it grows. The most common ways out:
- Summarize the old history near the limit (compaction).
- Clear old tool results that have already been used.
- Keep notes outside the window and load them when needed. Anthropic's memory tool does this with a directory of files that the model itself reads and writes, always executed on your application's side.
This care about what goes into the window is what people now call context engineering. If long-term memory turns into a document base, you've arrived at RAGTechnique that retrieves relevant passages from a document base and hands them to the model with the question, so it answers from sources, not memory alone., and the structure of a RAG project shows how to organize it.
Step 6: Guardrails and Human in the Loop
Up to here the agent only read data. The moment it acts (sends an email, edits a record, issues a refund), the nature of the risk changes. OWASP calls this Excessive Agency: harmful actions carried out based on unexpected, ambiguous or manipulated model output. It lists three causes: too much functionality, too many permissions and too much autonomy.
OpenAI's guide describes guardrails as a layered defense: no single one is enough, several together make the agent more resilient.
| Layer | What it does | Example |
|---|---|---|
| Input | Blocks out-of-scope or malicious requests | Relevance classifier, personal data filter |
| Permission | The tool only reaches what it needs | Read-only token; refunds capped by amount |
| Parameters | Your code validates before running | pedido_id must belong to the logged-in user |
| Output | Checks before showing or sending | No other customer's data, no promises outside policy |
| Human | Approves what is expensive or irreversible | Refunds above $500 go to an approval queue |
The two human-in-the-loop triggers OpenAI recommends are simple to implement: exceeding a failure threshold (the agent tried three times and couldn't do it) and high-risk actions (sensitive, irreversible or expensive). Frameworks like LangGraph have interrupts for this: the graph pauses, saves its state and resumes when the person answers.
One specific warning: if the agent reads outside content (email, web page, a document the user uploaded), that text can contain disguised instructions. Simon Willison called the combination of access to private data, exposure to untrusted content and the ability to send something out the lethal trifecta. With all three together, a malicious text can make the agent leak data. Cut at least one of the three.
Step 7: Evals and Observability
You tweak the prompt, swap the model, change a tool's description. Did it get better? Without evals, the answer is "seems like it", and an agent is exactly the kind of system where "seems" fools you.
An eval is a test for an AI system: an input, plus logic that grades the output. Anthropic's advice for getting started is concrete: 20 to 50 simple tasks drawn from real failures are a great start. You don't need a thousand cases or an expensive platform.
Two metrics that change the conversation:
- pass@k: the chance of getting it right at least once in k tries. Good for an assistive tool, where someone picks the best output.
- pass^k: the chance of getting all k tries right. That's the one that matters for a customer-facing agent. An agent that's right 75% of the time gets three out of three in only about 42% of cases (0.75 × 0.75 × 0.75).
Observability is the other side: logging every step (prompt, tool called, parameters, result, tokens, time) so you can understand why a run went wrong. Anthropic says it could only diagnose failures in its research system systematically after adding full tracing in production. OpenTelemetry has conventions for generative AI, still in development status; Langfuse and LangSmith combine tracing and evals; promptfoo, Ragas and DeepEval handle the tests.
Cost and Latency: The Math Nobody Does in the Prototype
Every turn of the loop is a model call with the entire history. A 6-step agent pays for the initial question 6 times, plus all the accumulated tool results. Anthropic's numbers give the scale: agents use about 4 times more tokens than a chat conversation; multi-agent systems, about 15 times.
What brings cost and time down, in order of effort:
- Fewer steps: tools that return the data ready to use, instead of three calls to build the same result.
- Lean results: the tool returns only the useful fields, not the API's entire JSON.
- Prompt caching: the system prompt and the tool list repeat on every turn; providers charge much less for the repeated part.
- The right model per stage: classify and route with a small model, reason with the big one.
- Run independent tools in parallel: the model can request several at once, and your code runs them together.
Latency is part of the experience too. Showing progress ("checking the order...") with streaming makes 10 seconds feel much shorter.
Deploy: The Agent Is a Service Like Any Other
When it's time to ship, almost everything is regular back-end engineering:
- An API in front, with authentication. The agent handles a request like any endpoint; the API concepts apply in full.
- Long runs go to a queue. A task that takes minutes doesn't fit in an HTTP request: it goes into a queue, a worker runs the loop and the client follows along via polling or events.
- State in a database, not in process memory. If the server restarts halfway through, the checkpointer picks up where it left off.
- Secrets out of the code and each tool with the minimum credential.
- Per-user limits: caps on steps, tokens and cost per run and per day.
- Prompt and tool versions alongside the code, so you know which combination produced which result.
If the agent's tools need to be reused by other clients (Claude, ChatGPT, a code editor), the way to go is publishing them as an MCPOpen protocol that standardizes how AI apps connect to external tools and data: a server exposes actions and the agent discovers and calls them. server; the MCP concepts explain how.
Frameworks: When and Which
Anthropic's advice is to start with the API directly, because many patterns fit in a few lines, and, if you do use a framework, to understand the code it runs underneath. A framework starts to pay off when you need persistent state, pausing for approval, built-in tracing or multiple agents.
| Framework | Language | Strength | Version (Nov 21, 2026) |
|---|---|---|---|
| OpenAI Agents SDK | Python and TypeScript | Ready-made loop, handoffs, guardrails and tracing | 0.25.0 (PyPI), 0.22.0 (npm) |
| LangGraph | Python and TypeScript | Stateful graph, checkpoints and human interrupts | 1.2.24 (PyPI), 1.7.5 (npm) |
| Pydantic AI | Python | Typing and validation in the Pydantic style | 2.71.0 |
| Claude Agent SDK | Python | The Claude Code harness as a library | 0.2.187 |
| Google ADK | Python | Google's Agent Development Kit | 2.15.0 |
| CrewAI | Python | Role-based agents, team orchestration | 1.15.44 |
| Vercel AI SDK | TypeScript | One interface for many models, streaming on the web | 7.0.179 |
| Mastra | TypeScript | Agent and workflow framework for TypeScript | 1.85.0 |
If the question is agents in code versus a visual tool like n8n, I wrote a guide just on that: n8n or AI agents in code.
What About Multi-agent?
Several agents talking to each other is the picture everyone has of "agentic AIUse of language models that plan, call tools and decide the next step on their own to reach a goal, instead of only answering a question.", and it's the last step for a reason. Anthropic's research system, with a lead agent and subagents in parallel, outperformed a single agent by 90.2% on its internal eval. In exchange, it used about 15 times the tokens of a chat, and Anthropic itself says that tasks where everyone needs the same context, or with lots of dependencies between agents, aren't a good fit for that design.
That same month, Cognition published the counterpoint: share the full context, and remember that every action carries implicit decisions; conflicting decisions between agents lead to bad results. Their recommendation is a linear, single-threaded agent.
The two positions meet at one practical point: multi-agent pays off for work that splits into independent parts (searching several sources at once, reviewing several files). For sequential, interdependent tasks, a single well-equipped agent wins.
Quick check
Frequently Asked Questions
Do I need a framework to build an agent?
Not to get started. The loop fits in about 30 lines with the provider's API. A framework starts to pay off when you need persistent state, pausing for human approval, built-in tracing or multiple agents.
What's the difference between an agent and an AI workflow?
In a workflow, the code defines the sequence of steps and the model executes each one. In an agent, the model decides the next steps and which tools to use. A workflow is more predictable; an agent handles open-ended tasks better.
How many tools can an agent have?
There's no magic number, but each tool takes up context and raises the chance of a wrong pick. Start with a few, well described, and split them into subagents or load them on demand when the list grows.
How do I keep the agent from making up answers?
Instruct it to check the tool before stating any data, validate the output with a schema, have it cite where the information came from, and build evals with cases where the right answer is "I don't know".
Can an agent run on a small or local model?
Yes, as long as the model is good at calling tools. A common approach is to use the small model to classify and route, and the big one only for the hard steps. If the behavior needs to change consistently, fine-tuning becomes an option.
References
- Building effective agents, Anthropic, 2024
- A practical guide to building agents, OpenAI, 2025
- ReAct: Synergizing Reasoning and Acting in Language Models, Yao et al., 2022
- Agents, a definition, Simon Willison, 2025
- Tool use, documentation, Anthropic
- Structured outputs, Anthropic
- Structured Outputs, OpenAI
- Memory tool, Anthropic
- Memory in LangGraph
- Interrupts in LangGraph
- Effective context engineering for AI agents, Anthropic, 2025
- MemGPT: Towards LLMs as Operating Systems, Packer et al., 2023
- LLM06:2025 Excessive Agency, OWASP
- OWASP Top 10 for Agentic Applications, 2025
- The lethal trifecta, Simon Willison, 2025
- Demystifying evals for AI agents, Anthropic, 2026
- How we built our multi-agent research system, Anthropic, 2025
- Don't Build Multi-Agents, Cognition, 2025
- GenAI semantic conventions, OpenTelemetry