Odysseus
Part I · Foundations
Chapter 2

The agent loop: models, tools and turns

How single model calls and tool calls combine into a loop that answers one message, why context is finite, how code rather than the model decides what runs, and what the smallest working agent must contain.

After this chapter you should be able to
  • Describe what a language model does in a single call, and what a tool call adds to it.
  • Explain how a loop of model calls becomes one turn of a conversation, and list every way that loop can end.
  • Say what context is, why it is finite, and what a long-running agent must do about that.
  • State the principle "the model proposes, code grants" and point to the lines of code that enforce it.
  • Trace one message from the chat, through the parts of a personal agent, to an answer.
  • List what a minimal first version must have, and what it must not have yet.
This unit
Week
1 of 14
Before it
Chapter 1; Definitions 1 to 3 and 6, Property 1 and the section on cost of the model. Definitions 1 to 3 are first met in code here.
Read first
[Yao et al. 2023a]; [Anthropic 2025a].
Laboratory
1: the loop, the journal and a conversation that can be stopped
Problem set
1

2.1The problem: a model that cannot look things up

The owner writes: "Is the museum on Harbour Street open on Monday, and what does a ticket cost?"

A language model on its own can only answer from what it absorbed during training. Opening hours change; the model's knowledge stops at a date. It may answer confidently and wrongly. What it needs is to look: to search the web, read what comes back, perhaps search again with a better query, and only then answer, saying where the answer came from.

The model cannot search by itself. It produces text and nothing else. So something has to sit around the model: a program that lets it ask for a search, runs the search, gives it the results, lets it ask again, and knows when to stop. That program must also refuse anything the model asks for that it should not have. The library this book's system is built on arrives with tools for running shell commands and editing files, because it was made for programming assistants. A personal agent on a server must have none of them.

2.2What a model does in one call

Chapter 1 defined the model as the part that takes text in and produces text out, and a step as one call to it. Modern models are trained to continue a conversation: given messages, they write the next one.

Definitions
Token
The unit a model reads and writes, roughly a short word or part of a word. Models are priced per token, separately for tokens read and tokens written.
System prompt
Fixed instructions sent at the start of every call, telling the model who it is, what it can do and how to behave.

A model call is a function from text to text. What goes in is the system prompt, the conversation so far and, if the model may use tools, a list of their descriptions. What comes out is the model's next message. (This is a general explanation of how such services work, not a finding of this project.)

The model keeps nothing between calls: it does not remember the previous call, and everything it needs to know must be sent again each time. A conversation of twenty messages is, from the model's side, twenty separate calls, each containing all the messages before it. This is why a long conversation becomes slower and more expensive, and why "the model's memory" is really a question of what the surrounding program chooses to send (Chapter 5).

Calls cost money by the token. The system's code holds a price table, used to estimate a task's cost while it runs. For the mid-priced model it reads:

# Dollars per million tokens: input, output, cache read, cache write.
PRICES = {
    "claude-sonnet-5-5": (2.00, 10.00, 0.10, 2.50),
    ...
}

For this model, writing a token costs five times as much as reading one, and reading a token the service has cached from a recent call costs a twentieth of reading it fresh. The comment beside the table in odysseus/agent.py records that all four prices were checked against the maker's price list, and that prices change. Because a long conversation resends its history on every call, the cheaper cached rate is what makes long conversations affordable at all (Chapter 20).

2.3What a tool call is

As defined in Chapter 1, a tool is one action the model may choose, and a tool call is the model's request to use it. Here is what they look like on the wire. A tool is described to the model by a name, a sentence saying what it does, and a schema: a precise statement of what inputs it takes. A tool call is a structured message from the model naming a tool and giving inputs that fit its schema, in place of (or alongside) text for the person.

Definitions
Tool result
What the code that ran the tool hands back to the model, as the next message in the conversation.
MCP
The Model Context Protocol, a standard format for describing tools to a model and calling them. In this system the tools are served by an MCP server that runs inside the same program.

A tool call is the model writing, in effect, "please run web_search with query Harbour Street museum opening hours". It is text with a fixed structure. Nothing happens in the world when the model writes it. Ordinary code receives the request, decides whether to honour it, runs it if so, and returns the result as a new message. The model then makes another call, now able to read the result.

Tools are declared in odysseus/tools.py. Each is a handler function wrapped with its name, description and schema. The memory tool forget is a typical small one:

tool("forget", "Remove one saved entry by its id, when the owner says it is no longer true or asks you to forget it.",
     {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]})(m["forget"]),

The description is all the model knows about when to use the tool. All the tools are gathered into one server named odysseus, so each has a full name of the form mcp__odysseus__forget, which is what the rules below refer to.

2.4From calls to a turn: the agent loop

Definitions
Agent loop
The repetition at the heart of an agent: call the model; if it requests a tool, decide, run it, append the result and call again; if it replies with text only, stop.
Task
The unit the system budgets, logs and can stop. In a conversation, one task is one turn.

A turn, everything between one message from the owner and the agent's reply, is therefore one pass of the agent loop from start to finish.

Owner's message+ time stamp Model callone step Tool request?or text only Policy (code)allow, ask or refuse Tool runsresult appended Reply deliveredturn ends Checked by code at every stepstep and money limits · no progress · owner's stop · errorsany of these ends the turn and the owner is told why tooltext onlyallowednext step
Figure 2.1. The agent loop. Notice that the model appears in one box only. Every arrow out of the model goes through code before anything happens, and the conditions that end a turn early are checked by code without asking the model.

A turn can end in seven ways, and the code names each one. The status of every task is one of done, stopped, stuck, budget, day_budget, turn_limit or error:

  • done: the model replied with text and no further tool request.
  • stopped: the owner sent "stop". This is matched by the shell and never shown to the model (Chapter 4).
  • stuck: the task was not getting anywhere. The same call was asked for three times, or four calls in a row failed (Chapter 4).
  • budget: the estimated cost of this task's steps reached the most one task may cost: four times its expected cost of $0.50, by default.
  • day_budget: the task's estimated cost reached what was left of the day's budget (Chapter 4).
  • turn_limit: the task used more steps than the most one task may take, by default four times 25. The count is checked after each step, so the limit is noticed on the step after the last one allowed.
  • error: something failed, and the owner is told it could not finish.

Only the first is chosen by the model. The other six are imposed on it. A loop that could end only when the model decided to end it would run, and spend, for as long as a confused model kept requesting tools.

2.5Context, and why it runs out

Definitions
Context
Everything sent to the model in one call: the system prompt, the tool descriptions, the conversation so far, and every tool result in it.
Context window
The largest context a model accepts in one call, fixed by the model's maker.
Compaction
Replacing the older part of a long conversation with a summary, so that the context stays within the window. Details are lost when this happens.

Every step adds to the context. A search result of several pages of extracts is appended in full; so is the model's reply; so is the next message. Because the model keeps nothing between calls, all of it is sent again with each step. Three consequences follow.

First, context is finite. A conversation kept open for days will, sooner or later, exceed the window. The agent library handles this by compaction: it summarises the older part and carries on.

Second, anything that must not be lost cannot live only in the context. The owner's lasting preferences are kept in a separate memory store and shown to the model at the start of a conversation, and again after compaction. The library signals that it is about to compact, and the system's code responds by marking the context as blank, so that the memory is shown again with the next message:

async def _on_compact(self, hook_input: Any, tool_use_id: Any, context: Any) -> dict[str, Any]:
    # The SDK is about to condense the conversation. What was shown at the start may not
    # survive that, so the memory is shown again with the next message.
    self._blank = True
    self._journal.write("compact")
    return {}

Not tested Compaction has not happened in a live conversation; this path has been exercised only by a test that sends the signal by hand.

Third, context costs money in proportion to its size, on every step. A document the owner sends (as opposed to a photo, which the model is shown directly) is therefore turned into text by a separate service, and the file itself is not put into the conversation, where it would be carried forward with every later message (Chapter 15).

The conversation must also survive a restart of the program: its id is saved to disk and the library resumes it (Chapter 7).

2.6The model proposes, code grants

Principle

The model proposes, code grants. The model may request any action. Whether the action happens is decided by code that the model cannot alter, on rules that do not depend on what the model was told or what it read.

The principle is needed because of a property of language models that has not been engineered away. Verified One model maker's own documentation says its model "sometimes follows instructions found in page content even when they conflict with yours" (Anthropic). Secondary A study of six leading models driving browsers reported that planted instructions succeeded about a quarter of the time on average (paper). A design that is safe only while the model behaves will fail.

The tool call is what makes the principle possible. Because every action passes through code as a request, code can inspect it. The table shows where the boundary is held.

Table 2.1. Where code, not the model, holds the boundary.
BoundaryWhat the model can doWhat code does
Which tools existRequest any tool nameOffers only the system's own tools; refuses any name without a rule
Consequential actionsRequest a send, a deletion, a shareHolds the request, shows the owner its real inputs, waits (Chapter 8)
StoppingNothing; it is not consultedEnds the task when the owner says stop
SpendingKeep workingCounts steps and estimated cost, ends the task at the ceiling
Who may speakRead what the shell passes itDrops messages from anyone but the owner; labels search results as material to read

2.7The parts of a personal agent

Owner Channeltelegram.py THE SHELL: ordinary code Conversation rulesowner check, stop, daily budget Agent runner + modelthe loop, step and cost limits Gate / policyallow, ask the owner, refuse Journalone line per step; the ledger Web search Memory Schedule Mail, calendar, apps Browser Scheduler the scheduler can start a task with no message
Figure 2.2. The parts of a personal agent as they appear in the code. The model sits inside the agent runner and reaches the tools on the right only through the gate. The conversation rules, the gate and the journal never consult the model.
Table 2.2. The core files of the system and their responsibilities.
FileResponsibilityCalls the model library?
telegram.py, whatsapp.pyCarry messages and button taps between the chat service and the conversation rulesNo
conversation.pyWho may speak, what "stop" does, the daily budget, one task at a time, what the owner is told at the endNo
agent.pyRuns one task through the loop; the options that restrict the library; per-task limitsYes
tools.py, search.pyEvery tool the model can call, gathered into one serverReturns results to it
gate.pyDecides allow, ask or refuse for every tool callNo
journal.pyThe log, one line per step, and the ledger of money spent per day derived from itNo

The right-hand column is the point of the arrangement. Only one file calls the model library, and the rules live in files that do not. (Others prepare what the model is sent: conversation.py adds the time stamp and the memory to the owner's message.)

2.8The mechanism in code

Restricting the library

The loop itself comes from a library, the Claude Agent SDK. Why a library and not a hand-written loop is a vendor decision (Chapter 3). The library is configured by one method in odysseus/agent.py, AgentRunner.options:

def options(self) -> ClaudeAgentOptions:
    return ClaudeAgentOptions(
        model=self._model,
        system_prompt=self._system_prompt,
        tools=[],                          # none of the SDK's built-in tools (shell, files, ...)
        mcp_servers={SERVER: self._server},
        strict_mcp_config=True,            # ignore any tool servers configured on the machine
        allowed_tools=sorted(self._allowed),
        can_use_tool=self._policy,         # anything not listed above is refused by code
        setting_sources=[],                # ignore settings files on the machine
        include_partial_messages=True,
        hooks={"PreCompact": [HookMatcher(hooks=[self._on_compact])]},
        resume=self.session_id,            # after a restart of the client, carry the conversation on
        # The agent library writes a transcript of every run. It is kept inside the data folder for every agent
        # (conversation, routines, triage), so that mail text never ends up in a folder nobody chose.
        env={"ANTHROPIC_API_KEY": self._s.anthropic_api_key, "CLAUDE_CONFIG_DIR": str(self._transcripts.resolve())},
    )

Four lines do the restricting. tools=[] asks for none of the library's built-in tools. strict_mcp_config and setting_sources=[] stop the library picking up tool servers or settings that happen to be configured on the machine it runs on. allowed_tools lists the tools that may run without consulting the policy, and can_use_tool names the function consulted about everything else. The rest turn on live previews, the compaction signal, resumption and a transcript folder of the system's choosing. Without the four, the agent would inherit a shell and a file editor, and whatever else was configured on the server.

The policy

The policy in its smallest form is in the same file:

def make_policy(allowed: frozenset[str]):
    async def policy(tool_name: str, tool_input: dict[str, Any], context: Any):
        if tool_name in allowed:
            return PermissionResultAllow()
        return PermissionResultDeny(message=f"{tool_name} is not available here.")
    return policy


tool_policy = make_policy(ALLOWED_TOOLS)

It has two of the gate's three answers, allow and refuse. The list it uses is defined in odysseus/tools.py:

SEARCH_TOOL = _name("web_search")
MEMORY_TOOLS = tuple(_name(n) for n in ("remember", "forget", "note", "recall"))
SCHEDULE_TOOLS = tuple(_name(n) for n in ("schedule", "list_schedule", "cancel_schedule"))
ALLOWED_TOOLS = frozenset({SEARCH_TOOL, *MEMORY_TOOLS, *SCHEDULE_TOOLS})
ROUTINE_TOOLS = frozenset({SEARCH_TOOL, _name("recall")})

Everything on the list either reads public information or writes only to the system's own files. A routine, run with nobody watching, starts from the smaller ROUTINE_TOOLS set (search and recall), to which routine_tools adds only the reading tools of connected accounts: it can read, and it can write nothing.

When the full gate is in use, the runner replaces this simple policy:

if gate is not None:
    # With a gate, only tools it always allows skip the question; everything else goes through it.
    self._allowed = frozenset(gate.always_allowed())
    self._policy = gate.permission

The search tool is not always allowed under the gate: its rule asks the owner when a query carries details read from the owner's private mail or calendar. So it is left off the skip list, and the gate is consulted on every search. Only tools whose rule is "allow" whatever their inputs may skip the check. Inside each consequential tool's handler the gate checks a second time, so if the first check were ever bypassed, the action would still not run unapproved. Chapter 8 explains both checks.

The loop

The heart of AgentRunner.run reads the stream of messages the library produces for one task:

await client.query(self._with_pictures(prompt, images) if images else prompt)
async for msg in client.receive_response():
    if isinstance(msg, StreamEvent):
        ...    # (lines omitted here: fragments of text are passed to on_text for the live preview)
    elif isinstance(msg, AssistantMessage):
        text = "".join(b.text for b in msg.content if isinstance(b, TextBlock))
        if text:
            last = text
        for b in msg.content:
            if isinstance(b, ToolUseBlock):
                progress.asked(b.name, b.input)
                self._journal.write("tool_request", name=b.name, input=b.input)
                ...    # (lines omitted here: the step is shown to the owner as a status line)
        # One model call can arrive as several messages sharing an id; count it once.
        key = msg.message_id or f"n{len(calls)}"
        calls[key] = estimate_usd(self._model, msg.usage or {})
        ...    # (lines omitted here: the size of what the model was sent is recorded)
        if self._limit is None and not self._stopped:
            # The task's budget and its number of steps are marks, not walls (progress.py). A task that passes
            # one carries on while it is getting somewhere, up to a ceiling `task_stretch` times higher. A task
            # that is not getting anywhere is ended at once, whatever it has cost. The day's budget is a wall.
            stretch = max(1.0, float(getattr(self._s, "task_stretch", 1.0) or 1.0))
            spent = sum(calls.values())
            self.stuck_why = progress.stuck()
            if self.stuck_why:
                self._limit = "stuck"
            elif len(calls) > self._s.max_turns * stretch:
                self._limit = "turn_limit"
            elif spent >= self._s.task_usd * stretch:
                self._limit = "budget"
            elif self.day_room is not None and spent >= self.day_room():
                self._limit = "day_budget"
            elif not passed and (spent >= self._s.task_usd or len(calls) > self._s.max_turns):
                passed = True
                self._journal.write("limit", which="passed", steps=len(calls), estimated_usd=round(spent, 4))
            if self._limit:
                self._journal.write("limit", which=self._limit, steps=len(calls), estimated_usd=round(spent, 4),
                                    **({"why": self.stuck_why} if self.stuck_why else {}))
                await client.interrupt()
    elif isinstance(msg, UserMessage) and isinstance(msg.content, list):
        for b in msg.content:           # what each tool call came back with: an error, or not
            if isinstance(b, ToolResultBlock):
                progress.came_back(bool(b.is_error))
    elif isinstance(msg, ResultMessage):
        result = msg

Four kinds of message arrive. A StreamEvent carries a fragment of text for the live preview. An AssistantMessage is one finished model message: its tool requests are journalled and counted towards the two signs of being stuck, and the step is counted and costed from its token counts. A UserMessage carries the results of the tools that ran, and the runner notes only whether each was an error. A ResultMessage arrives once, at the end, with the library's own cost figure.

The library runs the tools itself, between messages, once the permission check (the skip list or the policy) has let them through. The runner's job is to watch, count and, when a limit is reached, interrupt. The order of the tests matters: being stuck is tested first, so a task going nowhere ends at once whatever it has cost; the ceilings come next; and passing a mark only writes a line to the journal, once. Notice that the setting is called max_turns but counts steps (model calls) within one task; with the defaults the owner is told "I ended this task after 100 steps, the most one task may take". The names differ because the library uses "turn" for what this book calls a step.

After the loop, the outcome is decided by code, in order of precedence:

if self._stopped:
    status = "stopped"
elif self._limit:
    status = self._limit
elif result.subtype == "success" and not result.is_error:
    status = "done"
else:
    status = "error"

A stop by the owner outranks everything, a limit outranks the model's own success, and anything unexpected is an error. Whatever text the model had written by then is delivered with the explanation attached, so partial work is not thrown away.

A tool, end to end: search

The search tool, in odysseus/search.py, shows what a well-behaved tool handler does:

async def web_search(args: dict[str, Any]) -> dict[str, Any]:
    query = str(args.get("query", "")).strip()
    try:
        # The library is synchronous; keep it off the event loop so "stop" stays responsive.
        response = await asyncio.wait_for(asyncio.to_thread(spec.execute, args), SEARCH_TIMEOUT_S)
        text = spec.format(response)
    except (Exception, asyncio.TimeoutError) as e:  # bad arguments, network, quota, no answer: all go back to the model as a failed call
        journal.write("tool", name="web_search", query=query, ok=False, error=type(e).__name__)
        return {"content": [{"type": "text", "text": f"Search failed: {type(e).__name__}"}], "is_error": True}
    count = len(getattr(response, "results", None) or [])
    # The search service states what each call cost. It is recorded, and the ledger counts it (journal.py).
    price = getattr(getattr(response, "cost_dollars", None), "total", None)
    journal.write("tool", name="web_search", query=query, objective=str(args.get("objective", ""))[:300],
                  ok=True, results=count, cost_usd=float(price) if isinstance(price, (int, float)) else 0.0)
    if len(text) > MAX_RESULT_CHARS:
        text = text[:MAX_RESULT_CHARS] + f"\n[Cut: {len(text)} characters came back. Search again, more narrowly, for the rest.]"
    return {"content": [{"type": "text", "text": f"{UNTRUSTED_NOTE}\n\n{text}"}]}

Five habits are visible. The results are cut at 12,000 characters, with a note telling the model to search more narrowly, because whatever a search adds to the conversation is paid for again with every later message. The search runs on a separate thread with a 40-second timeout, so a slow search cannot freeze the program and "stop" still works. Any failure, from bad arguments to a lost network, goes back to the model as a failed tool call it can reason about, not as a crash that ends the task. Every call is logged with its cost, which the daily ledger counts. And the results are prefixed with a fixed line saying they are material to read, not instructions from the owner. That line lowers the chance of the model being misled by a page; it guarantees nothing (Chapter 9).

The model supplies a query describing the page it hopes to find and an objective saying what the search is for; both reach the search service unchanged, as the service's own guidance recommends. The system prompt carries the service's recommended sentence about when to search, so the model looks things up rather than answer from stale knowledge.

2.9Worked example: one message, end to end

The owner sends "Is the museum on Harbour Street open on Monday, and what does a ticket cost?"

  1. Channel. telegram.py receives the message in a private chat and passes the sender's id and text on.
  2. Conversation rules. The sender is the owner; the text is not a command such as stop; no task is running; today's spending is under the limit. A task starts and the journal records task_start.
  3. Prompt assembly. The time is appended in square brackets, as the weekday, the date and the hour (a stamp that begins [Friday, say), so that "Monday" can be worked out. At the start of a conversation the owner's saved memory is put in front.
  4. Step 1. The model replies with a tool call: mcp__odysseus__web_search, query Harbour Street museum opening hours and admission prices, objective the museum's own page first; Monday hours and adult price. The runner logs tool_request and counts one step.
  5. Policy. The gate's rule for search finds nothing from the owner's mail or calendar in the query, so it allows it.
  6. Tool. The search runs and is logged as tool with ok: true and its cost. The model receives the results under the line saying they are material to read.
  7. Step 2. The model replies with text only: closed on Mondays, the adult price, and the page it came from. The words appear in the chat as they are written.
  8. End. The ResultMessage arrives; the status is done; the task's cost is the new running total minus the old. The journal records task_end with status, cost, two steps and the seconds taken.

The museum and its answer are invented for this example. The order of events and the journal entries are those the code produces. Verified For scale: in the first live measurement, one sample, a question that needed one search cost $0.0145.

2.10What a minimal first version must have

The smallest system worth running is much smaller than the finished one. It must have:

  1. A channel that answers only its owner, and drops everyone else silently, before any model call.
  2. The agent loop, with the library's built-in tools removed and a policy that refuses anything not listed.
  3. One tool that only reads public information: web search.
  4. Stop, handled by the shell and never passed to the model.
  5. Limits on steps per task, money per task and money per day, enforced by the system's own code, with the owner told when one ends a task.
  6. A log of every step, from which the ledger of spending is derived.
  7. Instructions telling the model what it cannot yet do, so that it says so instead of pretending.

It must also have no tool that sends, pays, deletes or shares. With only a search, the worst outcome of a successful prompt injection is a wrong or strange reply. That stops being true the moment a consequential tool is added, which is why the gate must be built before the tools that need it.

2.11The theory

Here the first three definitions of the model are met in code. A model call is Definition 1: a context c = (s, h) in, an action out. Here s is the system prompt with the tool descriptions, and h is the conversation with every tool result in it. Nothing is assumed of M but its type, which is why the model keeps nothing between calls: each call is a fresh draw from M(c), and all it knows is c. A tool handler is Definition 2: it receives inputs x, may change the world, and returns r, which is appended to h. The agent loop is Definition 3: a run c₀ →ᵃ⁰ c₁ →ᵃ¹ … that ends when an action is text. One turn is one run.

Two refinements fit the definition to the code. One model call may request several tools, each checked, run and appended before the next call. And code can end a run before the model writes text: every status but done ends a truncated run, a prefix cut where the model did not choose.

The principle is Definition 6 with the record of reading ignored. The policy of this chapter is

G(τ, x, T) = allow if τ ∈ ALLOWED_TOOLS; refuse otherwise

a gate with two answers that looks at the tool's name alone. If every path from the model's output to execution passes through it (Property 1), then for every model each executed call is on the list. The list holds tools that read public information or write only the program's own files, so no run can send, change or destroy anything in the owner's accounts, whatever the model read. That is a property; the quality of the answers would be a measurement, and none is reported.

Calls per task. If a task ends done after u tool requests, every model call but the last requested at least one tool, so the number of calls is m ≤ u + 1, with equality when each requests exactly one. The museum task has u = 1 and m = 2.

Context growth. Let c₀ be the tokens of the fixed part of the first call (system prompt, tools, memory if shown, the message) and δ the tokens each call adds. By the Cost section of the model, m calls send m·c₀ + δ·m(m+1)/2 input tokens. The conversation is one long session, so the same holds across turns with m counting every call since the last compaction: input grows with the square of the number of calls. Two habits of the code act on the terms. The cut at 12,000 characters bounds the δ one search can add, and compaction replaces h with a summary, restarting the sum. The cache changes the price of the square term, not its size: if every call after the first reads the earlier prefix from the cache and writes only its own new tokens, the repeated tokens are paid at pcr, which for the mid-priced model is a twentieth of pin.

Property: a limit is detected within one call of being crossed

Let N be the step mark and B the money mark of a task, and s ≥ 1 the stretch, so that the ceilings are sN calls and sB dollars (100 and $2.00 by default). A task with status done made at most ⌊sN⌋ model calls; unless the owner stops it first, a limit is recorded no later than call ⌊sN⌋ + 1; and when the money ceiling is recorded, the estimated spend is below sB plus the estimate of the call that crossed it.

Argument. The check runs on every finished model message before the next is read, and counts calls by message id, so a call in pieces counts once. At call ⌊sN⌋ + 1 the count exceeds sN, so the check records turn_limit, or stuck if a sign of being stuck holds, since that is tested first; either way a limit is recorded. Before the crossing call the sum was below sB, or the check would already have recorded a limit. A recorded limit outranks the model's success, so a task of more than sN calls cannot end done. Passing a mark records nothing that ends the task, which is why the bounds are stated with the ceilings.

The property bounds detection, not spending, and a bound on spending fails in three places. What the library does between the request to interrupt and stopping is outside this code. The estimate uses a price table that can be out of date. And the check sums model calls only, so the search service's own charge, which the daily ledger counts, does not count towards sB.

Claim in this chapterKindHow it is known
A tool not on the list does not runPropertyArgued from options and the policy; tested in tests/test_slice.py
A task that ends done made at most 100 calls, four times the mark of 25PropertyArgued from the check and the order of statuses; the limits, the marks and both signs of being stuck tested with a stand-in
tools=[] leaves only the program's toolsMeasurementOne live run: the library listed one tool
Input grows with the square of the number of callsDerivationFrom the Cost section; not measured here
A question needing one search cost $0.0145MeasurementOne sample

2.12What goes wrong

Inheriting tools. An agent library built for one purpose carries tools for that purpose. Removing them is a matter of configuration, and configuration can silently not take effect. The system therefore removes the built-in tools and, separately, refuses any unlisted tool, so that if one measure fails the other holds. Verified The library's documentation did not state outright whether tools=[] removes every built-in tool. A live run settled it: the library's own start-up report listed exactly one tool, the search.

Using the library's limits. The library has its own step and money limits. They are fixed when a connection is made and count everything on that connection, so on a connection kept open between messages they cannot mean "per task". The system counts for itself, and its tests assert that the library's limits are left unset.

Counting a step twice. One model call can arrive as several messages sharing an id. Counting messages instead of ids would end tasks early. The loop keys its count on the message id, and a test checks that a call delivered in three pieces counts once.

Misreading cost. The library reports cost as a running total for the conversation, so the cost of a task is the new total minus the old one.

Case note

The code that counts what each task costs had a full set of passing tests, which used a stand-in (test code imitating the model library). The first live run showed that the library reports cost as a running total for the whole conversation, not per task. Three trivial questions reported $0.0013, $0.0026 and $0.0029; adding them gave $0.0068 for work that had cost $0.0029. Verified The tests had passed because the stand-in was written to report costs the way the builders wrongly believed the library did.

Case note

The first version connected to the library afresh for every message. Verified In the first live runs a one-word reply took 8 to 17 seconds, nearly all of it start-up. Keeping one connection open between messages brought it to about 2 seconds, and stop then ended a real task in 0.13 seconds instead of 1.1. Nobody had listed start-up time as a risk before the run.

2.13How to test it

A test of the agent loop must check the boundaries, because those are what the model cannot be relied on for: that only listed tools are offered and allowed; that each limit ends a task and the owner is told; that stop ends a task even when the model ignores it; that a failed tool returns an error, not a crash; that cost is attributed to the right task.

tests/test_slice.py does this with a stand-in for the model library: test code that replays a fixed script of messages. Its 28 tests pass. They cover the policy (search allowed; Bash, Write, a mail send and a web fetch refused), the options (no built-in tools, no machine settings, library limits unset), both per-task limits, a call delivered in pieces, cost as a difference of totals, the search's pass-through and labelling, a failed search, and a crash in the agent.

A stand-in is fast, free and can produce rare cases on demand, such as a model that never stops. But it behaves as its authors believed the real library behaves, so passing tests show only that the code agrees with those beliefs, and only live runs test the beliefs themselves.

What is proven and what is not

Verified The restrictions on the library, the policy, the per-task limits and the search tool are covered by passing tests against a stand-in. Live runs showed that the library offered exactly one tool when only search existed, that stop ended a real task, what one ordinary question cost (one sample), and that keeping one connection open cut a reply from 8 to 17 seconds to about 2.

Not tested Compaction in a live conversation. The quality of the answers the loop produces. Whether the label on search results changes how often a real model is misled by a page; the design does not rely on it.

2.14Where this sits in the literature

The loop of this chapter has a short history. [Yao et al. 2023a] interleaved reasoning with actions that query outside sources, and reported gains over reasoning alone and acting alone on question answering, fact checking and two interactive tasks; the cycle of observing, thinking and acting it described is the template most tool-using agents implement, this one included. [Schick et al. 2023] trained a model to decide when and how to call outside interfaces, which framed tool use as a capability of the model and led towards the function-calling interfaces in use. The flow traced in this chapter, tool definitions sent, a tool call received, the tool run by application code and its output returned, is the one vendor documentation describes [OpenAI 2025a]. The format in which this program serves its tools is the Model Context Protocol, whose specification of tools [MCP specification, tools] covers listing, calling, schemas and errors, and states requirements for a human in the loop and for security. The protocol carries the call; it does not decide whether the call runs. This program makes that decision in its own code, where the call executes, which is the end-to-end argument of [Saltzer et al. 1984] applied at the tool boundary: a check the model is asked to make is at most an optimisation, and the guarantee has to be supplied at the end that acts.

The literature adds most to this chapter on context. [Liu et al. 2023c] found that a model's accuracy on retrieval-style tasks depends on where the relevant text sits in a long context, and is often lower in the middle. The growth derived in the theory is therefore not only a cost: a conversation kept open for days puts the owner's earlier words in the middle of a long context, and this program does nothing about position except show the memory again after compaction. Whether that matters for its errands has not been measured. [Anthropic 2025a] describe managing what enters the context of a long task by retrieving just in time, by compaction and by sub-agents. This chapter uses the first two: a search result enters only when asked for and is cut at a fixed length, and compaction is the library's. [Packer et al. 2023] went further, letting the model move information between the context and outside storage through function calls, as an operating system moves pages. The memory tools here are a small case of that, with one difference: showing the memory again after compaction is done by code on the library's signal, not left to the model.

On price, the maker's documentation of prompt caching [Anthropic 2026c] gives cache writes at 1.25 times the base input price for the five-minute lifetime and reads at a tenth or less, which agrees with the price table quoted in this chapter. The derivation in the theory shows why that ratio, and not the base price, governs what a long conversation costs.

The published work is stronger than this program on the design of tools. [Yang et al. 2024] showed that the interface between model and computer, its commands, the form of its feedback and its guardrails, changes how well an agent performs. The search tool's habits, a cut with a note to search more narrowly, a failure returned as a result, a label on what was read, are interface decisions of exactly that kind, and none has been measured here against an alternative. Two questions bearing on this design are not settled: whether one long conversation with compaction serves an owner better over weeks than a fresh context assembled by code for each task, and how a loop's step and money limits should be chosen from evidence rather than set by hand.

Summary
  • A model call turns text into text and keeps nothing between calls; everything it needs is sent each time, and paid for by the token.
  • A tool call is the model asking, in structured text, for an action. Code decides, runs it, and returns the result.
  • The agent loop repeats calls until the model answers in text. A turn is one pass of the loop; it can also end by stop, a lack of progress, a step limit, a money limit, the day's budget or an error, all imposed by code.
  • Context grows with every step and is finite. Compaction summarises it, so lasting facts must be kept outside it and shown again.
  • The model proposes, code grants: built-in tools are removed, unlisted tools refused, and consequential ones sent to the gate.
  • A minimal first version has a channel that answers only its owner, the restricted loop, one read-only tool, stop, limits and a log, and nothing that can change the world.
Problems

Review

  1. A conversation has ten messages from the owner, each answered in one model call. On the eleventh, the model makes two calls. How many times has the first message been sent to the model in total? What does your answer imply for the cost of a long conversation, and how does the cache-read price change it?
  2. List the seven statuses a task can end with. For each, say whether the model or code chooses it, and what the owner is told.
  3. The search tool is on ALLOWED_TOOLS, yet under the full gate it is not on the list of tools that skip the policy. Explain why, and what would go wrong if it were added to the skip list.
  4. Write a new read-only tool, current_time, that returns the date and time in the owner's zone. Give its description and schema, the handler, where it is registered in make_tool_server, and which lists it belongs on. Then write the test that proves the policy allows it.
  5. The loop counts a step when an AssistantMessage arrives. Suppose the library delivered a tool result between two pieces of the same model call. Would the count be wrong? Write a stand-in script that tests your answer.
  6. Remove the line tools=[] from options in your head. Which remaining line still prevents the model running a shell command, and is there any situation in which it would not?

Analysis

  1. A conversation starts with c₀ = 6,000 tokens of fixed context and adds δ = 1,500 tokens per call, and call t sends c₀ + tδ input tokens, as in the Cost section of the model. Use the mid-priced model's prices from this chapter and ignore output tokens. (a) Over m = 40 calls with no cache, how many input tokens are sent, and what do they cost? (b) Now suppose call 1 writes to the cache everything it sends, and each later call reads from the cache everything the previous call sent and writes the rest. How many tokens are read from the cache and how many written, and what is the total cost? By what factor did the cache reduce it? (c) In a single task with the same c₀ and δ and no cache, on which call does the estimated input cost first reach the money mark of $0.50, and on which the ceiling of four times that? Is the step mark or the money mark passed first, and which ceiling is reached first, with the defaults of this chapter?
  2. Prove the property "a limit is detected within one call of being crossed" from the code in this chapter. Then give the largest number of model calls a task ending turn_limit can show, assuming the library stops at once when asked to interrupt, and say why the property gives no bound if it does not. Finally, construct with invented figures a task that spends more than sB in total although the money ceiling is never recorded, and name the hypothesis your construction breaks.
  3. Show from the code that no output of the model can produce the status stopped. For each of the other statuses the chapter lists, say whether it is chosen by the model, imposed by code on a condition the model can influence, or imposed by code on a condition the model cannot influence, and give for the second kind a sequence of model actions that brings it about.
  4. Definition 3 says the last action of a run is text. Is a task that ends budget a run in that sense? State precisely what the property of the simple policy (no executed call is off the list) says about a truncated run, and prove that it holds for every prefix of a run if it holds for runs. Then give a hypothesis about the library under which an allowed call requested in the crossing message runs after the limit is recorded, and say whether that breaks the property of the policy or only the bound on spending.

Design

  1. A colleague proposes removing the money limit from code and giving the model a tool, give_up, with an instruction to call it when a task seems too expensive, on the grounds that the model knows better than a counter when work is worth continuing. Say what this design can do that the counter cannot, what is guaranteed in each design whatever the model does, and what is given up. Where, if anywhere, would you use the model's judgement here?
  2. Design a tool fetch_page that returns the text of one web page at a given address. Give its description and schema, the bound it places on what it adds to the context and how the model is told about a cut, what it does on a slow or failed fetch, how its result is labelled, and which list in tools.py it belongs on. State what is guaranteed about it whatever the model does, and what is not, including what reaching an address chosen by a page the model read could send to another principal.

Reading

  1. [Yao et al. 2023a]. In about four hundred words: what it claims about interleaving reasoning and acting; why that matters for this chapter's loop, in which only the model's text ends a turn by choice and code imposes the other ends; where you were not convinced; and what you would measure or build next. In particular, find how the paper's agents end a task and whether anything outside the model can end it, and say what that implies for running its loop on an owner's accounts.
  2. [Anthropic 2025a]. In about four hundred words: what it claims about managing context over long tasks; why it matters for this chapter's decisions to rely on the library's compaction, to show the memory again after it, and to cut a search result at 12,000 characters; where you were not convinced; and what you would measure next to decide whether those three decisions are right for a conversation kept open for weeks.

Open

  1. (Hard, open) The system keeps one long conversation and relies on compaction. Design an alternative in which each task starts with a fresh context assembled by code from memory and recent history. What would be gained in cost and predictability, what would be lost, and how would you test that nothing the owner said in the last hour is forgotten?
  2. The step mark of 25, the money mark of $0.50 and the stretch of four that sets the ceilings are all set by hand. Propose a procedure that sets them from the journal of one owner's tasks, so that the share of tasks ended by a limit that would have finished usefully is below a stated rate, while the cost of the tasks that would not have finished is bounded. Nobody knows the distribution of steps or cost for an owner's real errands, or how it shifts as tools are added. Progress would be a procedure whose stated rate holds, with an interval, on tasks held out from the ones used to set the limits.