Skip to content

How to build an AI agent from scratch: a step by step roadmap, from the loop to production

An agent built step by step: model call, structured output, tool, loop, memory, guardrails, human in the loop and evals. With code, costs and when to pick a framework or multi-agent.

Ramon Gomes 19 min read Level: Intermediate

Also available in: Español, Français, Português

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.

Office desk with an open notebook, a to-do list with items crossed off, a phone and a document tray, a person's hands sorting papers
A good agent works like a good intern: a clear goal, access only to what it needs, and it knows when to call someone.

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.

Isometric staircase with seven numbered steps: Model call; Structured output; One tool; The loop; Memory and state; Guardrails and human; Evals and traces. Protection and measurement come before any multi-agent..
Climb one step at a time. Plenty of good applications stop at the third.
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.

json
{
  "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.

Four-stage timeline with a phone, model, server and answer: User: Where is my order 4821?; Model: asks: get_order(4821); Your code: runs it and returns: "in transit"; Model: Your order is in transit..
The model asks, your code runs it. That's why you stay in control of what actually happens.

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.

Four-station circuit with an exit to the final answer: Model decides → Asks for tool → Code runs it → Result returns → Final answer. step 3. limit: 8 steps.
The loop keeps spinning while the model asks for tools. The step limit is the handbrake.

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):

python
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.
Cartoon of a robot running inside a hamster wheel made of arrows, holding several tools at once, while a calm person next to it holds a stop sign and a clock
Without a step limit, a confused agent runs in circles and the bill shows up at the end of the month.

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.
Comparison of a phone conversation and a memory archive: Short term: this conversation: summary: address change for order 4821; confirmed; and the delivery date?. Long term: across sessions: prefers WhatsApp; customer since 2023. comes back when the topic shows up.
Agent memory is a well-kept filing system: what matters now stays on the desk, the rest goes in the drawer and comes back when needed.

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.

Two tracks cross protection layers and reach a human gate: Input: scope and abuse; Permission: least access; Parameters: validation; Output: before sending; Human: risky action. order lookup. $2,000 refund: awaiting approval → approved → done.
No layer is perfect. An irreversible action always goes through a person.
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.

Three illustrated architectures and a horizontal token chart: Chat: baseline; Agent: ≈ 4×; Multi-agent: ≈ 15×. Source: Anthropic, multi-agent research system (2025).
Every turn of the loop resends the history. Multi-agent multiplies that by each subagent.

What brings cost and time down, in order of effort:

  1. Fewer steps: tools that return the data ready to use, instead of three calls to build the same result.
  2. Lean results: the tool returns only the useful fields, not the API's entire JSON.
  3. Prompt caching: the system prompt and the tool list repeat on every turn; providers charge much less for the repeated part.
  4. The right model per stage: classify and route with a small model, reason with the big one.
  5. 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

1. Who runs a tool declared to the model?
Show answer

Answer: Your application's code, which sends the result back to the model

With client-side tools, the model only requests the call. Your application runs it, validates it and logs it.

2. The agent is right 80% of the time. What's the chance it gets 3 runs in a row right?
Show answer

Answer: About 51%

That's pass^3: 0.8 × 0.8 × 0.8 = 0.512. That's why consistency matters as much as average accuracy.

3. What should happen when the agent hits the step limit without finishing?
Show answer

Answer: End with an honest answer and hand it over to a person

The limit exists to cut cost and infinite loops. On the way out, the agent hands the task back instead of guessing.

4. When is it worth going multi-agent?
Show answer

Answer: When the work splits into independent parts that can run in parallel

Multi-agent uses far more tokens and suffers from split context. It pays off for parallel work, like broad research.

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

Source: https://ramongomessilva.com.br/blog/build-ai-agent-from-scratch · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. How to build an AI agent from scratch: a step by step roadmap, from the loop to production. Ramon Gomes, 23 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/build-ai-agent-from-scratch. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 23). How to build an AI agent from scratch: a step by step roadmap, from the loop to production. Ramon Gomes. https://ramongomessilva.com.br/blog/build-ai-agent-from-scratch

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026buildaiagent,
  author = {Gomes, Ramon},
  title = {{How to build an AI agent from scratch: a step by step roadmap, from the loop to production}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-23},
  url = {https://ramongomessilva.com.br/blog/build-ai-agent-from-scratch},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles