AI from scratch · Chapter 8

Agents

A language model only writes text: it predicts the next word (chapters 5 and 7). An agent is that same model put in a loop where some of what it writes is a request to do something, like look up trains, search the web or plan a trip, and the result is fed back for it to read. Blip, the little robot in the corner of this page, is one. This chapter opens it up.

1. The loop

your question + page + the list of tools
↓
model writes either a final answer  or  a tool call: subway_arrivals({"station": "Union Sq"})
↓ if a tool call
our code runs the tool → the result (JSON) is added to the conversation → back to the model
↓ when it answers (or after 4 rounds)
final answer

The model never touches the subway feed itself. It writes a structured request; ordinary code (the same server that runs this site) does the work and hands back data. The model's whole job is deciding which tool, with what arguments, and then reading the result correctly. Training taught it to write tool calls in a strict JSON format, the same way it learned to write sentences.

The pictureA conversation that grows: question, tool call, tool result, tool call, result, answer. The model rereads all of it every turn.
The mathEach turn samples the next tokens from \(p(\text{next} \mid \text{everything so far})\), chapters 5 and 7. A tool call is just text that our code recognizes, runs, and answers with more text.

An agent is a language model in a loop: some of what it writes is a request our code runs, and the result goes back into the conversation.

2. Blip's real toolbox

This is the actual list Blip is given with every question, loaded live from the server. Each tool is just a name, a description and its parameters; the descriptions are all the model knows about them, so writing them well matters as much as the code behind them.

The model keeps calling weather when people ask about the subway. What's the first thing to fix?

Tool choice is reading comprehension: the model matches the question against names and descriptions. Vague or overlapping descriptions cause most wrong picks, and they're the cheapest thing to fix (and to check with an eval, below).

Loading…

A tool is a name, a description and parameters, and the description is all the model knows about it.

3. Watch Blip work

Ask something and see every step: the tool calls it decides to make, what each tool returned, and the answer it writes from them. Give it about ten seconds.

The trace shows up here.

Check its work. Compare the answer with the tool results above it. Small models sometimes misread a result: say "0 minutes" when the data says 6, or round a number wrong. The tool call was right and the data was right, but the last step, reading, went wrong. That's why serious agents keep the evidence next to the answer, and why the next section matters.

The right tool and the right data can still end in a misread answer, so compare the answer with the trace.

4. What goes wrong, and the guardrails

Loops. A model can keep calling tools forever, or call the same one again and again. Blip gets at most 4 rounds; after that it must answer with what it has.

Prompt injection. Tool results are text from the outside world: a web page, an event listing, a store's description. Any of it can contain instructions aimed at the model. One of these three search results is an attack. Which?

The defenses are boring and essential: tell the model in its instructions that tool output is data, never instructions; give tools the least power needed (Blip's tools only read; none can buy, send or delete); check arguments in code before running anything; and keep keys on the server, never in what the model sees.

Bad arguments. The model might ask for station "Unoin Sq" or a date in the wrong format. Tools should validate inputs and return a clear error the model can recover from, not crash.

The math: why long tool chains break

If each step (pick the tool, fill the arguments, read the result) goes right with probability \(p\), and steps fail independently, a task needing \(n\) steps all right succeeds with probability

\[ P(\text{success}) = p^{\,n} \]

At \(p = 0.95\): 3 steps → 86%, 10 steps → 60%, 30 steps → 21%. Small per-step error rates compound fast. That's why good agents keep chains short, check results as they go (a failed step caught and retried is no longer a failure), and why per-step reliability matters far more than it looks.

Each step is right 95% of the time. What's the chance a 10-step task gets every step right? (Three decimals.)

\(0.95^{10} \approx 0.599\). Four times out of ten, something along the way goes wrong.

Guardrails: few rounds, tools with the least power needed, arguments checked in code, and tool output treated as data, never instructions.

Why checking each step beats a better model
  1. Ten steps at 95% each succeed together \(0.95^{10} \approx 0.60\) of the time.
  2. Add a check after each step that catches 80% of the failures and retries once. A step now succeeds if it goes right the first time, or goes wrong, gets caught, and the retry goes right: \(0.95 + 0.05 \times 0.8 \times 0.95 \approx 0.988\).
  3. Ten such steps: \(0.988^{10} \approx 0.89\). The same model went from 60% to 89%.
  4. Fewer steps help too: five steps at 95% give \(0.95^5 \approx 0.77\).
  5. Because success is a power, the per-step rate and the chain length matter more than anything else. A slightly better model raises \(p\) a little; checks and shorter chains change the shape of the curve.

5. Evals: measuring an agent

"It seemed to work when I tried it" isn't a test. An eval is a fixed set of questions with checkable expectations, run every time you change the model, the prompt or a tool description. Here's a tiny one for tool choice: does Blip pick the right tool for each question? Run it (four live questions, about a minute).

The last column is a second check, faithfulness: every number and time in Blip's answer is looked up in what its tools actually returned. A model can call the right tool and still say "the next train is in 4 minutes" when the data said 6. The answers above (in the traced question too) mark each number: found in the data, or not found, which means computed (from a timestamp, say) or made up, and is where a human should look. It's a crude check, numbers only, but it's automatic and it catches the worst kind of mistake: a confident, specific, wrong fact.

Blip says "the Q is 5 minutes away"; the tool returned {"arrival": "2026-10-10T15:20:00"} and the time was 15:15. The checker flags the 5. Is Blip wrong?

String matching can't see arithmetic. Real faithfulness evals handle this with a second model as a judge ("is every claim in the answer supported by this data?"), which is slower and itself imperfect; cheap checks like this one run on every answer and send the doubtful ones to the judge or a human.

Real eval suites have hundreds of cases and check more than tool choice: did the answer match the data, did it refuse what it should refuse, did it stay under the step limit. They're how you know whether a new model or a reworded tool description made things better or just different.

The math: how sure is an eval score?

An eval with \(n\) cases where \(k\) pass estimates the true pass rate as \(\hat p = k/n\). Like a poll, it has a margin of error. Its standard error is

\[ \mathrm{SE} = \sqrt{\frac{\hat p (1 - \hat p)}{n}}, \qquad \text{95\% interval} \approx \hat p \pm 1.96\, \mathrm{SE} \]

18 of 20 passing is 90% ± 13%: anything from about 77% to 100% is plausible. To tell 90% from 92% apart you need thousands of cases. So a change that moves a 20-case eval by one case is noise, not progress. Run bigger evals, or run the same eval several times (models are random, chapter 5) and compare averages.

18 of 20 eval cases pass. What's the standard error of the pass rate? (Three decimals.)

\(\sqrt{0.9 \times 0.1 / 20} = \sqrt{0.0045} \approx 0.067\). Times 1.96: a margin of about ±13 percentage points.

An eval is a fixed test set for an agent, and with 20 cases its score is only good to about ± 13 points.

Where it breaks: evals that fool you, and tools that combine

Last chapter: vision in practice, finding cars and people in real NYC traffic camera images.

All chapters: AI from scratch. Blip's code is server/blip.ts in this site's repo.

Last updated