About this notebook
Companion to Module 11: Optimizing agents. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Module 10 built the instruments: traces, graders, a gate. This notebook uses them to make an agent better without anyone editing its prompt by hand. The loop is the data flywheel:
┌──────────── serve users, record traces ────────────┐
│ v
deploy the better prompt collect feedback on each trace
^ │
│ v
optimise the prompt <── build a dataset <── turn traces + feedback into labels
(demos, instruction) (train / validation; the test set stays apart)You will
- serve a stream of support tickets with a traced classifier, and record a human triager’s feedback on each trace;
- turn the exported traces into a labelled dataset;
- optimise the demos: bootstrap them from the program’s own successes, then pick a set by random search;
- optimise the instruction: show a reflector model the failures and let it propose edits, keeping only those that help on validation;
- compare everything on a test set the optimisers never saw, and count what it cost.
Both models here are simulations
The student that classifies tickets is a rule set, not a language model. It reads three features of its prompt: the keyword lists in the label definitions, explicit priority rules, and the demos (by word overlap). Its accuracy therefore depends on the prompt in a way you can read in
agentlab/llm/fake_packs/nb11_prompt_opt.py. The reflector that proposes better instructions is a second rule set that imitates what a reflective optimiser asks an LLM to do. The loop, the data handling and the evaluation are real and would run unchanged against live models; the numbers only show how such a loop behaves, not how much a real model would gain.
from agentlab.llm import get_llm
from agentlab.nbsetup import setup
nb = setup("11a_flywheel_prompt_opt", packs=["prompt_opt"])
student = nb.llm
reflector = nb.track(get_llm(packs=["prompt_opt"], profile="11a_flywheel_prompt_opt"))LLM backend
offline policy model (deterministic, rule-based, no API key used)
1. The program
The agent is the first step of a support pipeline: read a ticket, send it to one of five queues. A program here is an instruction plus a list of demos; the optimisers below change those two things and never the code. This is the seed instruction someone wrote on day one:
from agentlab.optimize import SEED_INSTRUCTION, Program, load_tickets, predict
print(SEED_INSTRUCTION)
seed = Program()
for text in ["My package with the lamp has not arrived yet.",
"Can I get my money back for the kettle? It is broken.",
"I get an error on my phone when I try to reset my password on Friday."]:
print(f"\n{text}\n -> {await predict(seed, student, text)}")Classify the customer ticket into exactly one label.
Labels:
- shipping: where an order is and when it arrives (keywords: delivery, package)
- refund: the customer wants money back for an order (keywords: refund)
- billing: charges, payments and invoices (keywords: charge, charged, invoice)
- account: signing in and managing the customer account (keywords: account, password)
- bug: something on the website or in the app is broken (keywords: error, crash, crashes)
Answer with JSON: {"label": "<one label>"}.
My package with the lamp has not arrived yet.
-> shipping
Can I get my money back for the kettle? It is broken.
-> shipping
I get an error on my phone when I try to reset my password on Friday.
-> account
The first ticket uses a listed keyword and lands in the right queue. The second says
“money back” instead of “refund” and goes to shipping, the first label listed, which is
where this student goes when nothing matches. The third mentions both “error” and
“password”; the labelling guide says errors are bugs, but nothing in the instruction says
so.
2. Serve, trace, collect feedback
A week of production: 120 tickets, each handled inside a traced triage span (the
tracer from Notebook 10a). Downstream, a human triager either accepts the queue or
reassigns the ticket; that action is recorded as a feedback event on the trace. Here the
simulated triager knows the right answer and corrects every mistake.
from agentlab.optimize import serve
from agentlab.tracing import Tracer, export_jsonl
prod = load_tickets("prod")
tracer = Tracer()
labels = await serve(seed, student, prod, tracer, version="seed")
path = export_jsonl(tracer.spans, nb.workdir / "triage_traces.jsonl")
print(f"{len(prod)} tickets served, {len(tracer.spans)} spans written to {path.name}\n")
root = next(s for s in tracer.spans if s.name == "triage"
and s.events[0]["attributes"]["action"] == "reassigned")
print({k: root.attributes[k] for k in ("ticket.id", "input", "output")})
print(root.events[0])120 tickets served, 240 spans written to triage_traces.jsonl
{'ticket.id': 'p001', 'input': 'Checkout showed an error but I was still charged for the headphones.', 'output': 'billing'}
{'name': 'feedback', 'time': 1767225600.45438, 'attributes': {'action': 'reassigned', 'label': 'bug'}}
Now the flywheel turns: read the traces back and keep, for each one, the input and the label it ended up with (the triager’s correction if there was one, otherwise the model’s accepted answer). Then split by a hash of the ticket id into a training set (what optimisers learn from) and a validation set (what they are scored on while searching).
from collections import Counter
from agentlab.optimize import dataset_from_traces, split
from agentlab.tracing import load_jsonl
dataset = dataset_from_traces(load_jsonl(path))
train, val = split(dataset)
test = load_tickets("test")
print(f"dataset {len(dataset)}: {dict(Counter(ex.source for ex in dataset))}")
print(f"train {len(train)}, validation {len(val)}, test {len(test)} (separate tickets)")
print(f"production accuracy, from feedback alone: "
f"{sum(ex.source == 'accepted' for ex in dataset) / len(dataset):.2f}")dataset 120: {'corrected': 60, 'accepted': 60}
train 58, validation 62, test 60 (separate tickets)
production accuracy, from feedback alone: 0.50
Real feedback is thinner and noisier than this
Here every ticket gets feedback and every correction is right. In production most traces get no feedback at all, “accepted” often means “nobody looked”, and corrections come from busy people who disagree with each other. Treat accepted labels as weak, sample traces for careful human labelling, and keep the test set labelled by the most careful people you have. The test set here is 60 tickets that were never served, so nothing below can leak into it.
3. A baseline worth beating
Score the seed program on validation and test, and break the score down by the kind of ticket: direct tickets use a listed keyword, indirect ones say the same in other words, ambiguous ones contain keywords of two labels.
from agentlab.optimize import evaluate
base_val = await evaluate(seed, student, val)
base_test = await evaluate(seed, student, test)
print(f"seed validation {base_val.accuracy:.2f} test {base_test.accuracy:.2f}")
print("test by kind:", {k: round(v, 2) for k, v in base_test.by_kind(test).items()})seed validation 0.53 test 0.50
test by kind: {'ambiguous': 0.33, 'direct': 1.0, 'indirect': 0.15}
Direct tickets are solved, and nearly everything else is not. Two ways to improve: show the model examples (demos), or improve the instruction itself.
4. Optimising the demos
DSPy’s bootstrap few-shot runs the program on training inputs and keeps the runs that
pass the metric as demos: the program teaches itself from its own successes. Random
search then tries several random sets of demos and keeps the one that scores best on
validation. Both are a few lines (agentlab/optimize/fewshot.py).
from agentlab.optimize import bootstrap, random_search
successes = await bootstrap(seed, student, train)
kind_of = {t.id: t.kind for t in prod} # known only because the tickets are synthetic
print(f"bootstrapped {len(successes)} demos from {len(train)} training tickets")
print(" by kind:", dict(Counter(kind_of[ex.id] for ex in successes)))
print(" all training tickets:", dict(Counter(kind_of[ex.id] for ex in train)), "\n")
searches = {}
for name, pool in [("demos from successes", successes), ("demos from all labels", train)]:
best, tried = await random_search(seed, student, pool, val, k=12, candidates=10, seed=0)
searches[name] = best
scores = " ".join(f"{c.val.accuracy:.2f}" for c in tried)
print(f"{name:<22} validation per candidate (first = no demos): {scores}")bootstrapped 27 demos from 58 training tickets
by kind: {'direct': 17, 'ambiguous': 4, 'indirect': 6}
all training tickets: {'ambiguous': 13, 'direct': 17, 'indirect': 28}
demos from successes validation per candidate (first = no demos): 0.53 0.60 0.56 0.60 0.60 0.61 0.63 0.61 0.63 0.60 0.61
demos from all labels validation per candidate (first = no demos): 0.53 0.60 0.63 0.71 0.71 0.66 0.58 0.71 0.74 0.69 0.61
Demos bootstrapped from successes help a little, and the counts above say why. The
program succeeded mostly on tickets its keywords already handle (17 of the 27 are direct
tickets), and the rest are lucky: indirect shipping tickets that landed in shipping
only because it is the default, and ambiguous tickets whose tie happened to break the
right way. Such demos teach it little. Demos drawn from all labelled tickets include
the corrected failures, and those carry the information. (In a multi-step program, bootstrapped demos are worth
more than this: they show the model complete reasoning and tool-call traces to imitate.
For a single label there is nothing to imitate beyond the label.)
Note the spread between candidates. Which twelve demos you pick moves validation accuracy by more than ten points, which is why searching over demo sets pays.
5. Optimising the instruction by reflection
The second optimiser treats the instruction as the thing to learn. Each iteration:
evaluate current instruction on train ──> sample a minibatch of failures
^ │
│ keep only if validation improves v
evaluate the proposal on validation <── reflector: diagnose, propose an editThis is the shape of ProTeGi (Pryzant et al., 2023), which calls the reflector’s diagnosis a “textual gradient”, and of GEPA (Agrawal et al., 2025). Here is the prompt the reflector receives on the first iteration, and its reply.
from agentlab.optimize import parse_revision, reflection_prompt
first = (await evaluate(seed, student, train)).failures[:4]
prompt = reflection_prompt(seed.instruction, first)
print(prompt[prompt.index("These tickets"):])
reply = await reflector.ask(prompt)
print("\n--- reflector reply ---\n" + reply.split("<<<")[0])These tickets were labelled wrongly with the current instruction: 1. Ticket: Checkout showed an error but I was still charged for the headphones. | predicted: billing | expected: bug 2. Ticket: I get an error on my work computer when I try to reset my password on Monday. | predicted: account | expected: bug 3. Ticket: Pictures on the coffee grinder product page do not load. | predicted: shipping | expected: bug 4. Ticket: The lamp is scratched. I want my money back, not a replacement. | predicted: shipping | expected: refund For each failure, say in one line why the instruction led to the wrong label. Then PROPOSE A REVISED INSTRUCTION: keep the format, keep what works, and make the smallest general change that would fix these failures without breaking other tickets. Return the full revised instruction between <<< and >>>. --- reflector reply --- Diagnosis: - 'Checkout showed an error but I was still charged for the headphones.': keywords of bug and billing both appear; the tie went to billing. - 'I get an error on my work computer when I try to reset my password on Monday.': keywords of bug and account both appear; the tie went to account. - 'Pictures on the coffee grinder product page do not load.': nothing in the instruction says this is bug. - 'The lamp is scratched. I want my money back, not a replacement.': nothing in the instruction says this is refund. - Edits: add rule: tickets mentioning 'error' are bug
Now run the full search: up to eight iterations, a minibatch of eight failures each, and stop after two iterations in a row without an improvement.
from agentlab.optimize import reflective_search
search = await reflective_search(seed, student, reflector, train, val, iterations=8,
batch=8, patience=2, seed=0)
print(f"start: validation {base_val.accuracy:.2f}\n")
for st in search.steps:
edit = st.diagnosis.splitlines()[-1].removeprefix("- Edits: ")
v = " - " if st.val_acc is None else f"{st.val_acc:.2f}"
verdict = "keep" if st.accepted else ("repeat" if st.repeat else "drop")
print(f"iter {st.iteration} train {st.train_acc:.2f} val {v} {verdict:<6} {edit}")
print(f"\nbest validation {search.best_val.accuracy:.2f}, "
f"{search.calls} student and reflector calls")start: validation 0.53 iter 1 train 0.47 val 0.55 keep add keyword 'name' to account; add keyword 'back' to refund iter 2 train 0.66 val 0.66 keep add rule: tickets mentioning 'error' are bug; add rule: tickets mentioning 'refund' are refund iter 3 train 0.79 val 0.87 keep add keyword 'receipt' to billing; add keyword 'page' to bug iter 4 train 0.90 val 0.85 drop add keyword 'order page' to billing; add keyword 'phone' to account iter 5 train 0.90 val 0.85 repeat add keyword 'order page' to billing; add keyword 'phone' to account best validation 0.87, 605 student and reflector calls
What changed between the seed and the best instruction:
import difflib
for line in difflib.unified_diff(seed.instruction.splitlines(),
search.best.instruction.splitlines(), "seed", "optimised",
lineterm="", n=0):
print(line)--- seed +++ optimised @@ -4,4 +4,7 @@ -- refund: the customer wants money back for an order (keywords: refund) -- billing: charges, payments and invoices (keywords: charge, charged, invoice) -- account: signing in and managing the customer account (keywords: account, password) -- bug: something on the website or in the app is broken (keywords: error, crash, crashes) +- refund: the customer wants money back for an order (keywords: refund, back) +- billing: charges, payments and invoices (keywords: charge, charged, invoice, receipt) +- account: signing in and managing the customer account (keywords: account, password, name) +- bug: something on the website or in the app is broken (keywords: error, crash, crashes, page) +Rules: +- If the ticket mentions error, the label is bug. +- If the ticket mentions refund, the label is refund.
Read the diff the way you would review a colleague’s pull request. Two priority rules
encode the labelling guide exactly (“error” means bug, “refund” means refund), and
“receipt” is a fair billing keyword. Others fit the data more than the task: “back” (from
“money back” and “sent it back”) will misfire on “please call me back”; “page” sends
“the order page says 24 euros” to bug; “name” works only because two account templates
happen to mention one. The validation check accepted them because it scores a proposal as
a whole: every accepted proposal beat the one before, and nothing checked each edit on its
own. A real LLM reflector makes subtler versions of the same mistake: instructions that
fit the failures it was shown rather than the task.
The search then got stuck. Validation rejected the fourth proposal; the reflector, shown much the same failures, proposed it again (the search recognised the repeat and did not pay to score it twice), and patience ran out. GEPA avoids this by keeping a pool of candidates (a Pareto front across validation examples) instead of one, so a candidate that is better on some examples survives to be improved further. The remaining failures are one-off phrasings that no rule shared by two failures can fix, which is exactly what demos are good at.
6. Both together
combined, tried = await random_search(search.best, student, train, val, k=12, candidates=10,
seed=0)
print("validation per candidate:", " ".join(f"{c.val.accuracy:.2f}" for c in tried))validation per candidate: 0.87 0.90 0.89 0.89 0.89 0.87 0.87 0.89 0.87 0.87 0.89
7. The verdict on held-out tickets
Every optimiser above chose by validation score, so in general validation numbers are optimistic: selection rewards candidates that got lucky on those 62 tickets. The 60 test tickets were never served and never used to choose anything. They give the honest number.
programs = {
"seed instruction": seed,
"+ demos from successes": searches["demos from successes"],
"+ demos from all labels": searches["demos from all labels"],
"reflected instruction": search.best,
"reflected + demos": combined,
}
rows = []
for name, prog in programs.items():
v = await evaluate(prog, student, val)
t = await evaluate(prog, student, test)
kinds = t.by_kind(test)
rows.append((name, v.accuracy, t.accuracy))
print(f"{name:<25} val {v.accuracy:.2f} test {t.accuracy:.2f} test by kind: "
+ " ".join(f"{k} {kinds[k]:.2f}" for k in ("direct", "indirect", "ambiguous")))seed instruction val 0.53 test 0.50 test by kind: direct 1.00 indirect 0.15 ambiguous 0.33 + demos from successes val 0.63 test 0.55 test by kind: direct 1.00 indirect 0.19 ambiguous 0.50 + demos from all labels val 0.74 test 0.77 test by kind: direct 1.00 indirect 0.46 ambiguous 1.00 reflected instruction val 0.87 test 0.90 test by kind: direct 1.00 indirect 0.77 ambiguous 1.00 reflected + demos val 0.90 test 0.93 test by kind: direct 1.00 indirect 0.85 ambiguous 1.00
import matplotlib.pyplot as plt
import numpy as np
names = [r[0] for r in rows]
y = np.arange(len(rows))
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.barh(y - 0.18, [r[1] for r in rows], height=0.34, color="#2c5f9e", label="validation")
ax.barh(y + 0.18, [r[2] for r in rows], height=0.34, color="#2c7d54", label="test")
for i, r in enumerate(rows):
ax.text(r[2] + 0.01, i + 0.18, f"{r[2]:.2f}", va="center", fontsize=8, color="#81796f")
ax.set_yticks(y, names)
ax.invert_yaxis()
ax.set_xlim(0, 1.08)
ax.set_xlabel("accuracy")
ax.legend(frameon=False, loc="upper right")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Validation and test accuracy of each program. Demos from successes add little; demos that include corrected failures help; the reflected instruction helps most, and demos on top of it fix some of the one-off phrasings it could not.
Here test accuracy came out as good as validation or better, because both sets are drawn from the same templates; with real traffic, which drifts, expect the test number to be the lower one. Two more cautions before you trust a result like this with a real model.
- The gain is the simulation’s. This student reads keywords, so keyword edits move it a lot. A capable LLM already understands “money back”; its gains from prompt optimisation are usually smaller and come from conventions and edge cases (output format, policy priorities, when to ask a question). Measure; do not assume.
- Optimised prompts are fitted to one model. Change the model and the best demos and wording change with it. Keep the dataset and the optimiser, not just the prompt, and re-run them on every model upgrade, behind the Module 10 gate.
Count the cost as well: the searches above made thousands of student calls. With a live model that is real money, which is one reason to optimise a small model on a modest dataset, and to cache evaluations of candidates you have already scored.
total = student.usage.total_calls + reflector.usage.total_calls
print(f"student calls {student.usage.total_calls:,}, reflector calls "
f"{reflector.usage.total_calls}, total {total:,}")student calls 3,617, reflector calls 6, total 3,623
Try this
- Limit the reflector to one edit per proposal (in
reflectin the pack, changelen(edits) == 2to1). Does the search still accept “page” and “back”?- Make feedback sparse: in
dataset_from_traces, drop four traces in five. How small can the dataset get before the optimisers stop helping on the test set?- Add noise: let the simulated triager reassign 10% of correct tickets to a random queue. Which optimiser suffers most?
- Write a third optimiser that adds the failing training tickets as demos first (a “hard examples” pool), and compare it with random search.
- With a live model, point
studentat it and re-run. Which edits does a real reflector propose for the same failures?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 3623 (fake: 3623) | ≈ 1,400,120 | ≈ 21,019 | ≈ USD 1.4842 (reference price) |