Module 1 · Multi-agent system foundations

Agent anatomy: LLM, tools, memory, control loop

7 min read

Before orchestrating dozens of agents, you need to know exactly what one agent is. The word gets applied to everything: a chatbot, a script calling an API, an automated workflow… In this course we use a precise definition, because it drives every architecture decision that follows.

About the companion code. The Atlas repository that ships with this course uses French comments and French system prompts. The code snippets in this English edition are translated; behavior is identical, since models work equally well with prompts in either language.

Workflow or agent: who is driving?

The fundamental distinction is who decides the control flow.

  • In a workflow, your code decides. The model is called at predefined steps ("summarize this text", "classify this ticket"), and the sequence is written in advance.
  • In an agent, the model decides. At each turn it chooses which action to take, with which tool, and when it is done.
Single callWorkflowAgent
Who decides the next step?NobodyYour codeThe model
Number of LLM calls1Fixed or boundedVariable
PredictabilityHighestHighLower
Best forExtraction, classificationKnown pipelinesOpen-ended tasks that are hard to specify

This is not a prestige ladder. A good engineer picks the simplest level that solves the problem. Most business needs are met by a single call or a workflow; you move to an agent only when the task is genuinely open-ended.

The four components of an agent

Every agent, whatever the framework, combines four elements.

1. The model (the "brain")

It reads the context, reasons, and produces either a final answer or an action request. Recent models reason adaptively: they decide how much thinking a step needs, including between two tool calls. Your main lever is no longer a "thinking budget" but the effort level (low, medium, high…), which trades thoroughness against cost.

2. Tools (the "hands")

A tool is a function the model can ask to run: search a knowledge base, read a file, call an API. The model executes nothing itself: it emits a structured request (tool name + JSON arguments), and your program — the harness — executes it and returns the result.

This matters enormously for security: your code always performs the action. You can therefore validate, filter, log or refuse every action.

3. Memory

There are three levels:

  • Working memory: the message history of the current conversation (instructions, tool calls, results).
  • Task state: structured data you maintain alongside (plan, intermediate results, counters). In LangGraph, this is the State object.
  • Long-term memory: what survives from one session to the next (preferences, learned facts), stored in a database.

4. The control loop

This is the engine: call the model, execute the requested tools, return the results, repeat — until the model answers without requesting a tool, or a limit is reached.

A hand-written agent loop

Nothing demystifies like code. Here is the core of examples/01_agent_loop.py, a complete research agent in about thirty lines:

def agent(question: str, max_steps: int = 8) -> str:
    messages = [{"role": "user", "content": question}]
    for _ in range(max_steps):  # hard bound: an agent never loops forever
        response = client().messages.create(
            model=MODEL,
            max_tokens=16000,
            system="You are a research assistant. Ground every claim in the documents "
            "returned by your tools and cite their IDs in square brackets.",
            tools=TOOLS,
            messages=messages,
        )
        if response.stop_reason == "refusal":
            return "Request declined by the model."
        # Append the COMPLETE response (thinking and tool_use blocks included)
        messages.append({"role": "assistant", "content": response.content})

        tool_calls = [b for b in response.content if b.type == "tool_use"]
        if not tool_calls:
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for call in tool_calls:  # all results go back in ONE single message
            output, is_error = run_tool(call.name, call.input)
            results.append({"type": "tool_result", "tool_use_id": call.id,
                            "content": output, "is_error": is_error})
        messages.append({"role": "user", "content": results})

    return "Stopped: maximum number of steps reached."

Every line encodes a production rule:

  1. max_steps — A hard bound. Without it, an agent going in circles burns your budget until it runs out.
  2. stop_reason == "refusal" — The model can decline a request. Always check the stop reason before reading the content.
  3. The full response.content — Send the model back its entire response, not just the text. Thinking blocks and tool-call blocks are part of its reasoning; truncating them degrades what follows.
  4. One message for all results — When the model requests several tools at once (parallel calls), return all tool_result blocks in the same message. Spreading them across messages implicitly teaches it to stop parallelizing.
  5. is_error — A tool error is not a crash: it is information. The model reads the error message and adjusts its strategy (another query, another ID).

SDK note. The Anthropic SDK offers a Tool Runner (client.beta.messages.tool_runner) that manages this loop for you — see examples/02_tool_runner.py. Writing the loop by hand once is still essential to understand what frameworks do, and for cases where you must control every turn.

The life cycle of a turn

Let's visualize what actually flows:

user     ──► "What are the trade-offs of a supervisor?"
model    ──► [thinking] + tool_use: search_knowledge(query="supervisor", k=3)
harness  ──► executes → tool_result: [{id: doc-supervisor, …}]
model    ──► [thinking] + tool_use: read_document(doc_id="doc-supervisor")
harness  ──► executes → tool_result: "A supervisor agent breaks down…"
model    ──► final text: "The supervisor centralizes control [doc-supervisor]…"

Three model calls, two tool executions, one sourced answer. The model chose on its own to search, then read: that is what makes it an agent.

Classic pitfalls

PitfallSymptomFix
No iteration boundCosts explode on an ambiguous requestmax_steps, token budget (module 4)
Truncated historyThe model "forgets" what it just didAlways append the full response.content
Unhandled tool exceptionsThe program crashes on the first incidentReturn is_error: True with an actionable message
Huge tool resultsSaturated context, degraded answersPagination, excerpts, size limits (lesson 1.4)
Ignoring stop_reasonEmpty or inconsistent answersHandle refusal, max_tokens, pause_turn

Key takeaways

  • An agent is a system where the model decides the control flow; a workflow is driven by your code.
  • Four components: model, tools, memory, control loop.
  • The model only requests actions: your harness executes them, and can therefore control them.
  • A production loop is bounded, keeps the full history, returns errors as information, and always checks stop_reason.

Hands-on

  1. Install the companion code and run python examples/01_agent_loop.py "What is a handoff?".
  2. Add a print in the loop to show each tool call and count the turns.
  3. Set max_steps to 1: what happens? Why is that preferable to an infinite loop?
  4. Make read_document raise an exception, then surface it as is_error. Watch how the model adapts.

Resources