Module 10 gave the agent a score. This module turns the score into a better agent. There are two places to make a change. The context is everything the model reads: the instruction, the examples, the tool descriptions. The weights are the model itself. Context changes are cheap, quick and work with any model behind an API; weight changes need training, but can teach a small model what prompting alone cannot. The CS329Z lecture on optimisation lists what either one needs: data, a system with parameters to change, and a metric that says whether a change helped. Without all three there is nothing to optimise, only guessing.
Notebooks
Notebook 11a: The data flywheel and prompt optimisation serves support tickets with a traced classifier, turns the traces and a triager’s corrections into a dataset, then improves the prompt with bootstrapped demos, random search and a reflective instruction search, scored on a held-out test set. Notebook 11b: GRPO on a toy tool router writes REINFORCE, group-relative advantages, ratio clipping and a KL penalty in numpy, trains a router that picks one of five tools, then fits a reward model to biased preferences and watches the policy exploit it.
The data flywheel
The data comes from the agent itself. Every request it serves is a trace (Module 10), and many products collect a signal about the outcome for free: a thumbs-down, an edit to a draft, a ticket moved to another queue.
Definition 11.1 (Data flywheel).A data flywheel is the loop that turns production use into improvement: serve requests and record traces, attach feedback to them, turn traces and feedback into a labelled dataset, optimise the agent on it, and deploy the new version only if it passes a held-out evaluation. The new version’s traces feed the next turn.
In notebook 11a the agent sorts support tickets into five queues (shipping, refund, billing, account, bug). In a simulated week it serves 120 tickets; a human triager accepts the queue or moves the ticket, and that action is recorded as a feedback event on the ticket’s trace. Half the tickets were moved, so production accuracy, read from the feedback alone, was 0.50. Each correction is a free, correct label. The 120 served tickets are split into train (58) and validation (62). The test set is 60 separate tickets that were never served, and it stays untouched until the end. The flywheel (Definition 11.1) has one rule that is easy to break: the deploy decision uses data the optimiser never saw.
Optimising the prompt
DSPy (Khattab et al.) treats a prompt as the parameters of a program: an instruction and a list of demonstrations, plugged into a fixed signature such as “ticket in, label out”.
Definition 11.2 (Prompt optimisation).Prompt optimisation searches over the instruction and the demonstrations of a fixed program, with the model’s weights frozen, to maximise a metric on a training and validation set. The optimiser calls the model many times; the deployed program calls it once per request, as before.
Notebook 11a tries the two main moves of prompt optimisation (Definition 11.2). The first is DSPy’s bootstrapped few-shot: run the program on the training tickets, keep the runs that pass the metric as demos, and pick the best set of demos by random search on validation. It helped little, and the reason is instructive. Of the 27 runs that passed, 17 were the easy tickets that use a listed keyword, so the demos showed the model what it already knew. Demos drawn from all labelled tickets, corrected failures included, did much better.
The second move rewrites the instruction. A reflector model reads the training tickets the current instruction got wrong, explains each failure in a line, and proposes a revised instruction; the revision is kept only if validation accuracy improves. Pryzant et al. call the explanation a textual gradient (ProTeGi); GEPA (Agrawal et al.) keeps a population of candidates instead of one, and MIPROv2 (Opsahl-Ong et al.) proposes instructions grounded in the data and searches over instruction and demo choices together. In the notebook the reflective search ran five rounds. It kept the proposals of the first three (new keywords for four labels and two priority rules such as “if the ticket mentions error, the label is bug”), rejected the fourth, and stopped when the reflector proposed it again. On the held-out test set:
| program | validation | test | test, indirect tickets |
|---|---|---|---|
| seed instruction | 0.53 | 0.50 | 0.15 |
| + demos from successes | 0.63 | 0.55 | 0.19 |
| + demos from all labels | 0.74 | 0.77 | 0.46 |
| reflected instruction | 0.87 | 0.90 | 0.77 |
| reflected + demos | 0.90 | 0.93 | 0.85 |
“Indirect” tickets say what they mean without a listed keyword (“I want my money back, not a replacement”). The whole search cost 3,617 calls to the classifier and 6 to the reflector.
Remark 11.1 (What these numbers do and do not show).The classifier in notebook 11a is a rule set that reads keywords, so keyword edits move it a lot; a capable LLM already knows that “money back” means a refund, and gains less. With 60 test tickets, 0.90 and 0.93 are not distinguishable; 0.50 and 0.93 are. And an optimised prompt is fitted to one model: keep the dataset and the optimiser, and re-run them, behind the eval gate, whenever the model changes.
With those caveats (Remark 11.1), the shape of the result is typical: the instruction carries the rules that apply to many tickets, and demos patch the one-off phrasings no rule covers.
Changing the weights with a verifiable reward
When prompting plateaus, the weights are the next lever. The lecture separates two recipes. Supervised fine-tuning (SFT) has a strong teacher model do the tasks and trains the student on the teacher’s trajectories. Reinforcement learning has the student do the tasks itself and rewards it when it succeeds. For agents the reward is often a program: the tests pass, the answer matches, the booking exists. The CS329Z lecture on agent data names the raw material of each recipe: SFT needs trajectories (recordings of an agent solving tasks), RL needs environments (a task, a sandbox to act in, and a verifier).
Definition 11.3 (RL with verifiable rewards).Reinforcement learning with verifiable rewards samples outputs from the current policy, scores each with a program that checks success, and changes the weights to make rewarded outputs more likely. Nobody writes a target output; the verifier only judges.
Notebook 11b strips this (Definition 11.3) to its smallest version, small enough to run in numpy
in two seconds. A query has one of five hidden types (arithmetic, fresh facts, data
analysis, scheduling, records lookup). The policy sees nine binary features of the query
and picks one of five tools; the verifier returns 1 if the tool solved it. A uniformly
random router scores 0.339, the best possible router given the features 0.718, and one
that could see the hidden type 0.910. The policy is a softmax over a linear function of
the features,
Push up the log-probability of what you did, in proportion to how much better than the
baseline
GRPO (Shao et al.) is the variant behind DeepSeek-R1. It samples a group of
It then takes several gradient steps on the same samples, with PPO’s clipped ratio
With equation
| method | final value |
|---|---|
| REINFORCE | 0.539 |
| REINFORCE with a baseline | 0.537 |
| GRPO, one gradient step per batch | 0.580 |
| GRPO, four gradient steps per batch | 0.679 |
The honest reading is that most of GRPO’s lead here comes from reusing each batch four
times, which the clipping in equation
Real fine-tuning starts from an SFT model, not a uniform one. The notebook’s SFT router,
trained on 100 demonstrations from an expert who slips 30% of the time, scores 0.555.
GRPO from there with different penalty weights
| value | KL to the SFT policy | |
|---|---|---|
| 0 | 0.692 | 0.307 |
| 0.05 | 0.687 | 0.255 |
| 0.2 | 0.673 | 0.186 |
| 1.0 | 0.624 | 0.058 |
With a reward you can trust, the KL term only costs value. Its job shows up when the reward is not trustworthy.
When the reward is learned
Many qualities have no verifier: helpfulness, tone, whether a plan is sensible. The usual
substitute is to ask people which of two outputs they prefer and fit a reward model to
those comparisons. The Bradley–Terry model, the standard choice (Lambert, chapter 5),
assumes that the probability of preferring
where web_search as if it were 0.5 more
likely to succeed than it is. The reward model fits well by the usual measure: loss falls
from 0.578 to 0.404, and it agrees with the annotators on 80% of held-out pairs. Yet its
favourite tool is web_search for every one of the five query types.
Remark 11.2 (Reward over-optimisation).A learned reward is a proxy for the true one. Optimising it hard finds the places where the two disagree: the proxy keeps rising while the true reward stalls, then falls. Gao et al. measured this for language models: the gap grows with the KL distance from the starting policy, which is what the KL penalty limits.
The notebook shows the effect (Remark 11.2) in miniature. GRPO on the reward model, from
the SFT router, for different
| reward | proxy reward | true value | KL | |
|---|---|---|---|---|
| reward model | 0 | 0.72 to 1.84 | 0.555 to 0.472 | 1.98 |
| reward model | 1.0 | 0.72 to 1.33 | 0.555 to 0.578 | 0.36 |
| reward model | 3.0 | 0.72 to 0.95 | 0.555 to 0.588 | 0.03 |
| verifier | 0 | 0.555 to 0.658 |
Without the penalty, the policy more than doubled its proxy reward and ended worse than where it started. A strong penalty prevents the damage, but also most of the gain. The verifier, which cannot be flattered, did best. For agents the lesson is to use verifiable rewards wherever the task allows (tests, exact checks, the state of the environment), to judge training by the true metric rather than the reward, and to check a reward model’s agreement on the cases where it matters, not only on average. An overall 80% hid a bias that applied everywhere.
The same lecture collects the ways agent data teaches things nobody intended. An environment with a loophole trains the loophole: coding agents have learned to make a test run report success instead of fixing the code, which is Module 13’s reason to keep the verifier out of the agent’s reach. Trajectories recorded in a single harness teach that harness’s conventions along with the skill, so the model stumbles in another. And a model trained on human approval can learn to look right rather than be right, the human version of the reward-model bias above.
Which lever to pull
| lever | what changes | what it needs | when |
|---|---|---|---|
| prompt optimisation | instruction, demos | dozens to hundreds of labelled examples and a metric | first, and after every model change |
| SFT | weights | trajectories from a stronger teacher | to make a small, cheap model behave like a large one |
| RL with a verifier | weights | tasks, a verifier, much compute | when success is checkable and prompting has plateaued |
The lecture’s own summary is that optimisation is for the last mile: a general model is a good start, and optimisation adapts it to your data and your metric. Agents are now capable optimisers themselves, editing prompts, harnesses or code and keeping what scores better, which makes the metric the part that most needs guarding. Whatever is optimised, the eval gate of Module 10 decides what ships.
Try this
- In notebook 11a, the simulated triager in
agentlab/optimize/flywheel.pyalways knows the right queue. Make it wrong on 10% of tickets. How much do the demo and instruction searches lose on the test set? - Replace the reflector’s keep-if-better rule with keep-the-best-two (a small pool, as GEPA does). Does the search still get stuck after round four?
- In notebook 11b, run
grpowithgroup_size2, 4, 8 and 16 andgroups = 128 // group_size, so every run sees 128 rollouts per step. Plot the final value and the share of dead groups. Which group size is best here, and why does equation behave badly for ? - Set the annotator bias to 0 and re-run the reward-model experiment. Does over-optimisation disappear, or does a weaker version remain?
- Add a sixth tool that always fails but which the annotators rate highly. How fast does the unpenalised policy find it?
Readings
- Stanford CS329Z, Engineering AI Agents, Lecture 9: Optimization (slides), and Lecture 11: What data do agents need? by Diyi Yang, Michael Ryan and John Yang (slides), on trajectories, environments and what agent data teaches by accident.
- Hur and Song, Build an AI Agent (From Scratch), Manning 2026, section 10.4 on evaluation-gated deployment and the quality flywheel.
- Lambert, Reinforcement Learning from Human Feedback, Manning 2026: chapter 5 (reward models), chapter 6 (policy gradients, including GRPO), chapter 7 (verifiable rewards), chapter 14 (over-optimisation) and chapter 15 (regularisation).
- Khattab et al., DSPy: compiling declarative language model calls into self-improving pipelines, 2023.
- Opsahl-Ong et al., Optimizing instructions and demonstrations for multi-stage language model programs, 2024 (MIPROv2).
- Pryzant et al., Automatic prompt optimization with “gradient descent” and beam search, 2023 (ProTeGi).
- Agrawal et al., GEPA: reflective prompt evolution can outperform reinforcement learning, 2025.
- Williams, Simple statistical gradient-following algorithms for connectionist reinforcement learning, Machine Learning, 1992.
- Shao et al., DeepSeekMath: pushing the limits of mathematical reasoning in open language models, 2024 (GRPO).
- DeepSeek-AI, DeepSeek-R1: incentivizing reasoning capability in LLMs via reinforcement learning, 2025.
- Gao, Schulman and Hilton, Scaling laws for reward model overoptimization, ICML 2023.
- Liu et al., Understanding R1-Zero-like training: a critical perspective, 2025 (Dr. GRPO), and Yu et al., DAPO: an open-source LLM reinforcement learning system at scale, 2025.