An AI can improve by editing the text it reads, with no weight updates. Rewrite its notes every round and they collapse. Add small deltas and they keep what they learned.
Learn what context is, how a prompt, a memory or a playbook changes what a model does, and how a program can evolve that text by itself.
Pick Rewrite everything, then drag the step slider past 60. Watch the notes the agent has learned vanish. Switch to Add small deltas and run the same steps. Then we build, piece by piece, everything underneath.
You need a rough idea of what a language model is (a program that writes the next word of a text) and a little Python for the code. We build the rest from zero.
Based on Week 2 of MIT MAS.S62 How to AI an AI for (Almost) Anything (Fall 2026, MIT Multisensory Intelligence group), taught by Paul Liang, with a guest lecture by Qizheng Zhang. Slides: Lecture 2, Context and the guest lecture.
The four numbers on the rewrite line are the guest lecture’s (slide 9): 18,282 tokens and 66.7 accuracy just before the collapse, 122 tokens and 57.1 after it, and 63.7 with no notes at all. The line shapes between them are a sketch, not data. Both update lines share one slope on purpose: only the update rule differs.
Chapter 0
See why the text around a model decides what it does, and why that text is the cheapest thing in an AI system to change
Picture an assistant that fixes bugs in a code repository. You give it a task. It fails. You add one line to its instructions: “Run the tests before you say you are done.” Now it passes. You did not retrain anything. You did not touch a single weight. You changed the words it reads.
That small act is the subject of this whole lesson. Week 2 of MIT’s MAS.S62 course, taught by Paul Liang, calls it context evolution: letting the text around a model improve over time, by hand or by another program, so that the same model does better work.
First, the logistics, in one breath. The lecture opens with course announcements: everyone is notified of for-credit or listener status and added to the course site, a project preferences form is due, and the first reading assignment, on this very topic, goes out that night. Now the ideas.
The lecture starts from a classic picture. An agent perceives its environment through sensors and acts on it through actuators. A thermostat is a tiny agent: a temperature sensor in, a heater switch out. A self-driving car, a robot arm and a game player fit the same frame.
For an AI agent built on a language model, the slide fills in the words. The environment is a code repo, a website, an application or the real world. What the agent observes is messages, files, web pages and tool results. What it does is write text, edit files, call APIs, run shell commands or move a body. Its rewards are test cases, finished tasks, judge models and user feedback.
Now the key definition. Context is everything the model reads before it generates the next token. A token is a small piece of text, often a word or part of a word. The model has no other input. If a fact is not in the context, and was not learned in training, the model cannot use it.
The lecture sorts context by where it comes from. The developer supplies a system prompt, instructions, tool definitions, examples and memory. The user supplies a message. The environment supplies files, search results and tool output. The model itself adds its own thoughts and actions, which then become context for its next step.
It also sorts context by what it is for. Context can inform (give new facts), steer (set instructions, role and format), demonstrate (show examples), compute (let the model think step by step) and correct (pass on feedback from the last attempt). Try packing a context below. Switch each source on and off, and see which uses it serves.
Each button is one source of text. Press it to put that text in the context or take it out. The bar shows how many tokens each source adds. The five boxes light up for each use the context serves.
Token counts are illustrative. The sources and the five uses are the lecture’s (slide 5); which source serves which use is this lesson’s simplification.
Concretely, a chat model takes one request: a list of messages and a list of tool descriptions. The provider turns it into one long token list. That list is the context. Here is a request with every part labelled.
python# one request to a chat model: this whole structure becomes one token list request = { "system": "You fix bugs. Run the tests before you say you are done.", # developer: steer "tools": [{"name": "run_tests", "description": "Run the repo's test suite"}], # developer: inform "messages": [ {"role": "user", "content": "test_parse fails. Fix it."}, # user {"role": "assistant", "content": "I will run the tests first."}, # the model's own words {"role": "tool", "content": "FAILED test_parse: KeyError 'id'"}, # environment ], } # out: a probability for every possible next token, shape (vocab_size,)
The reply is one more message. The next request carries all of it again, plus the reply. So context grows with every step, and every part of it is something you, a tool or the model wrote. That is why it is the easiest thing to edit.
Who builds the request? The harness: the code around the model that manages its context and the flow of execution to finish a task. The lecture draws the loop from the ReAct paper. The harness builds the prompt, calls the model, parses the action the model wrote, runs it, and appends the observation. Then it goes round again.
The split is useful. The context is what the model sees. The harness is the program that decides what it sees next. Later weeks of the course evolve the harness itself. This week we evolve the context.
There are three ways to change what an AI system does. You can change the weights, with fine-tuning or reinforcement learning. You can retrieve facts and put them in the context. Or you can change the context itself. Editing text has three advantages. It is fast: one edit takes effect on the next call. It is readable: a person can open the context and see what the agent was told. And it is model-agnostic: the same notes work if you swap the model. The guest lecture in Chapter 9 sets these three ways side by side, with their costs.
The price is that text is fragile. Nothing stops a bad edit from sitting in the context and steering every later call. So context evolution is two skills: making the context better, and keeping it from getting worse.
Chapter 1
Follow one prediction to see how earlier text steers the next token, and how examples and step-by-step thoughts steer the whole task
You hand a stranger three index cards. Card one: “sea otter, loutre de mer.” Card two: “peppermint, menthe poivrée.” Card three: “cheese,” and the rest is blank. You never said the word “translate.” Yet the stranger writes “fromage.” The cards were enough.
A language model does the same thing, and it is the heart of the lecture’s second section. When the model predicts the next token, it attends to the context before it. To attend means to look back at earlier tokens and weigh how much each one matters for this prediction. Change the earlier tokens, and the prediction changes.
The slide shows a French sentence being translated, with the model about to write the word after “cheese :”. Each earlier token left behind two small vectors, a key (a label saying what the token offers) and a value (the content it can pass on). The pile of stored keys and values is the KV cache. The current position makes a query (a question saying what it needs). Each key is scored against the query, the scores become weights that add to 1, and the output is a weighted mix of the values.
shapes: qt is (d), K is (t × d), V is (t × d), αt is (t), ht is (d)
Nothing in this formula says “translate.” The behavior comes from which tokens sit in K and V. This is why the lecture says the model’s behavior is a function of its context. Chapter 7 returns to what this costs.
The next slide gives the most useful picture in the lecture. Before any context, the model could be doing many tasks: translating, summarizing, rhyming, answering. Call the task z. The model’s sense of which task is likely is a flat, wide spread, p(z). After it reads the three cards, the spread collapses onto one peak, p(z | c): the task is translation.
Bayes’ rule makes this precise. It says the new belief is the old belief times how well each task explains the evidence, then rescaled. Each card is evidence. A task that predicts English-to-French pairs well gains weight. A task that does not loses weight, fast. This is one standard way to read in-context learning: learning a task from examples in the prompt, with no weight change. The slide credits the GPT-3 paper for showing it works at scale.
The bars are the model’s belief about which task the prompt describes. Add the example cards one at a time and watch the belief sharpen.
The three example pairs are the lecture’s (slide 8). The five tasks and every likelihood below are illustrative: each pair is at least 10 times more likely under translation than under any other task, and the starting belief is flat at 20% each.
Look at the numbers after one card: translation already holds about 80% of the belief. After three, it holds nearly all of it. The lecture’s point is practical. Examples are not decoration. They are the cheapest way to tell the model which job it has.
The context can do more than pick a task. It can hold work. The model has a fixed amount of computation for each token it writes, so a hard answer written in one token has little thinking behind it. If the model first writes its reasoning, the reasoning tokens become context, and the final answer can attend to them.
That is chain of thought (Wei et al.). The slide uses a tennis-ball puzzle. Roger has 5 balls and buys 2 cans of 3 balls. The cafeteria has 23 apples, uses 20 and buys 6 more. Plain prompting answers “27,” which is wrong. A prompt that shows its steps (23 − 20 = 3, then 3 + 6 = 9) answers 9, which is right.
Tree of thoughts (Yao et al.) goes one step further. The model proposes several partial thoughts, scores them, keeps the good ones, and searches onward. Slide 11 draws four ways to prompt: direct input to output, chain of thought, chain of thought with a majority vote over samples, and the tree. Each adds more structure, and more tokens, to the context.
Take d = 4 and three earlier tokens. The query is scored against each key. Suppose the raw dot products are 2.0, 0.5 and 0.0. Divide each by √4 = 2 and you get 1.0, 0.25 and 0.0. Now the softmax: e1.0 = 2.718, e0.25 = 1.284 and e0 = 1.000. They sum to 5.002. The weights are 0.543, 0.257 and 0.200. They add to 1, and the first token gets more than half the attention.
The symptom: you add three good examples, but the model ignores them. This happens when the examples sit in a long prompt full of other text. The measurement is the weight the examples receive. Say three example tokens each score 1.0 (weight e1.0 = 2.718 before normalizing) and 3,000 filler tokens each score 0 (weight 1.0). The total is 3 × 2.718 + 3,000 = 3,008.2, so the three examples share only 8.15 / 3,008.2 = 0.27% of the attention. The fix is to cut the filler, or to move the examples close to the question, so they compete with fewer tokens. This is a toy model of one head. Real models have many heads and layers, but the pressure is the same: attention weights always add to 1, so every extra token takes a share from the rest.
Chapter 2
Put pictures and sound into a language model’s context, either as projected tokens or as words that describe them
You show a friend a photo and ask, “What is wrong with this kitchen?” Your friend looks, and answers. A language model has no eyes. Its context is a list of token embeddings, one vector for each token. So the question is practical: how does a picture become part of that list?
The lecture shows two families of answers. In the first, we turn the picture into vectors the model can read directly. In the second, another model turns the picture into words, and the language model only ever sees text. Both make a multimodal context: a context that carries more than one kind of signal.
Slide 12 shows the idea from the Frozen paper (Tsimpoukelli et al.), called prefix tuning here: put new vectors in front of the text. A vision encoder reads the image and produces a feature vector. A small adapter, a trained layer that converts one kind of vector into another, maps it into the language model’s embedding space. The language model itself stays frozen, meaning its weights never change. The slide models p(text | image), and shows a made-up word working as a few-shot lesson: “This is a dax.”
Slide 13 gives a larger version, MiniGPT-4 (Zhu et al.). A frozen vision transformer and a Q-Former, a small module that compresses many image features into a few, feed a single linear layer. That layer feeds the Vicuna language model. Training has two stages. Stage 1, alignment, uses paired image and text so the linear layer learns to translate. Stage 2, instruction tuning, uses image plus text instructions with example completions so the model answers in a useful way.
Slide 14 generalizes this. OmniSapiens (Ong et al., from the course’s own group) builds a foundation model for social behavior. Its context is interleaved tokens: language tokens, projected visual tokens, projected audio tokens, all in one sequence, in the order they happened. The model attends to all of them with the same attention from Chapter 1.
python# route one: image -> tokens the language model can attend to (shapes are illustrative) patches = vit(image) # (196, 1024) 14 x 14 patches, one vector each queries = qformer(patches) # (32, 768) 32 learned queries compress 196 -> 32 visual = linear(queries) # (32, 4096) the only trained layer in stage 1 text = embed(tokenize("What is wrong with this kitchen?")) # (9, 4096) context = concat([visual, text]) # (41, 4096) one sequence; the LLM stays frozen
Slides 15 to 17 show the other family, Socratic Models (Zeng et al.). No new training. A chain of existing models talks in language. An image captioner describes the scene. A language model reads the description and reasons. The slides show it on three jobs: image captioning, robot perception and planning (the robot’s camera view becomes a list of object names), and video reasoning (frames become a time-ordered log of what was seen, which a language model answers questions from).
The trade is clear. Words are cheap and easy to inspect, and a person can read the context and see what the model was told. But a caption keeps only what its writer thought to say. Projected tokens keep far more detail, but they need training, and nobody can read them.
Choose how images enter the context, then add images. The bar splits the context into question tokens and image tokens.
Illustrative arithmetic. A 224 by 224 image cut into 16 by 16 patches gives 14 × 14 = 196 patches. Thirty tokens for a caption and nine for the question are assumed. The 32 queries follow the Q-Former design used in MiniGPT-4; the slide gives the architecture, not these counts.
The lecture does not rank the two routes. Our reading: use words when you need to inspect and edit what the model knows, and projected tokens when the detail matters. Either way, the picture ends up as context, and everything you learned in Chapter 1 still applies.
You send six photos and the question “What is wrong with this kitchen?” (9 tokens). With raw patch tokens, each photo costs 196 tokens: 6 × 196 + 9 = 1,185 tokens. With 32 Q-Former tokens each, it costs 6 × 32 + 9 = 201 tokens. With a 30-token caption each, it costs 6 × 30 + 9 = 189 tokens. The raw route is about 6.3 times the caption route. Since attention cost grows with the square of length (Chapter 7), the raw route’s attention work is about 39 times larger (6.3 squared).
Now the data flow of route two. The captioner takes pixels of shape (224, 224, 3) and returns a string such as “a kitchen with white cabinets and a sink.” The language model gets only that string. It is cheap, readable, and it throws almost everything away.
The symptom: the model answers confidently, but it never mentions the leak under the sink. The measurement: write ten questions about small details in your photos. Run them once with the caption alone, and once with the projected tokens. Count the answers that are correct. If the caption route gets 3 of 10 and the token route gets 8 of 10, the caption is the bottleneck. The fix is to ask the captioner a targeted question (“describe anything wet or damaged”), or to move to the token route for those details. In both routes, remember that the language model can only answer from what reached its context.
Chapter 3
Step through an agent loop that writes its thoughts and actions into its own context, then see why small changes to a prompt can swing the score
You are asked a question you cannot answer from memory: “Aside from the Apple Remote, what other device can control the program the Apple Remote was originally designed to interact with?” You would not guess. You would look up the Apple Remote, find a program name, look that up, and read the answer. You would think between lookups.
Slide 18 shows an agent doing exactly that. It is the ReAct pattern (Yao et al., ICLR 2023): Reasoning and Acting interleaved. The model writes a thought (what it needs next), then an action (a tool call, such as Search[Apple Remote]). The harness runs the action and appends an observation (the tool’s result). The model reads the longer context and writes the next thought.
This is the harness from Chapter 0, made concrete. Every pass through the loop makes the context longer, and the context is the agent’s only memory.
pythoncontext = [system_prompt, question] # list of text pieces: this is all the agent knows for step in range(8): reply = llm("\n".join(context)) # in: tokens so far; out: "Thought: ...\nAct: Search[...]" thought, action = parse(reply) # the harness reads the model's own text context.append(reply) # the model's words become context if action.name == "Finish": return action.arg context.append("Obs: " + tools[action.name](action.arg)) # the environment's words become context
Each press runs one half of the loop: the model writes, then the tool answers. Orange is written by the model, blue by the environment.
The question and the three-step trace are the one on the lecture’s slide 18, shortened. Token counts are estimated as 1.3 tokens per word.
Notice what the harness did and did not do. It never searched by itself, and it never decided the answer. It only parsed text, ran a tool and appended text. The intelligence lives in what the model writes next, and that depends entirely on what is in the context.
If context is the lever, you would hope it is a sturdy one. Slide 19 says otherwise. Sclar et al. (ICLR 2024) found that language models are, or were, sensitive to spurious changes in a prompt. “Spurious” means a change with no meaning: a different separator between fields, upper case in place of lower case, an extra space. A person reads all of these the same way.
The slide plots one task across many such formats. The accuracy of one model ranged from 0.036 to 0.804 over plausible formats. Same task. Same examples. Same model. Only the typing differs.
Pick a separator, a casing and a spacing. Each of the 18 dots is one format. The line marks the one you chose.
Illustrative. The 18 accuracies are generated from a fixed seed and scaled so the worst lands on 0.036 and the best on 0.804, the two ends of the spread on the lecture’s slide 19. Real formats do not score like this; the point is the size of the spread.
Slide 20 adds the human side, from “Why Johnny Can’t Prompt” (Zamfirescu-Pereira et al., CHI 2023). People without AI training had trouble getting started, choosing the right instructions and expecting human abilities from the model, and often had to ask for help. The paper’s comparison table sets their intuitive approach against that of experts. Non-experts leave task requirements implicit; experts state them. Non-experts debug opportunistically; experts debug systematically.
Put the two slides together and you get the problem for the rest of the lecture. Prompts matter enormously. They are brittle. And people are not good at writing them. That is a good reason to let a program search for them instead.
Count the trace in the device. The question is about 26 tokens. Each thought and action pair is about 35 tokens, and each observation about 25. After three rounds the context is roughly 26 + 3 × 35 + 2 × 25 = 181 tokens. That is small. A real tool result, such as a web page, may be 1,500 tokens. Then three rounds cost over 4,500 tokens, and every later model call pays to read them all again.
The harness itself has one fragile step: parse(reply). The model must write its action in exactly the format the harness expects.
The symptom: the run stops with “no action found,” or it calls a tool that does not exist. The measurement: run 100 tasks and count parse failures. If 7 fail, your parse rate is 93%, which is not good enough for a ten-step task, since 0.93 to the tenth power is about 0.48. The fix: state the action format with one example in the prompt, check the reply with a strict parser, and on failure add the error text to the context and retry once. The model then reads its own mistake. Prompt sensitivity is the same lesson in miniature: the harness depends on text details the reader never sees.
For the sensitivity device, note the arithmetic. Three separators, three casings and two spacings make 3 × 3 × 2 = 18 formats. The honest way to report a prompt’s score is a range over formats, not one number. Choose a prompt whose worst format is still good, not one whose best format is lucky.
The slide compares three agents on the same question. A reason-only agent, which is chain of thought, thinks but cannot look anything up, so it may invent the program’s name. An act-only agent calls tools but writes no thoughts, so it cannot decide which lookup comes next, or notice when a result is not what it needed. The ReAct agent does both. The thoughts steer the actions, and the observations correct the thoughts. In the trace above, thought 2 is what turns “Front Row” from a word in a result into the next search.
Chapter 4
Let a model propose prompts, score them, and keep the best, so no person has to guess the right words
Chapter 3 ended with a problem: prompts matter, they are brittle, and people write them badly. Suppose you have a task, such as turning a word into its opposite, and ten examples. Which instruction should go in the prompt? You could try five by hand. A program could try five hundred, and measure each one.
Slide 21 draws the progression as three workflows. In standard prompting a user writes the prompt, the model answers, and an evaluation judges the output. In LLM-assisted prompting a model helps the user write the prompt, but the user is still in the loop. In prompt optimization the user disappears from the loop: the prompt, the model, the output and the evaluation form a cycle, and the evaluation’s score changes the next prompt.
Slide 22 names two challenges. The first: a prompt is made of discrete tokens, a choice from a fixed list, not a smooth number. Training a neural network works because a small nudge to a weight gives a small, measurable change in the loss. That small change is the gradient. You cannot nudge the word “opposite” by 0.01. Slide 23 shows the backpropagation picture and says it plainly: if inputs and layers are text, gradients are hard to compute. You could take a gradient with respect to a token embedding, but the result does not map back to any real word.
So the lecture offers two families of fix. Search-based methods try candidates and keep what scores well. Gradient-like methods use feedback to decide how to edit. There is a second choice inside both: update the prompt directly, or update a model that writes prompts.
The second challenge is size. The space of all long strings is enormous, so searching it blindly is hopeless. Chapter 6 answers that with modular, composable prompts.
The search-based answer on slide 24 is APE, the Automatic Prompt Engineer (Zhou et al., ICLR 2023, “Large Language Models Are Human-Level Prompt Engineers”). It treats the instruction as a program and searches over a pool of candidates. A model proposes the candidates. Another model scores them. The best wins.
pythondef ape(demos, heldout, rounds=3, n=6): # demos: [("big","small"), ("hot","cold"), ...] heldout: inputs with known good outputs pool = llm(f"Here are input-output pairs: {demos}. The instruction was:", samples=n) # n candidate instructions for _ in range(rounds): scores = [accuracy(llm(inst + "\nInput: " + x), y) for inst in pool # zero-shot: no demos in this call for (x, y) in heldout] best = pool[argmax(scores)] pool = [best] + llm(f"Rewrite with the same meaning: {best}", samples=n - 1) # resample around the winner return best
Read the data flow. The proposer sees the demonstration pairs and writes instructions. The scorer never sees the pairs: it sees only the instruction and a new input, so the score measures the instruction alone. The paper reports that the instructions APE writes beat the earlier model baseline by a large margin, and match or beat the human-written ones on all 24 Instruction Induction tasks and on 17 of 21 BIG-Bench tasks.
The task is: turn a word into its opposite. Each round the proposer writes six instructions and the scorer tests each on held-out words. Press the button to run a round.
Illustrative. The instructions are hand-written to look like what a proposer returns, and the scores are made up to show the shape of the loop. Real APE scores come from running a second model on held-out inputs.
Look at what the search found. Round 1 includes nonsense (“Say the same word back” scores 0), so the pool must be wide. Rounds 2 and 3 do not wander: they refine the winner. That is the pattern behind most prompt search.
One reading, “Evolving Prompts In-Context” (arXiv 2506.17930), pushes the search further and finds something odd. Take a prompt full of demonstrations and prune tokens from it until it looks like gibberish. The authors report that such pruned prompts match or beat state-of-the-art automatic prompt optimizers. Their method, PromptQuine, is an evolutionary search: it keeps a population of pruned prompts, mutates them, scores them, and keeps the survivors. It uses only tokens already in the context. The lesson for us: the best prompt for a model need not read well to a person.
Suppose the held-out set has 20 new words. A candidate instruction, “Reply with the antonym of the input word,” makes the scorer right on 17. Its score is 17/20 = 0.85. In one round, 6 candidates times 20 inputs is 120 scoring calls. Three rounds are 360 calls, plus 3 proposal calls. That is the price of the search, and it is why the held-out set is kept small.
The symptom: the winning prompt scores 0.91 in the search, but only 0.70 on fresh words. The measurement: with 20 inputs and a true accuracy near 0.9, the standard error of one score is √(0.9 × 0.1 / 20) = 0.067. So 0.91 and 0.85 are not clearly different. The search picked the luckiest of many noisy scores. The fix is to score the final winner on a separate test set the search never touched, and to use more inputs when the top candidates are close. The same lesson applies to every optimizer in this lesson: the winner is biased high.
Chapter 5
Send criticism backward through a chain of model calls, the way backpropagation sends error backward through layers
A teacher marks your essay. She does not write “you lost 7 points.” She writes, in the margin, “this paragraph needs a source.” The number tells you how bad it was. The note tells you what to change. A neural network gets only the number, and turns it into a push on each weight. What if the push were a sentence?
That is TextGrad (Yuksekgonul et al., “TextGrad: Automatic ‘Differentiation’ via Text”). Chapter 4 searched by trying many prompts. TextGrad instead follows feedback: it asks a model what is wrong, passes that criticism back to the prompt that caused it, and edits the prompt. It takes the shape of gradient descent, but every quantity is text.
Recall backpropagation: a network makes a prediction, a loss scores it, and the chain rule carries the loss’s sensitivity back to each earlier value. Slide 25 puts a neural network next to a black-box AI system and draws the analogy: the variables become text (a prompt, a prediction), the loss becomes an evaluation written by a model, and the gradient becomes a textual gradient, a piece of natural-language criticism.
The lecture writes the chain on slide 26 in two steps. First, collect feedback on the prediction given the evaluation. Second, collect feedback on the prompt given that feedback on the prediction.
The update then mimics the gradient step. In ordinary descent, new weight = old weight minus (learning rate × gradient). In Textual Gradient Descent (TGD), a model gets the old variable and the criticism, with the instruction: “Incorporate the criticisms, and produce a new variable.” The slide gives that exact template.
The three boxes are variables in a tiny computation graph. Forward arrows are blue, criticism going backward is yellow. Press the button to move one stage at a time.
Illustrative. The problem is the tennis-ball puzzle from the chain-of-thought slide, and the model replies and criticisms are written by hand to show the data flow. Real TextGrad uses a model for every box and arrow, and the reply text differs on each run.
The paper’s library mirrors PyTorch on purpose: a variable that needs a gradient, a loss object, a backward call, and an optimizer. Each line below costs one or more model calls, and each call’s output is a string.
pythonimport textgrad as tg # a sketch of the library's interface tg.set_backward_engine("gpt-4o") # the model that writes criticism prompt = tg.Variable("Solve the problem.", requires_grad=True, role_description="system prompt") solver = tg.BlackboxLLM("gpt-4o-mini", system_prompt=prompt) opt = tg.TGD(parameters=[prompt]) loss = tg.TextLoss("Check the answer step by step. Say what is wrong.") pred = solver(question) # forward: a Variable holding the model's answer (a string) l = loss(pred) # evaluation: a string, "Wrong, because..." l.backward() # two criticism calls: on pred, then on prompt opt.step() # one rewrite call: prompt.value is now a new string
The paper reports results in several domains. Without changing the framework, TextGrad raised GPT-4o’s zero-shot accuracy on Google-Proof Question Answering from 51% to 55%, and gave a 20% relative gain in optimizing LeetCode-Hard solutions. Slide 30 also shows it editing molecules, code, a radiation treatment plan and prompts.
One honest cost: a single step needs five model calls here (solve, evaluate, two criticisms, one rewrite). The feedback is rich, but it is not free.
Count the model calls in the device. One solve call. One evaluation call. Two criticism calls. One rewrite call. That is five. Run ten steps on one question and you have 50 calls. Many tasks use a mini-batch of questions per step, so the real count is higher. The prompt, though, is one string, and every step edits that one string.
The symptom: after several steps the prompt is twice as long, and it holds two rules that contradict each other: “be brief” and “explain every step.” Each criticism was reasonable alone. The measurement: track the score on a validation set after every step, and the prompt’s token count. If the score falls while the length climbs, the edits are not helping. The fix is a guard that every serious optimizer uses: keep a step only if the validation score goes up, and otherwise revert to the previous prompt. Text is easy to edit, so you must check that an edit helped. The next chapters show the same guard in other forms.
Slide 30 shows TextGrad on four kinds of variable. The variable can be a prompt, which you tune once on training examples and then freeze. It can also be a solution, such as a piece of code, a molecule or a treatment plan, which you refine at test time for one instance. The loop is the same. The difference is when it runs and what is kept. A tuned prompt is reused on every future question. A refined solution serves one question only.
That split matters for context evolution. A prompt that was tuned is a small piece of persistent context. The rest of the lecture is about making persistent context bigger and safer.
Chapter 6
Shrink the search space by writing a model pipeline as typed modules, then let a compiler tune its prompts and examples
You ask a model: “How many storeys are in the castle David Gregory inherited?” A plain model invents a castle. A retrieve-then-read system searches once, finds a hotel with a similar name, and answers “nine”: wrong building. The right answer needs two lookups. First find the castle he inherited (Kinnairdy Castle). Then look up that castle (five storeys).
Slide 31 shows this contrast, from the Demonstrate-Search-Predict paper (Khattab et al.). The fix is a program of several model calls, each with one small job. That brings back the second challenge from Chapter 4: if every call has a long hand-tuned prompt, the space of all prompts is enormous. We need abstractions, named building blocks that hide the strings.
The lecture’s tool is DSPy (Khattab et al., “Compiling Declarative Language Model Calls into Self-Improving Pipelines”). It pushes you away from editing free-form strings and toward programming: you compose modular operators into text-transformation graphs, and a compiler generates the prompts.
Two ideas carry it. A signature is a typed description of one call: its input fields and output fields, such as “context, question → answer”. It says what, not how. A module is a reusable piece, such as Predict, ChainOfThought or ReAct, that turns a signature into an actual model call. Slide 33 shows both in code: a ChainOfThought module that adds a “rationale” field in front of the answer, and a RAG module that retrieves passages and then reads them.
pythonimport dspy class RAG(dspy.Module): def __init__(self, k=3): self.retrieve = dspy.Retrieve(k=k) # in: a query string; out: k passages self.generate = dspy.ChainOfThought("context, question -> answer") # one typed model call def forward(self, question): context = self.retrieve(question).passages return self.generate(context=context, question=question) # out: .rationale, .answer # compile: the program, a few labelled examples and a metric go in; a better program comes out teleprompter = dspy.BootstrapFewShot(metric=dspy.evaluate.answer_exact_match) compiled = teleprompter.compile(RAG(), trainset=qa_trainset)
Nothing in this code says what the prompt text is. At run time the module writes one: the signature names the fields, the instructions come from the signature, and demonstrations (example input and output pairs) are added. Those three parts, instructions, field descriptions and demonstrations, are the parameters the compiler can tune.
Slide 34 lists three ways, and they map to a short recipe.
Each cell is one setting of the pipeline’s parameters: which instruction (rows) and how many demonstrations (columns). Slide the trial budget and watch random search find a good cell. Then switch on voting.
Illustrative. The twelve scores are made up (fixed seed), and the trial order is a fixed shuffle. The voting number is exact majority-of-five arithmetic, assuming the five copies err independently, which real copies only partly do.
With 12 cells and 12 trials you see everything; with 3 trials you may miss the best. That is the trade-off of any search. DSPy shrinks the space so that a small budget is enough.
The paper reports, within minutes of compiling, that a few lines of DSPy let GPT-3.5 and llama2-13b-chat build pipelines that beat standard few-shot prompting (generally by over 25% and 65%) and pipelines with expert-written demonstrations (by up to 5 to 46% and 16 to 40%). Slide 35 sums up the first half of the lecture in two lines: TextGrad and APE answer the discrete problem, DSPy answers the size problem. The next week, the course turns to using models to optimize and search over whole programs. The course’s other tool lesson on this theme is Agent Frameworks, which treats DSPy as one of several frameworks.
Take five training questions. Run the compiled-so-far program on each, with a teacher. Suppose three pass the metric (the final answer matches). Each passing run has a trace with two steps: the retrieval query and the answer. Those three traces give three demonstrations for the retrieve step and three for the answer step. The compiler can now try 0, 2 or 3 of them per module. With 3 instructions and 4 demonstration counts, that is 12 settings, as in the device. Scoring each on 20 questions costs 12 × 20 = 240 pipeline runs.
The symptom: the compiled program scores well on the metric but gives odd reasoning. The measurement: read ten bootstrapped traces. If three of them reach the right final answer through a wrong retrieval step, then 30% of your demonstrations teach a bad habit. The fix is to tighten the metric so it also checks the middle of the trace, such as “the retrieved passages contain the answer.” A compiler optimizes exactly what you measure, so the metric is the most important line you write.
Chapter 7
Compare three ways to let a model read more text: cheaper attention, longer training, and smarter management of what is in the window
A playbook grows. A memory grows. A coding agent’s history grows. Sooner or later the context is longer than the model can comfortably read. This chapter covers the lecture’s third section: what limits context length, and what to do about it.
Slides 36 and 37 recap attention from Chapter 1, now as a matrix. For T tokens, the queries and keys multiply into a T × T table of scores. Row i holds how much token i attends to each token j. After a softmax over each row, the output for token i is a weighted mix of the value vectors. Each row costs time proportional to T, so the whole table costs T².
shapes: Q is (T × d), KT is (d × T), scores are (T × T), V is (T × d), output is (T × d)
Double the text and you quadruple the table. The lecture then shows the test that made long context famous: needle in a haystack (slide 38). Hide one fact, the “needle,” at some depth inside a long document and ask for it back. A grid of colors shows, for each length and depth, whether the model found it. Green cells are success. Red cells are misses, and they cluster at long lengths.
Slide 39 gives the plan, with a pro and a con for each way.
The next two chapters live in way three. First, ways one and two.
Slide 40 draws attention as a grid of squares: rows are queries, columns are keys. In full attention every row can see every earlier column, a filled triangle. In sliding window attention each token sees only the last w tokens, a thin diagonal band. The cost falls from T² to about T × w, so it grows in a straight line with length.
Slide 41 adds sparse attention. One kind uses a fixed pattern: a few global tokens everyone can see, plus the local window. Another is context-dependent: the model picks which earlier tokens to look at, by their content. Slide 42 tables several recent models, and the common design is a hybrid: mostly cheap local or stateful layers, with a few global layers mixed in, at ratios from about 3 local per 1 global to about 5 per 1. Read the table as a trend, not a rule.
Each row is a token asking, each column a token it may read. Filled squares are pairs the model computes. Choose a pattern and drag the window.
The grid is 16 tokens so you can count. The 128,000-token comparison scales the same rule: full attention is n(n + 1)/2 pairs; a window of 4,096 is about 4,096 pairs per token after the first 4,096. The two global tokens are the first two tokens.
Slide 43 shows the recipe most labs use. Do not train on long text from the start; it is costly and data is scarce. Train short (4K to 8K tokens, plenty of data). Then continue training at 32K to 128K with packed sequences. Then adapt at 128K or more, with task traces and synthetic curricula. Useful long data includes whole books and code repositories, agent trajectories (observations, actions, rewards), and synthetic tasks that hide evidence at chosen positions among distractors.
Slide 44 covers position encodings. A model must know where each token sits. If it only ever saw positions up to L in training, asking for position 5L is outside what it learned. Position interpolation (Chen et al.) fixes this by squeezing: with a stretch factor s = L′/L, a token at position t is treated as if it sat at t/s. Every new position falls back inside the trained range. Slide 45 tables what real models do, from partial RoPE to no position encoding in some layers, and slide 46 points to HELMET (Yen et al.), a benchmark suite that tests long context on retrieval-augmented generation, citation, re-ranking, many-shot learning, long-document QA, summarization and synthetic recall, not on needles alone.
The model was trained on positions 0 to 4,096. Drag the target length. The top line is the real positions; the bottom line is what the model is shown after interpolation.
The rule R(t) to R(t/s) is the lecture’s (slide 44). The trained length of 4,096 is a round number chosen for the demo, in line with the 4K to 8K short-pretraining stage on slide 43.
Why not just use a huge window? Because the model keeps a key and a value for every earlier token (Chapter 1), in every layer. Take an illustrative model with 32 layers, 8 key-value heads, a head width of 128, and 2-byte numbers. Each token stores 2 (key and value) × 32 × 8 × 128 × 2 bytes = 131,072 bytes, which is 128 KiB. At 128,000 tokens that is about 16.8 billion bytes, close to 15.6 GiB, for one conversation. The window’s cost is memory as well as compute.
The symptom: the model finds a fact at the start or end of a long prompt but misses one in the middle. The measurement is the needle test: place the same fact at 10 depths, from 0% to 100%, and count hits. A dip in the middle is the signature. The fix depends on the way you chose. You can put the key facts first or last, shrink the context so there is less middle, retrieve only what the task needs, or use a model trained with the long-context recipe. HELMET exists because one needle is a weak test: a real long task needs many facts at once.
For the full story of attention variants, see Attention Variants.
Chapter 8
Store what an agent learned in one task as text, and fetch the right pieces when the next task begins
An agent fails to return an item because it started the return after 30 days. It writes no note. Tomorrow, a new task: another return. The agent has no memory of yesterday, because the context ended with the task. It fails the same way. A person would have written “check the policy window first” on a sticky note.
This is the third way from Chapter 7: context management. Slide 39 lists summaries, memory systems and retrieval, and gives the trade-off: they improve the information pipeline and can scale, but they depend on retrieval and memory quality. The lecture agenda gives the topic its own slot, “Context management and memory,” and the week’s reading list carries it. We follow the readings.
An agent memory is text that outlives one task and is added to the context when it is useful. It has three jobs: write (decide what to keep), store (hold it somewhere searchable) and read (pick the few items that fit this task). The reading step matters most, because context is limited. A memory with a thousand notes is useless if all thousand are pasted in.
The first reading, Reflexion (Shinn et al.), reinforces an agent without changing weights. After a failed attempt, the agent reflects: it writes a short note about what went wrong and what to do differently. Notes go into an episodic memory buffer, a list of past-attempt notes, and the next attempt reads them. Three roles run the loop: an actor acts, an evaluator scores, and a self-reflection model turns the score and the trace into a note. The paper reports 91% pass@1 on the HumanEval coding benchmark, ahead of GPT-4’s 80% at the time. The full walkthrough is in the Reflexion paper lesson.
The second reading, ReasoningBank (arXiv 2509.25140), points out two gaps. Storing raw trajectories is noisy and long. Storing only successful routines throws away what failures teach. ReasoningBank instead distills generalizable reasoning strategies from the agent’s own successes and failures. The agent judges its own runs, with no human labels. At test time it retrieves relevant memories to guide the task, then integrates what it just learned back into the bank.
The paper adds one more idea, memory-aware test-time scaling (MaTTS). Give the agent more compute per task, for example several attempts. The attempts contrast with each other, and that contrast makes better memory. Better memory then guides better attempts. Across web browsing and software engineering benchmarks, the paper reports gains in both effectiveness and efficiency over memories that store raw trajectories or only successes.
pythondef run_task(task, bank, k=3): notes = bank.retrieve(task, k) # in: task text; out: k memory items (short strings) trace = agent.act(task, context=notes) # notes are prepended to the context ok = judge.score(task, trace) # the agent's own verdict: success or failure item = llm(f"From this {'success' if ok else 'failure'}, write a reusable strategy or pitfall:\n{trace}") bank.add(item) # kept whether ok is True or False return ok
The bank holds six notes from earlier shopping tasks. Pick a new task, choose how many notes to retrieve, and decide whether failures were kept.
Illustrative. The six notes, the two skills each task needs, and the word-overlap ranking are made up to show the mechanism; real banks use embedding search and a model to write the notes. The claim it illustrates is the paper’s: memory built only from successes misses what failures teach.
Try the return task with failures off. The bank has a note for finding the order, but the policy window lesson came from a failure, so it is gone. The agent will likely fail in the same way again. Now turn failures on: the second skill is covered. That is the paper’s argument in one toggle.
The course returns to memory in Week 5 (agent memory and harness evolution). For a build-oriented tour, see Agent Memory and the MemGPT paper lesson.
Take the return task, “Return an item bought last month.” Its longer words are return, item, bought, last and month. Note 4 (find the order) shares four of them: return, month, item, bought. Note 5 (the policy pitfall) shares three: return, item, bought. The other four notes share none. So the two top notes are exactly the two the task needs. Each note is about 20 tokens, so reading two costs about 40 tokens, where pasting all six costs about 120. Retrieval keeps the context small and sharp.
The symptom: the agent keeps refusing a return on day 45, because an old note says the window is 30 days. The company changed the policy to 60. The measurement: give each note two counters, helpful and harmful, and update them from outcomes. A note with 2 helpful and 9 harmful is a warning sign. The fix: prune or rewrite notes whose harm outweighs help, and attach the date or source to each. You will see this exact design again in ACE, where each playbook item carries its own counters.
Chapter 9
Meet the guest lecture’s two failures, brevity bias and context collapse, and see why rewriting a whole prompt loses what it learned
The second half of the day belongs to a guest, Qizheng Zhang of Stanford, speaking on Agentic Context Engineering (ICLR 2026, joint work with Stanford, SambaNova Systems and UC Berkeley). He starts with a small, vivid failure. It is the best way into the chapter.
The setting is AppWorld, a benchmark where a coding agent works in an interactive environment of phone-style apps. Many tasks run over 10 turns and over 32,000 tokens, and each comes with custom tool and API definitions. In slide 2 the user says: “Find me some songs.” More exactly, the task is to list the top four most-played R&B songs across the user’s Spotify song, album and playlist libraries.
Slide 3 shows the agent reading a list of API descriptions, such as show_account and signup. It writes code (slide 4): a loop that calls the Spotify library API page by page with an access token. Slide 5 shows the result: an error, Key “access_token” does not exist. The agent never logged in. The fix is one call (slide 7): log in, and the response holds the token.
The obvious repair, on slide 6, is to add a rule to the context by hand: “Principle 1: Always log in to retrieve the access token as a first step.” It works. The lesson the speaker draws is on slide 7: agents often miss contextual and procedural knowledge, not facts. Facts you can retrieve. A procedure, such as “log in before you call anything,” is knowledge about how to work here.
Slide 8 sets context evolution beside the two older options.
| Way to adapt | Strengths | Weaknesses |
|---|---|---|
| Weight updates (fine-tuning, RL) | Strong, and compact at inference | Slow to iterate, heavy infrastructure, hard to audit or roll back |
| Retrieval (RAG) | Injects facts; modular | Weak for procedures, tool protocols and “how-to” knowledge |
| Context evolution (this talk) | Fast test-time learning, readable, works with any model | Needs stability and cost control over long runs |
The last row’s weakness is the rest of the chapter.
Slide 9 names the existing methods: prompt optimizers such as GEPA, and agent memory such as Dynamic Cheatsheet. Both follow a loop: a prompt runs, a reflector model reads the rollouts (the recorded runs), and the prompt is rewritten into the next prompt. The slide names two limits.
Brevity bias is a preference for short, concise, generic instructions. A model asked to improve a prompt tends to compress it into tidy general advice, such as “handle errors carefully.” That sounds fine and teaches nothing. Context collapse is what happens when rewriting turns a rich context into a shorter, less informative summary. Each rewrite throws away some detail, and nothing in the loop notices.
The slide plots a real run. Tokens in the context climb to 18,282 with accuracy 66.7. Then one rewrite drops the context to 122 tokens, and accuracy falls to 57.1. That is lower than the 63.7 of an agent with no context at all. A bad context is worse than none. The hero at the top of this page draws this curve.
GEPA itself (Agrawal et al.) is the lecture’s example of a prompt optimizer. It samples agent runs, reflects on them in natural language, proposes prompt edits, and combines lessons from a Pareto frontier of its own attempts. The paper reports beating GRPO by 6% on average, and by up to 20%, with up to 35 times fewer rollouts, and beating the MIPROv2 optimizer by over 10%. See the GEPA paper lesson. The guest’s claim is not that GEPA is bad. It is that rewriting the whole prompt each round is a risky update rule.
Slide 10 states the proposal. Contexts should function not as concise summaries but as comprehensive, evolving playbooks: detailed, inclusive and rich in domain insight. Slide 11 gives the first of two recipes. The old way is a monolithic rewrite, which risks collapse. The new way is a delta update: each round adds a small set of changes to the playbook and leaves the rest alone, which gives stable growth.
An agent learns one new rule each round from AppWorld-style failures. Choose how the notes are updated, then run the rounds. The five boxes are the five rules; green means the notes still hold the rule.
Illustrative and scripted. The five rules are written in the spirit of the lecture’s AppWorld examples, and the rewrite is scripted to collapse in round 5 so the effect is visible in five clicks. In the paper’s run, the collapse came at step 60 (slide 9).
Notice that the delta notes are longer, and that is the point. Length is not the enemy. A short context that lost the rules is the enemy. The next chapter shows how ACE keeps the longer playbook tidy.
Do the arithmetic on the slide. From 18,282 tokens to 122 tokens removes 18,160 tokens, which is 99.3% of the context. Accuracy falls from 66.7 to 57.1, a loss of 9.6 points, and ends 6.6 points below the 63.7 of the agent with no notes. To catch this in your own system, log the token count and the score after every update. A drop of more than half in one step, with a drop in score, is the alarm.
Chapter 10
Build a playbook that grows by small, merged updates, and see what it gained on AppWorld and what it cost
Chapter 9 ended with a rule: add deltas, do not rewrite. But who writes a delta? And who makes sure it is a good one? A single model asked to “improve the notes” would write a summary. So ACE (Agentic Context Engineering, arXiv 2510.04618) splits the job into three roles. Slide 19 calls this Recipe #2: structured division of labor.
Slides 12 to 19 build the diagram one box at a time. A query and the current context playbook go in. The Generator runs the agent and produces a trajectory: the code, tool calls and results of one attempt. The Reflector reads the trajectory and writes insights, short statements of what worked and what failed. It can refine them in several passes (the dashed arrow, “iterative refinement”). The Curator turns insights into delta context items, small additions, and an update merges them into the playbook. The loop then repeats with the new playbook.
Why three? Each role has one job and one kind of input. The Generator is judged on the task. The Reflector is judged on how useful its diagnosis is. The Curator is judged on keeping the playbook tidy. Slide 21 states the split plainly: execution, insight extraction and integration are separated.
Slide 20 asks the question itself. Slide 21 answers by treating context evolution as a system problem with three parts. The state is a structured representation of the context: sections, and itemized bullets with metadata. That structure allows localization (touch one item), fine-grained retrieval, incremental adaptation, and periodic de-duplication and clean-up. The update operator is a delta update plus a deterministic merge: compact deltas, not full rewrites, so old knowledge survives, collapse is avoided, and several updates can be batched or run in parallel. The architecture is an autonomous loop with the division of labor above.
Here is the state as data. Slide 22 shows a real ACE playbook on AppWorld, with predefined section names (strategies and hard rules, useful code snippets and templates, troubleshooting and pitfalls) and generated bullets under each.
pythonplaybook = { "STRATEGIES": [{"id": "str-001", "text": "Log in first and keep the access_token.", "helpful": 4, "harmful": 0}], "CODE": [], "TROUBLESHOOTING": [], } def merge(playbook, delta): # deterministic: no model call, no rewrite for item in delta.new_items: if not duplicate(item, playbook): # e.g. embedding similarity above a threshold playbook[item.section].append(item) for (item_id, verdict) in delta.feedback: # "this item helped" or "this item hurt" find(playbook, item_id)[verdict] += 1 # metadata only: the text is untouched return playbook
Read what the merge cannot do: it cannot delete or shorten an old item’s text. A bad Reflector can add a poor bullet, but it cannot erase a good one. That is how the design avoids collapse.
Press the button to move through one round. The lit box is the role that is working. The text panel shows what it received and wrote.
Illustrative. The task and the two playbook items follow the lecture’s AppWorld case; the trajectory, insight and delta text are written by hand. In ACE each role is a model call, and the Reflector may loop several times.
Slides 23 to 28 show the AppWorld results. The base agent is ReAct on DeepSeek-V3.1. The table reports task goal completion (TGC) and scenario goal completion (SGC, a stricter score where every variant of a scenario must pass) on a normal and a challenge test split, and the average.
Slide 26: ACE beats in-context learning with retrieved examples (46.0 average) and the GEPA prompt optimizer (46.4), reaching 59.4 against the plain agent’s 42.4. Slide 27: ACE needs no labels. With only the environment’s own feedback it reaches 57.2. Slide 28: it works both offline (it evolves a system prompt before deployment) and online (it evolves agent memory during use), at 59.5 online against 51.9 for Dynamic Cheatsheet. The paper adds that on the AppWorld leaderboard ACE matches the top-ranked production agent on the overall average and passes it on the harder challenge split, using a smaller open-source model. The summary on slide 31 reads +10.6% on agents and +8.6% on finance tasks.
Accuracy and adaptation numbers are read from slides 23 to 29 (DeepSeek-V3.1 base). The slider applies to the serving view: with 91.8% of ACE’s input tokens served from cache (slide 30), a cached token billed at a fraction r of the normal rate cuts cost by 1 − (0.082 + 0.918 r). The slide’s 82.6% saving implies r of about 10%; that reading is ours, not the slide’s.
Slide 29 compares ACE with GEPA component by component. ACE cuts adaptation latency from 53,898 s to 9,517 s (82.3% lower) and rollouts from 1,434 to 357 (75.1% lower), and uses about 80.8% fewer input tokens while adapting. Slide 30 shows the other side. At serving time ACE’s context is long, more than twice the input tokens of the GEPA agent. But KV cache reuse helps: the provider stores the work already done on a prompt prefix, and a request that starts with the same prefix does not pay again. The playbook is a stable prefix, and only its end grows. So 91.8% of ACE’s input tokens are served from cache, which cuts billed input cost by 82.6%. The slide’s title is the lesson: longer context is not higher serving cost.
Slides 32 to 34 show production uses. At SCX.ai, a customer-service chatbot without ACE always issued a refund, funny and dangerous. With an ACE playbook it always asked for and verified the order ID and details first. At AnyShift, a platform engineering company, root-cause analysis was 30% faster. Slide 35 looks ahead: treat context as a fast, test-time medium for continual learning, then distill it into weights when it stabilizes. Named next steps are parallel context learning at scale (Combee), meta-evolution of memory systems and harnesses (Meta-Harness), safety and correctness of updates, and consolidation by self-distillation. For a full walkthrough of the paper, see the ACE paper lesson.
Chapter 11
Review the numbers, the checklist and the core code, then follow the links to go deeper
The lecture’s own summary slide lists six items: types of context, prompt optimization, long-context models, context management and memory, the guest lecture on agentic context engineering, and a demo of context evolution. The demo is a hands-on tutorial notebook linked from the course schedule, which is a good next step after this lesson.
Context is everything the model reads before the next token, and it comes from the developer, the user, the environment and the model itself. It changes behavior because the model attends to it: examples pick the task, written reasoning does computation. Prompts are powerful and brittle. A program can optimize them by search (APE), by textual feedback (TextGrad), or by compiling a modular program (DSPy). Long contexts cost T² unless attention is masked, and need training and position tricks. Memory carries lessons across tasks. The guest lecture adds the key warning: rewriting a context whole causes brevity bias and collapse. ACE grows a playbook by delta updates from three roles, and KV cache reuse keeps its long context cheap.
| What | Number | Why it matters |
|---|---|---|
| Context collapse (guest slide 9) | 18,282 → 122 tokens; accuracy 66.7 → 57.1; no context 63.7 | A rewrite can leave a context worse than none |
| Prompt format spread (slide 19) | 0.036 to 0.804 accuracy | Typing changes alone move a score hugely |
| APE (Zhou et al.) | As good or better than human prompts on 24 of 24 Instruction Induction tasks and 17 of 21 BIG-Bench tasks | Search can replace prompt guessing |
| TextGrad (Yuksekgonul et al.) | GPQA 51% → 55%; LeetCode-Hard +20% relative | Textual feedback works as a step direction |
| DSPy (Khattab et al.) | Over 25% (GPT-3.5) and 65% (llama2-13b-chat) above few-shot | Compiling a program beats hand-written prompts |
| GEPA (Agrawal et al.) | +6% on average, up to 20%, over GRPO with up to 35 times fewer rollouts | Reflection can beat reinforcement learning |
| Reflexion (Shinn et al.) | 91% pass@1 on HumanEval, against 80% for GPT-4 | Verbal memory of failures is a learning signal |
| Long-context training (slide 43) | 4K to 8K, then 32K to 128K, then 128K+ | Train short, then stretch |
| ACE on AppWorld (slides 23 to 28) | Average 42.4 → 59.4; 57.2 with no labels | A playbook adds 17 points to the same model |
| ACE adaptation cost (slide 29) | 53,898 s → 9,517 s; 1,434 → 357 rollouts | Deltas are cheaper than rewrite search |
| KV cache reuse (slide 30) | 91.8% of tokens cached; 82.6% lower billed input cost | A long stable prefix is cheap |
This is ACE reduced to its bones. Everything above is a variation on these lines.
pythondef evolve(queries, llm, env, playbook): for q in queries: traj = generate(llm, q, playbook, env) # Generator: run the agent. in: query + playbook text; out: code, calls, results insight = reflect(llm, q, traj, rounds=2) # Reflector: diagnose, then refine. out: short, specific statements delta = curate(llm, insight, playbook) # Curator: new items + helpful/harmful verdicts on existing ones playbook = merge(playbook, delta) # deterministic: append, dedupe, bump counters; never rewrite return playbook # same weights, better text # what goes in the next request: a stable prefix (playbook), then the new query last prompt = system + render(playbook) + query # prefix identical across queries, so the KV cache is reused
Context evolution is the first of the course’s four things that can evolve: context, harness, model and environment. Week 1 sets that frame. Week 3 goes further on using models to optimize and search over programs, and Week 5 moves up a level to evolve the harness itself.
Now press Present or Teach and explain, from memory, how a playbook grows and why a rewrite can destroy it. Then go back to the chart at the top, switch between the two update rules, and drag the step past 60 again. You should be able to say what is happening to every token.