Skip to content
AI from Scratch
EN

Agents and multi-agent systems

In stage 12 you built an agent: a model that, instead of calculating, writes [suma 23 41], your code runs it and hands the result back. It went from 0% to 91% accuracy.

That five-line loop is everything. This document explains what has been built on top of it, what each thing is called, and — this matters — when not to use agents.


1. What an agent is, without the marketing

An agent is a language model inside a loop, with permission to execute actions and see their results.

That is it. No consciousness, no autonomy, no will. A while.

while it is not done and the budget is not exhausted:
    1. generate text
    2. has it asked for a tool?  →  stop generating
    3. EXECUTE IT (your code does this, not the model)
    4. paste the result onto the context
    5. generate again

The only thing the model does is predict the next token. That those tokens form [suma 23 41] and that your program reacts to them is an agreement between you and it, taught during training.

The uncomfortable consequence: an agent does not "decide" to act. It generates text resembling the text you trained it on, and your code takes it seriously. All the security in an agent system lives in your code, not in the model.


2. The patterns, in order of appearance

ReAct (Reason + Act), 2022

The founding pattern. The model alternates thought and action:

Thought:     I need to know the population of Lugo.
Action:      search("population of Lugo")
Observation: 97,000 inhabitants (2024)
Thought:     now I can compare it with Ourense.
Action:      search("population of Ourense")
...
Thought:     I have the data now. I will answer.
Answer:      Lugo has about 97,000 and Ourense about 105,000.

Why it works: the "Thought" tokens are not decoration. Every generated token is a complete pass through the network, so writing the reasoning out is literally thinking more before deciding.

Planning up front

Instead of improvising step by step, the model writes a complete plan first and then executes it.

  • For: fewer round trips, cheaper, and you can show the user the plan before touching anything.
  • Against: if the plan was bad, it executes all of it anyway.
  • In practice: hybrid. Plan, execute, and replan when something fails.

Reflection and self-criticism

The agent generates, criticizes itself and retries.

It works when there is an external signal: the tests fail, the compiler complains, the API returns an error.

It does not work when it criticizes itself with nothing objective to go on. A model reviewing its own answer with no new information tends to confirm itself. What looks like introspection is another plausible generation.

Practical rule: reflection is only worth it if there is a verifier. If you cannot check automatically whether it is right, self-criticism is theatre.

Memory

An agent with no memory repeats its entire context at every step, and that context fills up. The three levels:

TypeWhat it storesHow
Workingthe current conversationthe context itself
Episodicwhat happened in previous sessionssummary + database
Semanticfacts and preferences of the uservector search (RAG)

The classic failure: putting everything into the context "just in case". It costs money, adds latency and hurts quality through the "lost in the middle" effect. Retrieving a little, well, beats putting everything in.


3. Multi-agent: several models talking to each other

The patterns in use

Supervisor and workers — the most common and the one that works best.

            ┌── researcher  (finds information)
supervisor ─┼── writer      (writes)
            └── reviewer    (checks)

One agent coordinates, distributes and assembles. Each worker has a single job and its own tools.

Pipeline — one's output, the next one's input. Deterministic, easy to debug, no surprises. If your problem fits here, use this.

Debate — several agents argue and a judge decides. Improves reasoning... and multiplies the cost by the number of participants.

Swarm — agents handing control to each other with no hierarchy. Flexible, and very hard to debug.

The question almost nobody asks

Do you really need several agents?

An awful lot of multi-agent systems are one well-written prompt dressed up as an architecture. Before building five agents, ask yourself:

  1. Does each agent have different tools? If not, it is a prompt.
  2. Do they need separate contexts? If they share everything, it is a prompt.
  3. The cost multiplies by 5 in exchange for what measured improvement?

Errors compound. If each agent is right 90% of the time, a chain of five is right 59% of the time. Adding agents usually subtracts reliability rather than adding it.


4. Current protocols and standards

NameWhat it isWhat it is for
Function calling / tool usethe model returns JSON with the function and its argumentswhat you implemented in stage 12, standardized
MCP (Model Context Protocol)an open protocol for connecting models to tools and dataan MCP server works with any compatible client; it avoids reimplementing every integration
Structured outputforcing the output to follow a JSON schemadecoding gets constrained: tokens that would break the schema have zero probability
Computer usethe model sees screenshots and returns clicks and keystrokestools whose "API" is a screen

On structured output, which is prettier than it looks: the model is not asked to "please" return valid JSON. The sampling is modified so it can only choose tokens that keep the JSON valid.

With what you know from stage 08, you can already see how: it is setting the logits of the forbidden tokens to -infinity, before the softmax. Just like the causal mask, but with a grammar.


5. The framework ecosystem

With a warning up front: this is the corner of AI that changes fastest and ages worst. What matters are the concepts, not the library.

FrameworkApproachWhen it fits
LangChainthe most veteran and completerapid prototyping; it has a reputation for over-abstracting
LangGraphexplicit state graphsflows with cycles and fine control; what gets used when LangChain falls short
LlamaIndexfocused on RAG and ingestionyour problem is mostly retrieving documents
CrewAIagents with roles, "team" styledeclarative, readable multi-agent
AutoGenconversation between agentsresearch, debate patterns
Semantic KernelMicrosoft's, heavily typed.NET and Java ecosystems
PydanticAIstrict typing with Pydanticyou want strong validation and little magic
No frameworkyour own loopmore often than people think

My honest recommendation: start with no framework. The loop in stage 12 is 30 lines. When something specific starts to hurt — retries, observability, branching — adopt the tool that solves that pain. Adopting a framework before you have the problem is buying somebody else's abstractions.


6. What goes wrong, and it goes wrong often

FailureWhat you seeDefence
Infinite loopsthe agent repeats the same actionstep limit and repetition detection
Cost explosionone query costs 40 times the normala token budget per session, with a cut-off
Compounding errorseach step degrades things a littlefewer steps, verification between them
Badly called toolinvented argumentsstrict schemas and validation before executing
Prompt injectiona web page tells it what to doleast privilege, isolation, human confirmation
Goal driftit ends up doing something elseremind it of the task on every round
Overconfidenceit says it finished and it did notexternal verification, always

Security: the non-negotiables

  1. Never eval() or exec() on model output. Parse with a strict schema and a whitelist of tools.
  2. Least privilege. An agent that reads email does not need to be able to send it.
  3. Human confirmation for anything irreversible: deleting, paying, publishing, sending.
  4. Isolation for any code execution, in a container with no network.
  5. Log everything. Without traces you cannot debug or audit.
  6. A hard budget. Of time, of tokens and of money.

7. When NOT to use an agent

This section is worth more than the six before it.

If...Use this instead
the task always follows the same stepsan ordinary script
you only need information from your documentsRAG, no agent
you need an answer that is 100% reliabledeterministic code
cost mattersone well-made call
it has to answer in under a seconda small model, no loop
you cannot verify the resultrethink the problem

An agent is the right tool when the steps are NOT known in advance and the result CAN be verified.

If you know the steps, write a program. If you cannot verify, do not automate.


8. How to build it yourself, with what you already have

Your stage 12 has the loop, the parsing and the executor. To take it further:

AddWhere you would touch itDifficulty
More toolsthe HERRAMIENTAS dictionarytrivial
Multiple roundswrap the loop in a while with a limiteasy
Memorystore summaries between sessions + the RAG from 12.1medium
Structured outputa mask over the logits driven by a grammarmedium
Supervisoran agent whose "tools" are other agentsmedium
Traceabilitylog every round with its costeasy, and do this first

What to take away

  1. An agent is a loop. There is nothing else. You built it in stage 12.
  2. The intelligence is shared between the model and your code. The code does more than people think.
  3. Errors compound. Five steps at 90% give you 59%.
  4. Multi-agent is almost never necessary. Start with one.
  5. Without verification there is no agent, there is a machine for generating work somebody will have to review.

Next: 14-roles-profesionales.md