Agent Design Patterns

An agent system is a pile of design decisions. Five workflow patterns, four ways to reason and act, and five ways to manage context cover most of them. Run one ticket both ways first.

Learn who holds the steering wheel (your program or the model), then the named patterns for each, and how a real harness such as Pi combines them.

Pick a system and a ticket, then press Run a few times. Watch which system takes the same path every time, and which one copes when the ticket is odd. Then we build, piece by piece, every pattern the lecture names.

You need a picture of a language model that reads text and writes text and a little Python for the code. We build the rest from zero.

Based on Lecture 6 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang, and its readings. Lecture slides (PDF). Every idea is re-taught here in our own words and devices. It follows Lecture 5, Agent Frameworks.

Run the ticket

Toy simulation, not a measurement: the workflow always runs classify, read policy, draft reply. The agent picks from six tools, and on the odd ticket it fails about one run in five. The paths are drawn at random in your browser each time you press Run.

Chapter 0

Who Holds the Steering Wheel

Decide whether your code or the model chooses the next step, and see why that one choice sorts every system you will build

Picture two support desks. At the first, a new hire has a laminated card: read the ticket, pick a category, find the matching policy, write the standard reply. The card never changes. At the second, an experienced agent gets the same kind of ticket, but nobody tells them what to do. They open the order system, then the bank log, then maybe the shipping tracker, and they decide each move after seeing the last result.

Both desks answer tickets. They differ in one thing: control flow, which means who decides what step runs next. At the first desk the card decides. At the second desk the person decides. That one difference is the spine of this whole lecture.

Patterns are half-baked, on purpose

The lecture opens with a book cover: Design Patterns by Gamma, Helm, Johnson and Vlissides, the classic of software engineering. A design pattern is a named, reusable shape for a solution, like a recipe card for a problem that keeps coming back. The slide quotes Martin Fowler on the catch: patterns are half-baked, so you always have to finish them yourself and adapt them to your own environment.

That sets the tone. The lecture gives you a vocabulary of named shapes for building agent systems. You will mix and bend them. The lecture has three goals: define the common patterns for workflows and agents, compare the patterns for managing context, and analyze the design choices in a real production harness called Pi.

One short paragraph for course logistics. Google credit forms are due as soon as possible. The project proposal should follow the ICLR format, with leniency for now and strict checks for the midpoint and final reports. Homework 1 is due Friday October 30. The midpoint demo is due November 4 and the report November 6.

Workflow or agent: the definitions

A workflow is a system where your program holds the control flow. The program calls the model at fixed points and decides, in ordinary code, what happens next. An agent is a system where the model holds the control flow: it looks at what it has seen and chooses the next action, again and again, until it decides to stop.

The lecture draws a line with three marks. On the left sits a bare model: one call, a small part of a larger system. In the middle sits a workflow, also called a compound AI system, because several parts (models, tools, code) work together and the program holds the logic and orchestration. On the right sits the agent, where control flow is the model's role. The slide's examples are an email categorizer and a news feed summarizer for the middle mark, and a customer service agent and a coding agent for the right mark.

Why not always pick the agent, since it adapts? Because of a trade the lecture draws as a curve. Workflows are more predictable, since the control flow lives in program logic you can read and test. Agents are more adaptable, since the control flow lives in the model's decisions and can follow the task wherever it goes. You gain agency and you lose predictability. The curve on the slide is qualitative: it shows the shape of the trade, not measured numbers.

The slide's two graphs show the same idea as pictures. The workflow graph is a chain: start, extract, pick an emoji, add to calendar, end. The agent graph is a loop: start, then the model, which either calls tools (and returns to the model) or ends. The chain has no choices. The loop has one choice, repeated.

Sort the task

Each card is a job. Choose whether the steps are known in advance (a workflow) or must be found while working (an agent).

Four cards come from the lecture's own examples (the email categorizer, the news feed summarizer, the support-ticket reply and the coding agent); the others are made up in the same spirit. The sorting rule is the lecture's: fixed, repeatable structure means workflow; exploration and flexible decisions mean agent.

The table, and the same ticket in code

WorkflowAgent
Who holds control flowYour codeThe model
How it adaptsFixed branches, routes and loops you programmedChooses the next step from what it observes
Best fitTasks with a clear, repeatable structureTasks that need exploration and flexible decisions
ExampleClassify a support ticket, retrieve the policy, draft an automatic replyResolve a ticket by using tools to investigate

Here is the first row as code. In the workflow, the program owns the order. Each line that calls llm is one model call, and nothing the model says can change which line runs next.

pythondef handle_ticket(ticket):                    # WORKFLOW: the program holds control flow
    label  = llm(f"Classify this ticket: {ticket}")   # call 1
    policy = POLICIES[label]                            # plain code, no model
    return llm(f"Policy: {policy}\nWrite the reply to: {ticket}")  # call 2

def handle_ticket_agent(ticket):               # AGENT: the model holds control flow
    msgs = [SYSTEM, {"role": "user", "content": ticket}]
    while True:
        reply = llm(msgs, tools=TOOLS)                  # the model picks: a tool call, or an answer
        if not reply.tool_calls: return reply.text   # the model chose to stop
        for call in reply.tool_calls:
            msgs.append(run_tool(call))                 # the result goes back in for the next choice

The data flow differs too. The workflow sends two small prompts and gets two text replies. The agent sends a growing list of messages, and each reply is either text or a request such as {"name": "search_orders", "arguments": {"email": "ana@example.com"}}. Your code runs that request and appends the result. The model never touches your systems. It only asks.

Real systems often combine both. A workflow can call an agent for its one hard step. An agent can call a workflow as a tool. The rest of the lecture names the pieces for each side.

Failure, and the fix

A team builds an agent for a routine job. The symptom: the same ticket takes three model calls on Monday and seven on Tuesday, and nobody can say why. The measurement: run the same ticket twenty times and count distinct paths. The hero at the top does exactly this, with five runs. The fix: if the path should never vary, put it in a workflow.

The reverse failure also happens. A workflow meets a ticket nobody planned for and sends a confident, wrong reply, because its fixed path has no branch for the surprise. The measurement here is the share of tickets resolved in each category. The fix is a route to an agent for the odd ones (Chapter 1 builds that route).

The road

The lecture has five parts, and this lesson follows them in order: the workflow patterns, the reasoning and acting patterns, the context patterns, and a case study of the Pi harness.

  1. Chaining and routing: split a task into steps, or send each input to the right handler.
  2. Parallelization and orchestrator-workers: run calls side by side, or let one model hand out the jobs.
  3. Evaluator-optimizer, and real compositions: a critique loop, then STORM and Archon.
  4. ReAct: think out loud before every action.
  5. Reflexion and CRITIC: turn failures into notes, and check with tools.
  6. CodeAct: write the action as a small program.
  7. ReWOO and LLMCompiler: plan first, then execute, in parallel.
  8. Context principles, event logs and offloading: keep it focused, keep it continuous.
  9. Compaction, masking and isolation: three ways to shrink what the model reads.
  10. Case study: Pi: a minimal harness that uses ReAct and three context patterns.
  11. Field guide: the numbers, a checklist and the core code on one page.
A system calls a language model three times in a fixed order, and ordinary code decides what happens between the calls. What is it?

Chapter 1

Chaining and Routing

Split one hard prompt into easy steps, then send each input to the handler that suits it

You ask a model to turn a pile of messy meeting notes into a finished product brief, with the right sections, in one go. Sometimes it is good. Sometimes it forgets the metrics section, or it invents a user group. One prompt is carrying too much.

The lecture's workflow patterns come from Anthropic's essay Building Effective Agents, the course reading. The slide lists five. This chapter covers the first two, and the next two chapters cover the rest. All five are workflow patterns: your program holds the control flow, and each pattern is a small shape you can combine with the others.

Prompt chaining: many easy calls instead of one hard call

Prompt chaining decomposes a larger task into a series of smaller steps. Each model call reads the output of the call before it. The lecture's slide draws this as three green boxes in a row, with a diamond between the first two: a gate. A gate is a plain-code check on an output. If the output passes, the chain goes on. If it fails, the chain exits.

The slide gives the trade in one line: chaining trades latency for accuracy. You wait for several calls instead of one, but each call has an easier job, so each is more likely to be right. Anthropic's essay gives two examples: write marketing copy, then translate it; or write an outline, check that it meets the criteria, then write the document from the outline.

Here is the brief task as a chain. The data flow is plain text from step to step, and the gate is ordinary Python.

pythonoutline = llm(f"Outline a product brief from these notes:\n{notes}")        # call 1: notes in, outline out
if not all(s in outline.lower() for s in ["problem", "users", "metrics"]):
    return None                                                       # the gate: no model, just a check
brief = llm(f"Write the brief from this outline, section by section:\n{outline}")  # call 2

Now put numbers on the trade. Say one hard prompt gets the brief right 60% of the time. Split into steps, each call is simpler and gets its step right more often. Chain four steps at 90% each and the whole chain is right about 0.9 × 0.9 × 0.9 × 0.9 = 65.6% of the time. Four calls at 2 seconds each take 8 seconds instead of 2.

That is a small gain for a large wait. Add a gate after each step that catches 80% of the bad outputs and retries once, and the step is right more often (the device does this arithmetic). Try it. Find the point where the chain stops being worth it.

Price the chain

The boxes are model calls and the diamonds are gates. The bars compare the chain with one hard call. Drag the number of steps and the accuracy of each step.

4
90%

Illustrative numbers, not from the lecture: one hard call is right 60% of the time and takes 2.0 s; every chain call takes 2.0 s. With a gate, a bad output is caught 80% of the time and the step is retried once, so a step is right with probability a + (1 − a) × 0.8 × a, and a retry adds a call.

The lesson: chaining wins only when splitting makes each step much more reliable than the one big prompt. A chain of weak steps multiplies its errors. Gates help because they stop a bad chain early, before later calls waste time on a broken input.

Routing: the right handler for each input

A bank's front desk does not send every caller to the same person. A short question goes to the first desk. A fraud case goes to a specialist. Routing does this for model calls: one call classifies the input, then your code sends it to a handler. The handler can differ in the prompt, in the tools, or in which model it uses.

The slide gives two reasons. A complex task may have several categories that deserve different processing. And you can save money and time by sending easy cases to a weaker, cheaper model. A routing step is usually a small model and a one-word answer.

pythonlabel = llm_small(f"Reply with one word (refund, bug or other):\n{ticket}")   # the router: a cheap call
HANDLERS = {"refund": (BIG, REFUND_PROMPT), "bug": (BIG, BUG_PROMPT), "other": (SMALL, GENERIC_PROMPT)}
model, prompt = HANDLERS.get(label, HANDLERS["other"])                   # plain code picks the path
answer = llm(model, prompt + ticket)

On the wire, the router is tiny. The request is one short message with a low cap on the reply length, such as {"model": "small", "max_tokens": 3, "messages": [{"role": "user", "content": "Reply with one word...\nMy refund never arrived"}]}. The reply is one word, refund. Your code looks that word up in the table. A reply such as Refund. with a capital and a full stop would miss the table, so clean the word first (lower case, strip punctuation) and fall back to other when it still does not match.

Routing has its own failure mode. The symptom: hard tickets get thin answers. The measurement: compare what the router said with the true category on a sample of tickets, and count how often a hard ticket went to the cheap handler. The fix: send the router's unsure cases to the strong handler, so a mistake costs money and not quality.

Price the router

Three systems answer the same tickets. Drag the share of easy tickets and compare cost with the share resolved. The router is right 92% of the time.

70%

Illustrative cost units and rates, not measurements. Small model: 1 unit per ticket, resolves 95% of easy and 40% of hard tickets. Large model: 12 units, resolves 97% of easy and 85% of hard. The router costs 0.5 units. A misrouted ticket pays for the handler it reached.

At 70% easy tickets the router reaches about 91% resolved for about 5.2 units per ticket. The large model alone reaches about 93% for 12 units. You give up two points and save more than half the cost. At 0% easy tickets, the router adds its own cost and saves nothing. Routing pays only when the inputs really differ.

A chain of four steps is each right 70% of the time, while one hard call is right 60% of the time. What should you expect from the chain?

Chapter 2

Parallelization and Orchestrator-Workers

Run several model calls at once, and let one model decide how many jobs to hand out

A newspaper desk is about to publish a story. A lawyer checks it for legal risk. A fact checker checks the numbers. A copy editor checks the grammar. Nobody waits for anybody, because the three checks do not depend on each other. The story goes out when all three finish.

That is parallelization: you divide the work among several model calls that run at the same time, and your code collects the results. The lecture's slide shows one input fanning out to three calls, which feed an aggregator, a step that combines the outputs into one. The slide names two forms.

Form one: sectioning

Sectioning splits one job into independent parts and runs the parts side by side. The slide's example: flag a query as safe or unsafe while, at the same time, you process that query. One call does only the safety check. Another call does only the answer. Each call can focus on a single aspect, and the slide lists that focus as a benefit of the whole pattern.

Why run the safety check beside the answer instead of before it? Time. If each call takes 2 seconds, checking first and answering second costs 4 seconds. Running both at once costs 2. If the check says unsafe, your code throws the answer away. The price is some wasted tokens on the answers you discard. The aggregator here is not a model at all: it is one line of code, if flagged: return refusal.

Form two: voting

Voting sends the same input to the model several times, and the aggregator makes the final call, for example by taking the majority answer. The lecture ties this to inference-time scaling: you spend more computation while answering, to buy more accuracy.

The arithmetic is exact when the calls are independent. Say each call is right with probability p = 0.7, and you take a majority vote of 3 calls. The vote is right if all 3 are right, or if exactly 2 are right. That is 0.7³ + 3 × 0.7² × 0.3 = 0.343 + 0.441 = 0.784. Five calls give 0.837. Fifteen calls give about 0.95.

The catch is the word independent. Five calls to the same model with the same prompt often make the same mistake, for the same reason. Then the vote just repeats the mistake with more confidence. The device lets you set how much of the error is shared: the more the calls share their mistakes, the flatter the curve.

Vote with n calls

The curve is the accuracy of a majority vote as the number of calls grows. The dashed line is one call. Drag the number of calls, then raise the share of mistakes the calls have in common.

5
70%
0%

The independent case is exact: the sum over k above n/2 of C(n, k) p^k (1 − p)^(n − k). Shared mistakes use a simple toy mixture, not a measurement: with that probability all calls copy one common answer (right with probability p), otherwise they are independent.

Orchestrator-workers: the job list is not known in advance

Parallelization has one weakness. You wrote the list of calls in code, so you decided in advance how many there are. Suppose you ask an assistant to change a program in several files. How many files need changes? You cannot know until you read the request and look at the code.

In orchestrator-workers, one model, the orchestrator, breaks the task into subtasks on the fly and delegates them to worker models. A last step, a synthesizer, merges the results. The slide puts the difference in one line: it is similar to parallelization, but the subtasks are dynamically created. Use it when it is hard to anticipate the nature and number of subtasks. Anthropic's essay gives coding changes across many files and searches across many sources as examples.

The orchestrator's reply is data your code reads. Its length is the model's choice. Your code only loops over it.

pythonplan = json.loads(llm(f"Split this request into independent subtasks. Reply as JSON.\n{request}"))
# plan = {"subtasks": [{"id": 1, "file": "auth.py", "goal": "add a token check"},
#                      {"id": 2, "file": "routes.py", "goal": "call the check"}]}   (the model chose 2)
with ThreadPoolExecutor() as pool:                          # workers run side by side
    results = list(pool.map(lambda t: llm(f"Do only this: {t}"), plan["subtasks"]))
final = llm(f"Merge these results into one change:\n{results}")   # the synthesizer

Compare three designs on the same request with the next device. A sequential design does one subtask after another. A fixed parallel design has exactly three workers, because that is what the author wrote. The orchestrator plans first, then uses as many workers as the request needs.

Hand out the jobs

Each bar is one model call over time. Choose a design, then drag how many subtasks the request really needs. Watch the finish time and how many subtasks get done.

6

Illustrative times, not measurements: a worker takes 4 s, the orchestrator's planning call 3 s, the merge call 2 s, and the orchestrator can start as many workers as it needs at once. The fixed design handles at most 3 subtasks because its code has 3 calls.

With 6 subtasks, the sequential design needs 26 seconds. The fixed design needs only 6 seconds but finishes half the job. The orchestrator needs 9 seconds and finishes all of it. Its planning call is the price of flexibility. With 3 subtasks, the fixed design wins on time, because it skips the plan.

Two failure modes to watch. For voting, the symptom is more votes with a flat accuracy curve. The measurement is accuracy against the number of calls on a labelled sample. The fix is to make the calls differ (different prompts or models) or to add a checker. For orchestrators, the symptom is a plan of twelve overlapping subtasks and a huge bill. The measurement is the total tokens spent by all workers. The fix is a cap on the number of subtasks and a narrow, written brief for each worker (Chapter 9 returns to this under context isolation).

Five calls to the same model with the same prompt keep making the same wrong answer. Why does a majority vote not fix it?

Chapter 3

Evaluator-Optimizer, and Real Compositions

Draft, critique and redraft in a loop, then see how STORM and Archon stack all five patterns together

You write a cover letter and hand it to a friend. The friend says: "The second paragraph is twice as long as the rest. Cut it to three sentences." You fix it and hand it back. Two rounds later it is good. The loop worked because your friend gave you feedback you could act on.

The fifth workflow pattern is that loop, with two models. In evaluator-optimizer, one model, the generator, writes a response. Another model, the evaluator, judges it and returns feedback. If the evaluator accepts, the loop ends. If it rejects, the feedback goes back to the generator, which tries again. The slide draws it as two boxes joined by a Solution arrow going one way and a Rejected-plus-feedback arrow coming back.

When the loop works

The slide gives two necessary conditions. First, the feedback must be clear and articulable: the evaluator can say, in words, what is wrong. Second, a language model must be capable of giving that feedback. The slide adds a third point: the generator must be able to improve when it receives the feedback. Anthropic's essay gives two example uses: literary translation with nuances that a first pass misses, and complex searches that need several rounds.

In code the loop is short. The evaluator's reply is data, so ask for a format your code can read.

pythondraft = llm(f"Write a headline, 10 words or fewer, for: {story}")
for round in range(5):                                       # always cap the rounds
    verdict = json.loads(llm(f"Judge this headline. Reply as JSON.\n{draft}"))
    # {"verdict": "reject", "feedback": "14 words; the limit is 10. Cut the second clause."}
    if verdict["verdict"] == "accept": break
    draft = llm(f"Rewrite using this feedback: {verdict['feedback']}\n{draft}")

The next device runs this loop on a toy task: a headline that must come within one word of 10 words. The generator starts around 25 words long. Three kinds of evaluator are on offer. A clear evaluator says how far off the draft is. A vague evaluator only says "not good enough", so the generator must guess again. A rubber-stamp evaluator speaks clearly but accepts a third of the drafts without looking.

Run the critique loop

The dots show the length of each draft. The green band is the accepted range, 9 to 11 words. Choose an evaluator and press Run. Then read how it fares over 400 seeded tasks.

Toy model, not a measurement. With clear feedback the generator closes about two thirds of the gap each round, with a little noise. With vague feedback it redraws a length from 4 to 40 words. The rubber stamp accepts any draft with probability 1/3. The summary line runs 400 tasks with a fixed seed, at most 6 drafts each.

Clear feedback fixes about 96% of the toy tasks, in four drafts on average. Vague feedback fixes about 38%. The rubber stamp gets about 23% right, in three drafts.

Vague feedback is a random search with extra steps. And a rubber-stamping evaluator is the dangerous one: it ends the loop early with a wrong answer and no warning.

This matches the lecture's two conditions. An evaluator that cannot judge, or feedback that cannot be acted on, turns the loop into noise. The failure shows as a loop that runs to its cap. You measure it by the share of tasks accepted that a human also accepts. The fix is a sharper rubric, or a check that does not depend on a model, such as a word count.

Real systems are compositions

The lecture then makes a key point: real systems are compositions of these basic patterns. Its first example is STORM, a Stanford system that writes a Wikipedia-style article from a topic. Its authors describe it as a writing system for pre-writing: it discovers different perspectives on the topic, simulates conversations between a writer and an expert grounded in trusted web sources, and curates what it collects into an outline.

The slide marks up STORM's diagram with red boxes. Part of it is orchestrator-workers (with a note that it is close to parallelization in this instance). The question-and-answer part is approximately evaluator-optimizer. The stages in sequence are prompt chaining. The collected conversations are parallelization. Try the labelling yourself before you read the marks.

Label the STORM parts

Each card describes one part of STORM in our words. Choose the pattern the lecture's slide marks it with.

The marks are the lecture's own, drawn on STORM's diagram from the STORM paper (Shao et al., 2024). The lecture itself calls two of the marks approximate, so a close call is expected.

STORM's authors report that, against a baseline that retrieves documents and writes from an outline, more of STORM's articles were judged organized (a 25% absolute increase) and broad in coverage (by 10%), in an evaluation with experienced Wikipedia editors. Composition is where the value is.

Searching for the composition: Archon

If real systems stack patterns, how do you pick the stack? The lecture's second example, Archon, treats it as a search problem. You give it a target benchmark, a budget of model calls, and a list of available models. A search procedure (Bayesian optimization, which tries configurations and learns from the scores) builds an architecture from standard parts and returns the best one it finds.

The parts are named by what they do. A generator writes candidate answers. A fuser merges several candidates into one. A critic writes strengths and weaknesses for each. A ranker returns the best few. A verifier and a pair of unit-test parts check reasoning and code. You can see the old patterns inside: generators in parallel, a critic as the evaluator, a ranker as a vote. The lecture's example for math has four generators from different models, a critic, a ranker, fusers and a verifier.

Archon's authors report that the architectures it found outperformed frontier models such as o1, GPT-4o and Claude 3.5 Sonnet by 15.1% on average, and the lecture's chart shows its score climbing as the call budget grows. The lecture's recap states the practical rule: workflows are simpler to reproduce and debug than agents, and real workflows are larger compositions of the five patterns.

An evaluator-optimizer loop keeps running to its round cap, and the evaluator only ever replies "not good enough". What is the likely cause?

Chapter 4

ReAct: Think, Then Act

Make the model write its reasoning before every action, and watch that one habit keep it on the question

Two detectives hunt for the same missing ring. The first runs from room to room, opening drawers. The second stops before each move and says out loud: "The maid saw it last on Tuesday, so I will check the guest room first." The second detective is easier to follow, and she is harder to lead astray. She keeps the question in her head.

The lecture's section on agents starts with a reminder. An agent is a model in a loop with a human, an environment, actions and feedback. Besides the tools themselves, you must design how the model reasons and interacts with the environment. The first design is ReAct (2023), short for Reason plus Act. The slide gives its key insight in five words: reason before taking actions.

The three-line loop

ReAct writes the agent's work as a transcript with three kinds of line. A Thought is the model reasoning in plain words. An Action is a tool call in a fixed format, such as Search[Apple Remote]. An Observation is the tool's result, written by your code, not by the model. The three repeat until the model writes Finish[answer].

The data flow matters, so here it is exactly. Your code sends the model the instructions, a few worked examples and the question. The model writes a Thought and an Action, and then it would keep going and invent an Observation. So you give the model a stop sequence: a string that makes generation halt. Stop on Observation:. Your code runs the tool, appends the real Observation to the transcript, and calls the model again with the longer transcript.

pythontranscript = FEWSHOT + f"Question: {question}\n"
for step in range(1, 8):                                  # always cap the steps
    out = llm(transcript + f"Thought {step}:", stop=[f"\nObservation {step}:"])
    transcript += f"Thought {step}:" + out           # the model's thought and action
    action = parse_action(out)                    # e.g. ("Search", "Apple Remote")
    if action.name == "Finish": return action.arg
    transcript += f"\nObservation {step}: {run_tool(action)}\n"   # real text from the real tool

The lecture's example is a question from the HotpotQA benchmark: aside from the Apple Remote, what other device can control the program the Apple Remote was originally designed to interact with? No single search answers it. The first search finds the program, Front Row. The second finds nothing, because the page is named differently. The third finds the right page, which names the answer. Step through it below, and then switch to a version without the Thoughts.

Step the loop

The bar is the transcript so far, one block for each line. Press Next step to add the next Thought, Action and Observation. Then reset and choose Act only to remove the Thoughts.


    

The question and the shape of the trace follow the ReAct paper's Figure 1 (Yao et al., 2023); the wording of the lines is shortened and paraphrased by us, and the token counts are our estimate at 4 characters per token. In the paper's figure the Act-only run sees the same observations but answers "yes".

Look at Thought 2 and Thought 3. Thought 2 says what to do and why: the Apple Remote was made for Front Row, so search Front Row. Thought 3 notices that the search failed and picks a better name. Without Thoughts, the model sees the same results but never restates the goal. By step 4 it has lost what the question asked, and it answers "yes" to a question that wanted a device.

There is a cost hidden in the loop. Every call sends the whole transcript again. Call 1 sends the question. Call 4 sends the question plus three full rounds. The total the model reads across the run is the sum of all those growing prompts, which is far more than the final transcript alone. Chapter 7 shows a pattern, ReWOO, that attacks exactly this cost.

The numbers, and a surprise about fine-tuning

The paper's abstract reports the headline: on two interactive decision-making benchmarks, ALFWorld and WebShop, ReAct beat imitation learning and reinforcement learning methods by an absolute success rate of 34% and 10%, using only one or two worked examples in the prompt. The lecture's table is smaller. With a 540-billion-parameter model prompted this way, HotpotQA exact match goes from 25.7 for acting alone to 27.4 for ReAct, and Fever accuracy from 58.9 to 60.9. The gain is real but modest on question answering, and the lecture reads it as: it is useful to reason before taking actions.

A second slide adds a twist. The original paper found that you need to fine-tune the model for the best performance. Today that is routine: labs fine-tune models to act as agents during post-training, so the Thought-then-Action habit is built into the weights. Including thoughts before actions is, in the lecture's words, still very common today. You will meet it again in Chapter 10, where the Pi harness runs a ReAct-style loop.

One failure to plan for. The symptom: the agent repeats the same search three times in a row, and its Thoughts say the same thing. This is an observation from practice, not a number from the paper. The measurement: count identical Actions inside one run. The fix: cap the steps (the code above does), and when an Action repeats, feed the model a line such as "You already tried this search".

Go deeper on the paper in our ReAct Veanor.

In a ReAct loop, who writes the Observation lines, and why do we set a stop sequence?

Chapter 5

Reflexion and CRITIC: Learn From the Last Try

Turn a failed attempt into a short written note, and see when that note helps and when it fools you

A student fails a practice exam. She can retry the same exam with no changes, and she will probably fail the same way. She can reread her old answers, which helps a little. Or she can write one line: "I misread the units on question 3, so next time I underline them first." That line is the most useful thing she owns.

The lecture's next pattern is Reflexion (2023). Its key insight, from the slide: self-reflection is useful. More exactly, it turns evaluations and reflections into memory, which is context for the actor model to read on its next try.

Three roles and two memories

The algorithm on the slide has three model roles. The actor acts in the environment and produces a trajectory: the list of its actions and what it observed. The evaluator scores the trajectory. The self-reflection model reads the trajectory and the score and writes a short text about what went wrong. The slide names two memories. The trajectory is short-term memory, since it lasts for one trial. The reflections are long-term memory: they stay in the actor's prompt for all later trials.

The loop is simple. Try, score, and if the score is bad, write a note and try again with the notes in the prompt. The weights of the model never change. All the learning lives in text.

pythonmemory = []                                             # long-term memory: short notes in plain text
for trial in range(MAX_TRIALS):
    traj  = actor(task, notes=memory)                   # short-term memory: this trial's actions and results
    score = evaluate(traj)                              # from the environment: tests pass? reward? (see the limit below)
    if score == 1: return traj
    memory.append(reflect(task, traj, score))           # "I guessed 8 and was told higher. The answer is above 8."
    memory = memory[-3:]                                # keep only a few notes, so the prompt stays small

The paper's headline number is on code. Reflexion reaches 91% pass@1 on the HumanEval coding benchmark, where the previous best, GPT-4, scored 80%. The lecture's plots show the pattern across tasks: on HotpotQA, adding Reflexion to ReAct keeps raising the share of solved tasks over six trials, while ReAct alone stays flat. A second plot isolates the cause. Giving the actor only its past trajectories helps a little. Adding the written reflection helps more. In the slide's words, it is the reflection that helps, not just the past trajectories.

Why the note beats the replay

Here is a toy that shows why. A secret number from 1 to 16 is hidden. Each trial the actor guesses a number, and the environment replies correct, higher or lower. With no memory, the actor guesses at random every trial. With past trajectories only, the actor can see its history, but only half the time does it use it well. With a reflection, a short note says exactly what the replies mean: the answer is between 9 and 16. The next guess is the middle of that range.

Retry with a note

Each line shows the share of 400 tasks solved by each trial. Choose a kind of memory. The chosen line is bright and the others stay faint.

Toy model, not the paper's experiment: secret number 1 to 16, six trials, 400 seeded tasks. Past trajectories: half the guesses fall inside the range the history allows, half are random. Reflection: 90% of guesses are the middle of the allowed range. Self-judged: no reply from the environment, and after each wrong guess the model wrongly declares success with probability 0.3.

Read the lines at trial 4. With no memory, about a quarter of the tasks are solved. With past trajectories, about 39%. With a reflection, about 89%, because each note halves the search range. The reflection did not give the actor new ability. It turned a pile of raw replies into the one conclusion the actor needed.

Walk one task by hand, with the secret set to 11. Trial 1: guess 8, reply higher, note: "the answer is 9 to 16". Trial 2: guess 12, reply lower, note: "9 to 11". Trial 3: guess 10, reply higher, note: "11 only". Trial 4: guess 11, correct. Each note is one line, about 15 tokens, and the next prompt carries it. Four trials found the answer, and no single guess was wasted.

The limit: who judges?

The fourth line is the warning, and the lecture makes the same point. A study of self-correction found that when a language model is asked to evaluate its own responses, performance decreases. Reflexion gets around this with external environment feedback: a test result, a game reward, a reply that does not come from the model's opinion. In the toy, the self-judged actor stops early on a wrong guess about a third of the time, and the line flattens at 45%.

The lecture adds a note on time. This finding pre-dates reasoning models, which show impressive ability to correct themselves inside their own reasoning. Today self-reflection is typically built into the model's reasoning itself and not enforced as a separate step.

One more idea from the slides is CRITIC (2024). Its chart shows a verifier that can call external tools (a search engine, a code interpreter, a calculator) improving over iterations, while the same loop without tools stays flat. The lesson: make the verifier agentic. A critic who can look things up satisfies the evaluator condition from Chapter 3: a model that is capable of giving clear feedback.

The failure to watch: the second try is no better, or worse, after "reflecting". The measurement: success rate by trial number, with and without a real external signal. The fix: give the evaluator ground truth, such as unit tests, not a second opinion from the same model. Go deeper in our Reflexion Veanor.

A Reflexion-style agent has no tests and no environment reward. A model both tries and judges its own work, then writes notes. What should you expect?

Chapter 6

CodeAct: Actions Written as Code

Let the model write one small program for a whole job, instead of one tool call per turn

You need to find the cheapest country to buy a phone from four candidates. You can phone a helper and say: "Look up the exchange rate for Germany." They reply. You say: "Now the price in Germany." They reply. You say: "Now convert and add tax." That is twenty calls for four countries. Or you can hand over a short script: "For each country, do these five steps, then pick the lowest." One call.

That is the whole idea of CodeAct (2024). The slide states it as a key insight: code is the right form factor for actions. An action is what the model emits so that something happens in the world. Up to now the actions in this lesson were text lines such as Search[Apple Remote]. Most agent frameworks use JSON actions: one structured tool call per turn. CodeAct lets the action be a program.

The same job, two ways

The lecture's example is a purchase question: determine the most cost-effective country to buy the smartphone model "CodeAct 1"; the countries are the USA, Japan, Germany and India. Five tools are available. lookup_rates(country) returns an exchange rate and a tax rate. lookup_phone_price(model, country) returns the local price. convert_and_tax(price, rate, tax) returns a price in dollars with tax. estimate_shipping_cost(country) returns shipping. estimate_final_price(converted, shipping) adds them.

With JSON actions, each turn is one request, and the reply comes back before the next one. The data flow is a long conversation:

json// turn 1, the model writes:  {"tool": "lookup_rates", "arguments": {"country": "Germany"}}
// observation 1, your code writes: {"exchange_rate": 1.08, "tax_rate": 0.19}
// turn 2, the model writes:  {"tool": "lookup_phone_price", "arguments": {"model": "CodeAct 1", "country": "Germany"}}
// ... five turns per country, then the same again for every other country ...

With a code action, the model writes one block, and your sandbox runs it. The loop, the variables and the comparison are all inside the block:

pythonbest = {}
for country in ["USA", "Japan", "Germany", "India"]:
    rate, tax = lookup_rates(country)
    price = lookup_phone_price("CodeAct 1", country)
    converted = convert_and_tax(price, rate, tax)
    best[country] = estimate_final_price(converted, estimate_shipping_cost(country))
cheapest = min(best, key=best.get)             # reuses Python's own min, no new tool needed
print(cheapest, round(best[cheapest], 2))     # the observation the model reads: "Japan 904.0"

The slide's callouts name two gains. The control flow and data flow of code (loops, variables, conditions) simplify complex operations that would take many turns. And the model can re-use existing software: it did not need a min tool, because Python already has min. Add a third reason of our own: models have read enormous amounts of code, so writing it is a skill they already have.

Count the cost with the device. Both styles make the same tool calls. The difference is how many times the model must be called, because each model call takes seconds and a tool call takes a fraction of one.

Count the turns

Warm squares are model turns. Blue squares are tool calls. Choose a style, then drag the number of countries. The tools below are really run in your browser on toy data.

4

    

The five tool names follow the lecture's example. Every price, rate and tax is made up by us, so the numbers are a toy, chosen so that Japan wins at 4 countries, as in the lecture. Time is illustrative: 3 s per model turn and 0.2 s per tool call. JSON mode needs 5 tool turns per country plus one final answer turn; code mode needs one code turn plus one final answer turn.

At 4 countries the JSON agent needs 21 model turns. The code agent needs 2. The tool calls are the same 20. Because the model is the slow part, the code agent finishes in about 10 seconds instead of about 67. Add countries and the JSON agent grows by 5 turns per country. The code agent stays at 2.

What does the model actually see? Not JSON schemas, but Python. The prompt lists the tools as function signatures with their types, such as lookup_phone_price(model: str, country: str) -> float. The model replies with a code block. The harness pulls the block out, runs it in a live interpreter, and sends back whatever the program printed, or the error. The interpreter stays alive between turns, so a variable such as best is still there on the next turn. That is a form of memory that JSON actions do not give you for free.

Errors are where the two styles differ most. Say the model forgets that lookup_rates returns two values and writes rate = lookup_rates(country). The program then fails on the next line. The harness sends back TypeError: unsupported operand with the line number. The model reads it, sees its own mistake and rewrites the line. With a JSON action the same slip is a malformed argument, and it costs a whole extra turn.

The results, and the safety bill

The lecture's chart shows the effect across several models: with code as the action, the success rate is higher, and the task takes fewer turns. The paper's abstract puts the best case at up to 20% higher success rate, from an analysis of 17 language models. The authors also released a training set of 7,000 multi-turn interactions in this style, and an open model fine-tuned on it. Our CodeAct Veanor goes through the paper.

Now the cost. A program written by a model is code you did not review, and it runs. So the code must run in a sandbox: an isolated container with no access to your files, a time limit and a memory limit. The failure to plan for: the generated program crashes, hangs or does something unwanted. The measurement: the crash rate and the run time per action. The fix: a sandbox with limits, and a design where a crash is not fatal. The error message (a traceback) comes back to the model as the observation, and the model fixes its own code on the next turn.

Why does a code action cut the number of model turns for the phone-price job, even though the same tools are called?

Chapter 7

ReWOO and LLMCompiler: Plan First, Then Execute

Write the whole plan up front, run the tools without calling the model again, and run the independent ones at once

A general plans a campaign. In the ReAct style, she sends one scout, waits for the report, thinks, and sends the next. Every report goes through her. In the other style, she studies the map once, writes orders for all the scouts, and sends them out together. She reads the reports once, at the end. The second general talks less and finishes sooner. She also has less room to change her mind.

The slide gives this pattern a key insight that links back to Chapter 0: planning enables turning agent action execution back into workflows. A plan is the control flow, written ahead of time. Once it exists, your code can run it like a workflow.

ReWOO: reasoning without observation

ReWOO (2023) stands for Reasoning WithOut Observation. It splits ReAct's loop into three parts. A planner model writes the whole plan in one call, using placeholders (named blanks such as #E1) for the results it does not have yet. A set of workers, plain code, run the tools in plan order and fill the blanks. A solver model reads the plan and all the evidence once, and writes the answer.

Here is a plan for a made-up shop question, how much more does the Aria laptop cost than the Brio laptop? The tool results are toy values.

planPlan: Look up the Aria price.            #E1 = price_lookup[Aria]            # no model call
Plan: Look up the Brio price.            #E2 = price_lookup[Brio]
Plan: Subtract the second from the first. #E3 = calc[#E1 - #E2]              # fills in #E1, #E2 first
# after the workers run:  #E1 = 1240   #E2 = 980   #E3 = 260
# the solver is called once with the question + the plan + the three results, and answers: 260

Why does this save tokens? In the ReAct loop of Chapter 4, every call re-reads the whole transcript. In ReWOO the model is called twice, once to plan and once to solve, and the workers never call a model for their own steps. The paper's abstract reports 5 times the token efficiency and a 4% accuracy improvement on HotpotQA. The lecture's scatter plot shows the same: accuracy goes up while token use goes down. The authors also show you can move the planning skill from a 175-billion-parameter model into a 7-billion-parameter one by fine-tuning, since the planner no longer needs to watch the tool results.

Count the tokens yourself. The device charges both styles for every token the model reads and writes.

Count the tokens

Two bars show every token the model reads (dark) and writes (light). Drag the number of tool calls the question needs. The ReAct bar grows faster than the number of calls.

4

Illustrative sizes, not the paper's measurements: 800 tokens of instructions and examples, a 30-token question, 60 tokens of thought and action per ReAct step, 300 tokens per tool result, 40 tokens per plan line, 300 tokens of solver instructions, a 40-token answer. ReAct makes k + 1 calls, each re-reading everything before it. ReWOO makes 2.

At 4 tool calls the toy ReAct run spends about 8,050 tokens and ReWOO about 2,720, close to 3 times fewer. At 8 calls the ratio is about 5. The more steps, the bigger the gap, because ReAct's cost grows with the square of the steps and ReWOO's grows in a line.

Follow what each part reads. The planner sees the question and the tool list, and writes about 40 tokens for each step. A worker reads one plan line and a few earlier results, and never calls the model. The solver reads everything once: the question, the plan and every result. That final prompt is the biggest in the run, but it is read one time. In a ReAct loop the same text would be read again at every step.

LLMCompiler: a plan with a shape

ReWOO's workers still run the plan in order. But look at the plan above: the two price lookups do not depend on each other. Only the subtraction needs both. LLMCompiler (2024) uses that. Its planner writes the tasks as a DAG, a directed acyclic graph: tasks as nodes, with an arrow from each task to the ones that need its result. A task fetching unit starts every task whose inputs are ready, and an executor runs them in parallel. The slide lists the two differences from ReWOO: parallel execution and dynamic replanning, which means the planner can be called again when a result changes the picture.

The lecture's example asks how much Microsoft's market cap must grow to pass Apple's. Two searches run at once. The calculation waits for both. The paper's abstract reports latency speedups of up to 3.7 times, cost savings of up to 6.7 times and accuracy gains of up to about 9% over ReAct.

Run the plan

Each bar is a task. Choose how the plan runs, drag the number of independent searches, and turn on a failed search to see what a fixed plan does.

2

Illustrative times: planning 3 s, a search 2 s, the calculation 0.5 s, the final answer 3 s, a replanning call 3 s. LLMCompiler's real speedups are in its paper (up to 3.7 times); these numbers only show why the shape of the plan matters.

Today this idea hides inside ordinary APIs. When a model returns several tool calls in one message, for example "tool_calls": [{"name": "search", "arguments": {"q": "Microsoft market cap"}}, {"name": "search", "arguments": {"q": "Apple market cap"}}], your code can run them at once. The lecture's recap says exactly this: compiling workflows is mostly done with parallel tool calls today, planning is still important, and sometimes workflows still orchestrate sub-agents.

The failure to plan for is a plan that goes stale. Symptom: one early tool fails, and every step after it runs on a blank, then the solver writes a confident wrong answer. Measurement: the share of runs with a failed tool whose final answer is wrong. Fix: replan when a task fails (as LLMCompiler does), or fall back to a ReAct loop for the broken branch.

Why does ReWOO use far fewer tokens than a ReAct loop on a five-tool question?

Chapter 8

Context Principles, Event Logs and Offloading

Keep the model's reading small and continuous, keep a perfect record on the side, and move bulky facts out of the way

Two desks. The first is buried in paper: every letter, every receipt, every draft since January. The second has one page on top and a filing cabinet beside it. Ask each person a question about last week. The first person digs for ten minutes and finds the wrong receipt. The second reads one page, opens one drawer and answers.

The lecture's last big section is about the second desk. Look again at the agent diagram from Chapter 4. This time a box sits between the model and everything else: the context manager. Each time the model is called, the context manager decides what the model reads. The craft of making that decision well is context engineering. Anthropic's essay on it frames the contrast. Prompt engineering is about writing one good prompt for a single-turn query. Context engineering is about curating everything in the window, across many turns: the system prompt, the tool descriptions, the examples, the message history and the data the tools return.

Why more context is not better

The slide shows a famous test, the needle in a haystack. Someone hides one fact (the needle) at a chosen depth inside a very long document (the haystack), asks the model to find it, and repeats at many lengths and depths. The slide's heat map, for a 200,000-token model, shows retrieval getting worse as the context grows. Anthropic's essay calls this context rot: the more tokens in the window, the less reliably the model uses any one of them.

So the lecture gives two principles. Focus the context: keep only what the task at hand needs. The entire history does not need to be in the window, and excess information is context bloat. And preserve continuity: reshape the context without losing the requirements, goals, constraints and progress. The slide adds a practical reading of the second principle: it also means preserving the KV cache.

The cache that punishes edits

The KV cache (Lecture 2 builds it in full: LLMs for Builders) stores the work the model has already done on the tokens it read. If the next call starts with exactly the same tokens, the model reuses that work, and providers charge less for those cached tokens. The key word is starts. The reuse covers only the shared beginning.

Work the arithmetic. Say the prompt is 20,000 tokens, and a tool adds a 500-token result. If you append the result at the end, 20,000 tokens are cached and only 500 are new. If you instead edit something near the top, every token after the edit looks different, so all 20,500 are processed from scratch. With cached tokens priced at a tenth of normal, which is a typical shape (the exact discount varies), appending costs about 2,500 token-equivalents and editing the top costs 20,500. That is roughly eight times more. This is why context patterns prefer to append, and why the next two sections care about where a change happens.

Pattern one: the persistent event log

The five patterns on the lecture's overview slide are the persistent event log, memory offloading, compaction, observation masking and context isolation. This chapter takes the first two. The first answers a hard question: if you will trim what the model reads, where does the truth live?

In the persistent event log pattern, used by the OpenHands coding agent, every action and every observation is written to a log exactly as it happened. The log is append-only: it may be immutable. The model never reads the log directly. For every call, the system rebuilds the model's input from the log. The slide's pipeline has four stages: take the event list, filter the events that can become model messages, group the actions that came from one model response, and convert the groups into messages. A side benefit the slide lists: external observers can hook into the log to watch the system.

pythonlog = []                                                  # the truth: append only, never edited
def to_llm_input(log):                                       # a VIEW of the log, rebuilt on every call
    events = [e for e in log if e.llm_convertible]               # 1. filter: UI-only events stay out
    groups = group_by(events, key="llm_response_id")         # 2. parallel tool calls from one reply are one message
    return [to_message(g) for g in groups]                     # 3. convert to chat messages
reply = llm(to_llm_input(log))                            # the model reads the view, not the log

The pattern separates two jobs that are easy to confuse. The log is for remembering. The view is for reading. You may change the view as often as you like (shorter, summarized, reordered) and the record is untouched. The next device shows it. Switch the rules on and watch the log stay the same while the model's input shrinks.

Rebuild the model's view

Left: twelve events of a coding agent, never changed. Right: the messages the model would read. Turn on the rules one at a time.

A toy log written by us in the spirit of the OpenHands pipeline on the slide; the sizes are illustrative. Rule three keeps only the two newest tool outputs in full and replaces older ones with a 15-token stub.

Pattern two: memory offloading

Memory offloading moves facts out of the window into storage the agent can search later. The slide's example is MemGPT, which treats the context like a computer's fast memory and a store outside it like a disk. In its example chat, the user says their birthday is February 7. The agent calls a function to write that into its working context, and when the user later asks about a past event, it calls a search function on its recall storage. The slide also shows a memory pressure alert, a system message that tells the model the window is filling up, so that it saves what matters before old text is dropped.

The slide's summary: storing things to memory or files frees up parts of the context to prune. A coding agent does the same with files. A 3,000-token test report becomes a one-line pointer, saved to notes/test_report.txt, and the agent reads back only the lines it needs.

Offload to a file

Add steps until the window nears its limit. Then save the biggest result to a file and add more. Read back a few lines when the agent needs them.

Illustrative sizes. The window holds 8,000 tokens. Each step adds a 1,500-token tool result. A saved result leaves a 30-token pointer, and reading 20 lines back costs 250 tokens. The warning line at 70% is our toy, in the spirit of MemGPT's memory-pressure alert.

The failure modes. For the log: the view and the log drift apart, and the model acts on a claim the log contradicts. Measure it by replaying the log and comparing the rebuilt view with what was sent. Fix it by building the view in one function only. For offloading: the agent saves a fact and never reads it back. Measure how often a saved file is opened again. Fix it with a pointer that says what the file holds, so the agent knows when it needs it.

Why does the persistent event log pattern rebuild the model's input from the log on every call instead of editing one growing prompt?

Chapter 9

Compaction, Masking and Isolation

Shrink what the agent reads in three ways, then see how the four buckets of context engineering fit together

It is the end of a long semester, and your notebook holds four hundred pages. You have four options for the exam. Write a two-page summary of everything. Keep your final answers and erase the long working beside the old ones. Ask a lab partner to study one chapter and give you three lines about it. Or leave most of the notes at home and bring an index that tells you which page to open.

Those are the lecture's remaining context patterns, in order: compaction, observation masking, context isolation and progressive disclosure. Each shrinks what the model reads at a different cost.

Compaction: summarize the past

In compaction, a model reads the older part of the history (its reasoning, actions and observations) and writes a summary. The summary replaces those turns. The slide draws two columns of turns. In the raw agent, every turn stays. In the summarizing agent, the oldest turns collapse into one pink block, "summary of turns 1 and 2", and the recent turns stay raw. The slide adds that it can help for the compaction itself to be agentic: the model can decide what to keep, even looking things up to check.

Observation masking: hide the bulk, keep the thread

Where do the tokens actually go? The lecture shows a pie chart from a coding agent. In the raw agent, observations (the tool outputs) are 83.9% of the tokens. The agent's reasoning is 9.6% and its actions 6.5%. A file read or a test log can run to thousands of tokens, while the thought and the action that produced it take a few dozen.

That suggests a cheap trick. Instead of asking a model to summarize, mask the old observations: truncate them, or swap each for a short stub such as [output omitted]. Keep the model's own reasoning and actions, so the thread of what it did and why stays. This is especially useful for coding agents, where observations are long. The slide's last charts, from a study on SWE-bench Verified, compare solve rate against cost for the raw agent, masking and LLM summarization. Their abstract reports that simple masking halves the cost relative to the raw agent, and matches summarization's solve rate, sometimes slightly beating it. A hybrid of the two cuts cost a further 7% against masking and 11% against summarization, across five model setups.

Work a number. Say each step adds 1,500 tokens: 1,260 of observation, 144 of reasoning and 96 of action, close to the pie's shares. After 40 steps the raw context is 2,000 + 40 × 1,500 = 62,000 tokens. Now mask all observations except the newest 10, each stub costing 20 tokens. Old steps then cost 144 + 96 + 20 = 260 tokens, not 1,500. The context is 2,000 + 40 × 240 + 10 × 1,260 + 30 × 20 = 24,800 tokens, about 2.5 times smaller.

Context isolation and progressive disclosure

In context isolation, the agent hands a subtask to a sub-agent, a second model call with its own fresh window. The slide shows a plan on top and two agents below, each in its own dashed box: parallelize computation with isolated context windows. The sub-agent reads whatever it needs, which may be a lot, and returns a short result. The parent only ever sees that result. The lecture's wording: include in the context only what you need for the task at hand. Chapter 2's orchestrator-workers pattern is the workflow form of the same move.

Isolation moves tokens. It does not remove them. The sub-agent still reads its thousands of tokens, so the total bill can go up even as the parent's window stays small and focused.

Progressive disclosure applies the same logic to instructions. Anthropic's Agent Skills are files with a short header (a name and a one-line description) and a long body. The agent's first prompt includes only the headers. When a task matches a skill, the agent opens the body. You do not need all tools and context in the initial prompt: disclose things later, as needed.

Compare the four

Each line is the size of the agent's context at each step. Choose a strategy and drag the number of steps. The read-out also adds up every token the model reads over the run.

40

Illustrative rules, with shares taken from the lecture's pie chart: 2,000 tokens of system prompt and task; 1,500 tokens per step (1,260 observation, 144 reasoning, 96 action). Masking keeps the newest 10 observations and stubs older ones at 20 tokens. Compaction replaces everything older with an 800-token summary every 20 steps. Isolation hands each 5-step job to a sub-agent that returns 300 tokens; the sub-agent's own window peaks at 9,500 tokens and is not counted in the parent line.

The four buckets

The lecture closes the section with a taxonomy from the LangChain essay on context engineering, the second reading. It sorts every move into four buckets. Write context: save information outside the window, in a scratchpad (within one session) or in long-term memory (across sessions). Select context: pull the right pieces back in, such as relevant tools, notes, memories and knowledge. Compress context: summarize it to keep the relevant tokens, or trim it to drop the irrelevant ones. Isolate context: split it across state, a sandbox, or several agents.

Our five patterns land in these buckets. The event log and offloading are Write, and reading a file back is Select. Compaction and masking are Compress (summarize and trim). Isolation and sub-agents are Isolate. The lecture marks two cells for later: retrieving long-term memory is Wednesday's topic, and partitioning across multi-agent systems is next Monday's. The lecture's note on all of this: the strategies are compatible. You can offload to memory and then compact. You can build the context from an event log and also truncate the observations. Real systems combine many or all of them.

The failure to plan for is the forgotten constraint. Symptom: after a compaction, the agent repeats a mistake you told it about an hour ago, such as "do not edit the config file". Measurement: replay the run, and after each compaction ask the agent a question whose answer sits only in the dropped turns. Fix: write the summary prompt to preserve requirements, goals, constraints and progress (the lecture's continuity list), and pin a short task-notes block that no compaction may touch. Our own reading adds a cache cost: every compaction or sliding mask rewrites tokens near the start of the context, which breaks the KV cache from that point. Mask and compact in rare, large steps.

A coding agent's observations are about 84% of its tokens. Which move cuts the most tokens with the least extra model work?

Chapter 10

Case Study: Pi, a Minimal Harness

Read a real coding agent as a short list of design choices, each one a pattern you now know

Two carpenters arrive at a job. One unloads a van with two hundred tools. The other opens a single belt with four: a tape measure, a saw, a hammer, a pencil. Anything else she makes from those. Which is easier to carry, to learn, and to fix when it breaks? And which one can hurt you with a tool you forgot was in the van?

The lecture's third learning objective is to analyze the design decisions inside a production agent harness. A harness is the program around the model: the loop, the tools, the context manager and the safety rules. The case is Pi, a coding-agent harness built to be minimal. Its slide gives the philosophy in one line: adapt Pi to your workflows, not the other way around. Pi is extremely basic, and the community adds features as extensions on top.

What Pi leaves out

The slide lists five things Pi does not have: no sub-agents, no permission checks, no plan mode, no to-do lists for the agent, and no bash running in the background. Each is a feature that mainstream harnesses ship. Pi's bet is that a small core you can read in an afternoon beats a large one you must configure. A feature you need becomes an extension you write or install.

The tools follow the same rule. The documentation lists read, bash, edit, write, and a few more (grep, find, ls). Only read, bash, edit and write are on by default. Everything else is a subset of bash: grep is a shell command, so a separate grep tool is bloat. Four tools means short tool descriptions, which means a short system prompt, which leaves more of the window for work. That is Chapter 8's first principle, applied to the tool list.

The loop: ReAct with JSON actions

The slide calls Pi's loop ReAct style: reason before acting, then act with a JSON tool call. So Pi uses Chapter 4's thought-then-action habit, and the JSON action style, not Chapter 6's code actions. A JSON call here looks like {"name": "bash", "arguments": {"command": "pytest -x"}}. Your code runs it and returns the output as the next message.

One feature stands out. Context is built as a tree, not a list. Each message is a node whose parent is the message before it. You can go back to an earlier node and continue a different thread from there, so two attempts at one problem live side by side as branches. The model only ever reads the path from the root to the node you stand on.

Three context patterns, from this lesson

The slide lists Pi's context management as three items, and you have met all of them. First, event log to model input: the session is stored as entries, and the model's input is built from them (Chapter 8). The tree above is that log. Second, progressive disclosure through skill files: a skill's short header is always visible, and its body loads only when needed (Chapter 9). Third, compaction.

Pi's documentation gives the compaction rule exactly. Auto-compaction starts when the context tokens exceed the context window minus a reserve. The default reserve is 16,384 tokens. With a 200,000-token window, as an example, compaction starts once the context passes 183,616 tokens. Pi keeps the most recent tokens as they are (20,000 by default) and summarizes everything before them. The entry where the verbatim part begins is called firstKeptEntryId. After compaction the model sees three things in order: the system prompt, the summary, and the messages from firstKeptEntryId onward. The slide's picture shows the same strip: system, summary, then the kept messages.

The next device is a toy tree with two branches. Choose where to continue, then turn compaction on. Watch what the model reads, and notice that the tree itself never loses an entry.

Walk the tree

Dots are messages. The bright path is what the model reads. The strip under the tree is the model's input, in order. Choose where you continue, then toggle compaction.

A toy session written by us. Token sizes are illustrative, and the keep-recent budget is scaled down to 1,000 so you can see it act (Pi's documented default is 20,000). The input order, system prompt then summary then messages from the first kept entry, follows Pi's compaction documentation.

Safety: there is none, on purpose

The last slide of the case is a warning sign. Pi runs with the same permissions as the process that starts it. It shows no pop-up asking for permission. Treat it as always on auto-mode with no protections. That follows from the philosophy: permission checks are a feature, and features are extensions. It is also the sandbox lesson from Chapter 6, made concrete. If you run a harness like this, you provide the walls: run it in a container or a virtual machine, with only the files and the network access it needs.

The failure to plan for is the wrong command at the wrong place. Symptom: the agent deletes or overwrites files outside the project. Measurement: the event log is a full record of every bash command, so review it. Fix: isolate the process, and add a permission extension if you want confirmations.

Design questionPi's choicePattern from this lesson
Who holds control flow?The model, in a loopAgent (Chapter 0)
How does it reason and act?Thought first, then a JSON tool callReAct (Chapter 4)
Which tools?read, bash, edit, write; the rest is bashFocus the context (Chapter 8)
Where does the truth live?A tree of entries; the model reads one pathPersistent event log (Chapter 8)
When the window fills?Summarize all but the newest tokensCompaction (Chapter 9)
How are instructions loaded?Skill headers first, bodies on demandProgressive disclosure (Chapter 9)
What stops a bad command?Nothing; you add the wallsSandbox (Chapter 6)
After Pi compacts a session, what does the model read, in order?

Chapter 11

The Field Guide

Keep the whole lecture on one page: the terms, the numbers, a checklist, the core code and where to go next

One question runs through the lecture: who decides the next step, your code or the model? If your code decides, you have a workflow, and five named patterns help you build it. If the model decides, you have an agent, and four named ways of reasoning and acting help you steer it. Either way, what the model reads shapes everything, so five context patterns keep that reading small, focused and continuous. The Pi harness shows all of it in one small program. The lecture's own advice, from Fowler: these patterns are half-baked, and you finish them for your environment.

The terms

PatternWhat it doesWhat it trades
Prompt chainingSplits a task into steps, each reading the last, with gates betweenLatency for accuracy
RoutingClassifies the input, then sends it to the right handler or modelA little accuracy for cost and time
ParallelizationSectioning (independent parts) or voting (same input, many calls)More calls for speed or reliability
Orchestrator-workersOne model writes the job list while running, workers do the jobsA planning call for flexibility
Evaluator-optimizerA generator and an evaluator loop on clear feedbackRounds for quality
ReActThought, then action, then observation, in a loopTokens for a goal that survives many steps
ReflexionTurns a failed trial into a written note for the next trialTrials for quality, with an external signal
CodeActThe action is a program, run in a sandboxA sandbox for far fewer turns
ReWOO, LLMCompilerPlan with placeholders, run workers, solve once; run independent tasks togetherAdaptivity for tokens and latency
Event log, offloadingKeep a perfect record, move bulky facts to filesRead-back steps for a small window
Compaction, masking, isolationSummarize, stub old outputs, or hand work to a fresh windowDetail and cache for focus

The numbers

ClaimNumberSource
ReAct vs acting alone, HotpotQA exact match (PaLM-540B)27.4 vs 25.7Lecture slide, ReAct paper Table 1
ReAct vs acting alone, Fever accuracy60.9 vs 58.9Lecture slide, ReAct paper Table 1
ReAct over imitation and RL, ALFWorld and WebShop+34% and +10%ReAct abstract
Reflexion, HumanEval pass@1, against GPT-491% vs 80%Reflexion abstract
CodeAct, success rate over alternativesup to 20% higherCodeAct abstract, 17 models
ReWOO token efficiency, and accuracy on HotpotQA5x, +4%ReWOO abstract
LLMCompiler over ReAct: latency, cost, accuracyup to 3.7x, 6.7x, about 9%LLMCompiler abstract
STORM over an outline-driven RAG baseline: organized, coverage+25%, +10%STORM abstract
Archon over frontier models, average+15.1%Archon abstract
Observation share of a raw coding agent's tokens83.9%Lecture slide, observation masking study
Masking against the raw agent, costabout halfObservation masking abstract
Pi defaults: reserve and keep-recent tokens16,384 and 20,000Pi compaction docs

The checklist

  1. Name the control flow. If the steps are known and repeat, build a workflow. Reach for an agent only when the path depends on what the tools return.
  2. Start with the smallest pattern. One augmented call, then a chain, then a router. Add a box only when a measurement says you need it.
  3. Give every loop a cap. Cap the steps, the rounds and the sub-agents.
  4. Ground every critique. Use tests, tools or the environment as the judge, not the same model's opinion.
  5. Run code actions in a sandbox. A harness with no permission checks needs walls you build.
  6. Keep a log and a view. Store the truth append-only. Rebuild what the model reads on each call.
  7. Shrink the biggest share first. In coding agents that is the tool output.
  8. Protect continuity. Pin the goals and constraints. Trim in rare, large steps so the KV cache survives.

The core as code

This is a small harness that carries the lesson's patterns together. It is simplified: real chat APIs also want tool-call ids on each message. Each comment names the chapter it comes from.

pythonlog = []                                                     # persistent event log: append only (Ch 8)

def view(log, keep_obs=10):                                 # what the model reads, rebuilt on every call
    s = next((e for e in reversed(log) if e["kind"] == "summary"), None)
    body = [e for e in log[(s["first_kept"] if s else 0):] if e["kind"] != "summary"]
    old = {id(e) for e in [e for e in body if e["kind"] == "obs"][:-keep_obs]}   # observation masking (Ch 9)
    msgs = [{"role": "system", "content": SYSTEM}]                        # tool list + skill headers only (Ch 9)
    if s: msgs.append({"role": "user", "content": "Summary so far:\n" + s["text"]})
    for e in body:
        msgs.append({"role": e["role"], "content": "[output omitted]" if id(e) in old else e["text"]})
    return msgs

def compact(log, keep_recent=20):                           # compaction (Ch 9, Pi in Ch 10)
    cut = max(0, len(log) - keep_recent)
    log.append({"kind": "summary", "first_kept": cut, "role": "user",
                "text": llm(view(log[:cut]) + [ASK_FOR_GOALS_CONSTRAINTS_PROGRESS])})

def run(task, max_steps=30):                                 # a ReAct-style agent loop (Ch 4)
    log.append({"kind": "user", "role": "user", "text": task})
    for step in range(max_steps):                          # always cap the steps
        if count_tokens(view(log)) > WINDOW - RESERVE: compact(log)
        reply = llm(view(log), tools=TOOLS)                   # a thought, then zero or more tool calls
        log.append({"kind": "act", "role": "assistant", "text": reply.text})
        if not reply.tool_calls: return reply.text
        for call in reply.tool_calls:                       # independent calls may run together (Ch 7)
            log.append({"kind": "obs", "role": "tool", "text": run_in_sandbox(call)})   # (Ch 6)

Pick the first pattern

Each card is a situation. Choose the pattern you would try first. The explanation names the deciding question.

Our own scenarios, built on the decision rules in the lecture and in Anthropic's Building Effective Agents; reasonable engineers can disagree on a close call.

Where it sits, and where to go next

This lecture sits between two others. Lecture 5, Agent Frameworks shows the libraries that package these patterns. Lecture 4, Tool Use builds the tools every pattern calls. The next class is about memory, the Write and Select buckets of Chapter 9, and the one after about multi-agent systems, the Isolate bucket.

The takeaway. Decide who holds the control flow, then pick the smallest named pattern that fits. Ground every loop in a real signal, cap it, and give the model the smallest context that still holds the goals. The patterns are half-baked. You finish them.

Now press Present or Teach and explain one agent step out loud, from memory: who held the control flow, which pattern chose the action, what the model read, and what you would stub or summarize to shrink it. Then go back to the ticket at the top, run the odd ticket as a workflow and as an agent, and explain which pattern you would add to each.

Credit: this lesson re-teaches Lecture 6 of Stanford CS 329Z, Engineering AI Agents (Fall 2026), by Diyi Yang, Michael Ryan and John Yang. The slides are at web.stanford.edu/class/cs329z/slides/lecture06.pdf. All explanations, devices and toy numbers are ours, and the course's slide images are not reproduced here.

CS 329Z L06: Agent Design Patterns and Scaffolds
Course slides · Back to Gleams