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:
| Type | What it stores | How |
|---|---|---|
| Working | the current conversation | the context itself |
| Episodic | what happened in previous sessions | summary + database |
| Semantic | facts and preferences of the user | vector 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:
- Does each agent have different tools? If not, it is a prompt.
- Do they need separate contexts? If they share everything, it is a prompt.
- 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
| Name | What it is | What it is for |
|---|---|---|
| Function calling / tool use | the model returns JSON with the function and its arguments | what you implemented in stage 12, standardized |
| MCP (Model Context Protocol) | an open protocol for connecting models to tools and data | an MCP server works with any compatible client; it avoids reimplementing every integration |
| Structured output | forcing the output to follow a JSON schema | decoding gets constrained: tokens that would break the schema have zero probability |
| Computer use | the model sees screenshots and returns clicks and keystrokes | tools 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.
| Framework | Approach | When it fits |
|---|---|---|
| LangChain | the most veteran and complete | rapid prototyping; it has a reputation for over-abstracting |
| LangGraph | explicit state graphs | flows with cycles and fine control; what gets used when LangChain falls short |
| LlamaIndex | focused on RAG and ingestion | your problem is mostly retrieving documents |
| CrewAI | agents with roles, "team" style | declarative, readable multi-agent |
| AutoGen | conversation between agents | research, debate patterns |
| Semantic Kernel | Microsoft's, heavily typed | .NET and Java ecosystems |
| PydanticAI | strict typing with Pydantic | you want strong validation and little magic |
| No framework | your own loop | more 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
| Failure | What you see | Defence |
|---|---|---|
| Infinite loops | the agent repeats the same action | step limit and repetition detection |
| Cost explosion | one query costs 40 times the normal | a token budget per session, with a cut-off |
| Compounding errors | each step degrades things a little | fewer steps, verification between them |
| Badly called tool | invented arguments | strict schemas and validation before executing |
| Prompt injection | a web page tells it what to do | least privilege, isolation, human confirmation |
| Goal drift | it ends up doing something else | remind it of the task on every round |
| Overconfidence | it says it finished and it did not | external verification, always |
Security: the non-negotiables
- Never
eval()orexec()on model output. Parse with a strict schema and a whitelist of tools. - Least privilege. An agent that reads email does not need to be able to send it.
- Human confirmation for anything irreversible: deleting, paying, publishing, sending.
- Isolation for any code execution, in a container with no network.
- Log everything. Without traces you cannot debug or audit.
- 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 steps | an ordinary script |
| you only need information from your documents | RAG, no agent |
| you need an answer that is 100% reliable | deterministic code |
| cost matters | one well-made call |
| it has to answer in under a second | a small model, no loop |
| you cannot verify the result | rethink 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:
| Add | Where you would touch it | Difficulty |
|---|---|---|
| More tools | the HERRAMIENTAS dictionary | trivial |
| Multiple rounds | wrap the loop in a while with a limit | easy |
| Memory | store summaries between sessions + the RAG from 12.1 | medium |
| Structured output | a mask over the logits driven by a grammar | medium |
| Supervisor | an agent whose "tools" are other agents | medium |
| Traceability | log every round with its cost | easy, and do this first |
What to take away
- An agent is a loop. There is nothing else. You built it in stage 12.
- The intelligence is shared between the model and your code. The code does more than people think.
- Errors compound. Five steps at 90% give you 59%.
- Multi-agent is almost never necessary. Start with one.
- Without verification there is no agent, there is a machine for generating work somebody will have to review.