Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 15
Module 7 · Case studies: applying the design principles · Chapter 15 of 24
Case study: an agent that builds LLM pipelines
Builds on Agent design fundamentals, Embeddings and vector databases, Fine-tuning language models and Case study: an agent that writes reward functions. Next up: Case study: designing a web agent.
Part 1 · The problem and its requirements
Why build pipelines with an agent
Every team that adds a language model to a product tunes the same things by hand: a prompt, a few examples and an output format. A pipeline-building agent runs that search: it proposes a configuration, tests it on labelled examples and keeps the best.
A pipeline, in this chapter, is everything around one model call that you can change without changing the model: the prompt template, how many worked examples it shows and how they are chosen, whether the model may think first, and the shape of the output. Tuning the pipeline is the cheapest way to improve a task, and it is what the fine-tuning chapter said to try before touching weights.
The input to the system is a task specification (a sentence saying what to do and what the allowed labels are) and labelled examples (messages with the correct label, written by a person). The output is a tested pipeline configuration and its measured score.
The task here is a made-up one. Residents of an apartment society write to the office, and each message must be routed to one of five labels: safety, repair, billing, amenity or noise. The rule that makes it interesting is that safety wins over every other label: someone trapped in a lift is safety, while a lift stuck with nobody inside is repair. A prompt that does not know the rule will get those messages wrong.
Requirements
Functional requirements:
- Accept a task specification and 30 labelled examples.
- Split the examples into a development set for searching and a test set for one final check.
- Propose several candidate configurations, and reject invalid ones.
- Run each candidate on the development set and score it with code.
- Return the best configuration with its development and test scores.
Non-functional requirements decide what a good design is:
| Quality | Target | What it forces |
|---|---|---|
| Honest scores | The test set is looked at once | A split, and a rule about who may see which half |
| Bounded cost | A fixed number of model calls per search | A budget in code, not in a prompt |
| Repeatability | A second search costs almost nothing | A cache keyed on the exact request |
| Safe output | Every candidate is a validated object, never model-written code | A typed schema for configurations |
| Explainability | Each choice has a table row to point to | A log of every run |
The metric is accuracy: the share of examples where the returned label equals the true label. It needs a baseline to mean anything. With five labels in equal numbers, a pipeline that always answers noise scores 20 per cent, 4 out of 20 on the development set. Anything near that is no better than guessing one label.
The data and the split
There are 30 invented messages, six per label. They include boundary cases on purpose. The split puts 20 in a development set (used to compare candidates) and 10 in a test set (looked at once, at the end). The split is stratified, meaning each label has the same share in both halves, so the test set is not made of easy cases by accident. A fixed shuffle spreads the labels through the file.
rows = [] for c in CLASSES: for j, text in enumerate(ITEMS[c]): rows.append({"text": text, "label": c, "split": "test" if j in (2, 5) else "dev"}) # fixed shuffle so neighbours are not all one class order = [(i * 7) % 30 for i in range(30)] assert sorted(order) == list(range(30)) rows = [rows[i] for i in order] for i, r in enumerate(rows): r["id"] = i + 1 json.dump({"task": "Route a resident's message to the society " "office with one label: " + ", ".join(CLASSES) + ".", "classes": CLASSES, "examples": rows}, open("data.json", "w", encoding="utf8"), indent=1, ensure_ascii=False)
{
"text": "The intercom in flat 3C does not ring.",
"label": "repair",
"split": "dev",
"id": 28
}The shape of one example in data.json.
30 examples; 20 dev; 10 test dev {'safety': 4, 'repair': 4, 'billing': 4, 'amenity': 4, 'noise': 4} test {'safety': 2, 'repair': 2, 'billing': 2, 'amenity': 2, 'noise': 2}
Output from make_data.py.
Labels are also opinions. Two people reading "A tile is cracked outside the Tower B entrance" might choose repair or, if someone could trip, safety. The rule in the task, safety only for danger right now, settles it for this set, but a real task needs a written labelling guide and a second reader for disputed items. A search cannot rise above the quality of its labels. If a few of them are wrong, the best score it can report is capped, and it may reward a candidate that copies the mistake.
Thirty examples is small, and that matters for everything that follows. With 20 development examples, one message is 5 percentage points. The fourth lesson returns to what that means for choosing between candidates.
Why is the test set looked at only once?
- Every look at the test set while choosing a configuration leaks information into the choice. After a few looks, the test score is no longer an honest estimate.
Part 2 · The search space
What a candidate can vary
A search needs a space to search. Here a candidate has five fields, and each field matters in a different way.
| Field | Values | What it changes |
|---|---|---|
| style | bare, rules, definitions | How much of the routing rule the prompt states |
| shots | 0 to 6 | Worked examples shown before the message (few-shot) |
| retrieval | true or false | Shots chosen by similarity to the message, not by a fixed order |
| output | label, reason_then_label | Only a label, or a short reason first |
| effort | none, low | Whether the model thinks before answering |
A real search space would also include the model itself. Only one model fits on this machine, so it is fixed here and named in the log instead. The five fields are a small search space: 3 × 7 × 2 × 2 × 2 = 168 combinations, counting the retrieval flag even at 0 shots, where it changes nothing. A model proposes a handful of them, which is the point: the cost of trying all 168 is the cost the agent exists to avoid.
Retrieval needs a short explanation. With retrieval-based few-shot selection, the message is embedded as a vector, the development examples are ranked by cosine similarity to it, and the closest ones become the shots. A message about a stuck lift then sees the other lift messages, with their labels. The embeddings come from the local embedding model, as in the vector databases chapter, scaled to length 1 so that the dot product of two vectors is their cosine similarity.
A configuration as a typed object
The configuration is a Pydantic model. Types and ranges are checked when it is built, so a candidate with 50 shots or an unknown style cannot exist.
class Config(BaseModel): style: Literal["bare", "rules", "definitions"] shots: int = Field(ge=0, le=6, description="Examples in the prompt") retrieval: bool = Field( description="Pick the shots most similar to the message") output: Literal["label", "reason_then_label"] effort: Literal["none", "low"] = "none" def key(self): return json.dumps(self.model_dump(), sort_keys=True)
The pool of shots and the prompt are built from the configuration by ordinary code. The system message holds the style text. Each shot becomes a user message with the example and an assistant message with the correct answer, in the same JSON shape the model must produce.
def pick_shots(cfg, item): pool = [e for e in DEV if e["id"] != item["id"]] # never itself if cfg.shots == 0: return [] if cfg.retrieval: q = embed(item["text"]) pool.sort(key=lambda e: -float(embed(e["text"]) @ q)) return pool[:cfg.shots] def messages(cfg, item): msgs = [{"role": "system", "content": STYLES[cfg.style]}] for s in pick_shots(cfg, item): msgs.append({"role": "user", "content": s["text"]}) msgs.append({"role": "assistant", "content": json.dumps( {"category": s["label"]} if cfg.output == "label" else {"reason": "main cause", "category": s["label"]})}) msgs.append({"role": "user", "content": item["text"]}) return msgs
The result is an ordinary list of chat messages. The script below prints the prompt for the first development message under a configuration with the definitions style and two fixed shots. The message being scored is the last one, and it is not among its own shots.
[system]
Route the message with one label.
safety: danger to a person or property right now. Safety wins over
every other label.
repair: a fault in the building or its services with no immediate danger
billing: charges, statements, receipts and payments
amenity: booking or asking about shared facilities
noise: complaints about noise
[user]
Corridor lights on the 5th floor have not worked for two days.
[assistant]
{"category": "repair"}
[user]
How do I join the society library?
[assistant]
{"category": "amenity"}
[user]
Someone is trapped inside the lift in Tower C right now.Output from show_prompt.py; no model call is made. Long lines are wrapped here.
Asking the model for candidates
The proposing step asks the model for six configurations through structured output, which constrains the reply to a list of the configuration type. The prompt also gives a rule that the schema cannot express: use effort: low at most twice.
class Proposals(BaseModel): configs: list[Config] PROMPT = f"""You design prompts for a classification task. Task: {DATA['task']} Propose 6 different configurations to test. Vary the style, the number of worked examples (shots, 0 to 6), whether examples are retrieved by similarity, the output form and the thinking effort. Use effort "low" at most twice."""
A first call of the proposal step shows why. The prompt said to use effort: low at most twice. The reply was a list of six valid configurations, and all six had effort: low. A schema can enforce the shape of each item and cannot enforce a rule about the whole list, so the code below does. It keeps the first two low candidates and sets the rest to none. This is one call of one model. The claim is only that the rule can be broken, and that code has to hold it.
def enforce(configs, max_low=2): """The schema cannot say 'at most two'. Code can.""" fixed, low = [], 0 for c in configs: if c.effort == "low": low += 1 if low > max_low: c = c.model_copy(update={"effort": "none"}) fixed.append(c) return fixed
That function is the lesson in miniature. A schema enforces the shape of each candidate and cannot enforce a rule about the set. Code can, so the code does. The same pattern appears in every agent system: let the model propose, then let ordinary code decide what is allowed.
Watch for the shots coming from similar examples, not from a fixed list
Read it as steps
Part 3 · Generate and test
Scoring one candidate
To test a candidate, run it on every development example and compare the label it returns with the true one. The comparison is plain code: the label is right or it is not. There is no judge model, which keeps the score exact and repeatable.
The function below builds the prompt from the configuration, asks the model for a label as structured output, validates the reply and caches the result. The validation matters. If the reply is cut off or is not one of the five labels, the function returns None, which counts as a wrong answer, instead of raising an error in the middle of a search. The output limit of 1,200 tokens includes any thinking tokens, so a candidate that thinks cannot run away.
def classify(cfg, item): fmt = LabelOnly if cfg.output == "label" else ReasonThenLabel msgs = messages(cfg, item) key = hashlib.sha256(json.dumps( [MODEL, cfg.key(), msgs]).encode()).hexdigest() if key in CACHE: _log(key, 0.0, 0, 0, True) return CACHE[key] t0 = time.time() r = client.chat.completions.create( model=MODEL, messages=msgs, reasoning_effort=cfg.effort, temperature=0, max_tokens=1200, response_format={ "type": "json_schema", "json_schema": { "name": "label", "schema": fmt.model_json_schema()}}) try: label = fmt.model_validate_json( r.choices[0].message.content).category except (ValidationError, TypeError): label = None # counted as a wrong answer
The cache key is a hash of the model name, the configuration and the full list of messages. If the model, the configuration or the messages change, the key changes. Temperature and the token limit are fixed in the code, so they are not part of the key. If nothing did, the call is skipped. The fourth lesson uses this to repeat a search for free.
The search and its table
The search script asks for candidates, scores each on the development set, prints a table and picks the best. A tie goes to the candidate with fewer shots, because fewer shots mean a shorter prompt and lower cost.
import json from core import DEV, TEST, evaluate from propose import propose cfgs = propose() print(len(cfgs), "valid candidates") print("id style shots retr output effort " "dev secs") rows = [] for i, c in enumerate(cfgs, 1): ev = evaluate(c, DEV) rows.append((c, ev)) print(f"{i:<3} {c.style:<12} {c.shots:<5} {str(c.retrieval):<5} " f"{c.output:<18} {c.effort:<6} " f"{ev['correct']}/{ev['n']} {ev['secs']}") # best by dev accuracy; a tie goes to the config with fewer shots best_cfg, best_ev = max(rows, key=lambda r: (r[1]["acc"], -r[0].shots)) print("best on dev:", json.dumps(best_cfg.model_dump())) t = evaluate(best_cfg, TEST) print(f"test (checked once): {t['correct']}/{t['n']}") json.dump({"rows": [{"cfg": c.model_dump(), **e} for c, e in rows], "test": t}, open("search_run.json", "w"), indent=1)
6 valid candidates id style shots retr output effort dev secs 1 bare 0 False label low 11/20 159.6 2 bare 6 False label low 18/20 116.9 3 bare 0 True label none 16/20 58.2 4 definitions 3 False label none 20/20 54.3 5 definitions 0 True label none 19/20 48.3 6 definitions 3 True reason_then_label none 19/20 53.0 best on dev: {"style": "definitions", "shots": 3, "retrieval": false, "output": "label", "effort": "none"} test (checked once): 10/10
Output from run_search.py on this machine, one run at temperature 0; the proposal step is random, so yours will differ. Seconds include waiting on a shared model server. Long lines are wrapped here.
Read the table before anything else. Three things stand out in this run, which used one model (gemma4:12b, run locally) and one pass per candidate.
- The prompt style mattered most. The three candidates with the bare style scored 11, 18 and 16. The three that spelled out the routing rule scored 20, 19 and 19.
- Thinking did not help. Candidates 1 and 3 differ only in effort (candidate 3 also asks for retrieval, but with 0 shots there is nothing to retrieve). With effort
lowthe score was 11 out of 20, and without it 16. Candidate 1 also cost the most. This is one run, so it shows that thinking is not free, and does not show that it always hurts.
One look at the test set
The best candidate on the development set is number 4: the definitions style, 3 fixed shots, label output, no thinking. It scored 20 out of 20. Only now does the code touch the test set, once, with that candidate.
best on dev: {"style": "definitions", "shots": 3, "retrieval": false,
"output": "label", "effort": "none"}
test (checked once): 10/10The last lines of the same run.
The test score is 10 out of 10. That is a good sign and a weak proof. Ten examples can only say so much, and the next lesson puts numbers on it. A score of 10/10 on the test set does not mean 100 per cent on messages you have not seen. It means the pipeline did not fail on these ten.
A second search, run later from an empty cache, asked the model for six new candidates, as the proposer is random. Its two zero-shot, effort low candidates scored 11 and 10 of 20. Its four rules-style candidates with 3 to 6 shots scored 17, 18, 19 and 19. Its best, 19 of 20, scored 10 of 10 on the test set. The details differ and the pattern repeats: stating the routing rule and showing examples helped, and thinking did not help.
It also does not make the test set reusable. If the next idea is tried on the test set and then changed, the test set has become a second development set. The honest next step is to collect new labelled examples.
Why does a reply that is not one of the five labels count as wrong, instead of stopping the search?
- A search runs many calls. One bad reply should lower a score, not end the run. Returning
Noneand counting it wrong keeps the table complete and honest.
Candidates 1 and 3 differ in effort. What does the table show, and what does it not show?
- With thinking on (low), 11/20; with it off, 16/20, at a much lower cost. It is one run of one model, so it does not show that thinking always hurts.
The test score is 10/10. Does that mean the pipeline is 100 per cent accurate?
- No. It means no errors on ten examples. The interval in the next lesson shows the true rate could still be as low as about 72 per cent.
Part 4 · Overfitting and cost
How sure is a score
A score from 20 examples is a measurement with error, and the error is large. One message is 5 percentage points. A confidence interval gives a range that would contain the true accuracy in about 95 of 100 repeated experiments. The Wilson score interval is a standard choice for a proportion when the sample is small, and it behaves sensibly near 0 and 100 per cent, where the simpler textbook formula does not.
import json import math def wilson(k, n, z=1.96): """95% Wilson score interval for k successes in n trials.""" p = k / n d = 1 + z * z / n centre = (p + z * z / (2 * n)) / d half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d return centre - half, centre + half
candidate dev 95% interval 1 11/20 34% to 74% 2 18/20 70% to 97% 3 16/20 58% to 92% 4 20/20 84% to 100% 5 19/20 76% to 99% 6 19/20 76% to 99% test 10/10 72% to 100%
Output from intervals.py over the saved search run.
Candidates 4, 5 and 6 scored 20, 19 and 19, and their intervals overlap almost completely: 84 to 100, 76 to 99 and 76 to 99. The data cannot say that candidate 4 is better than candidate 5. It can say the three of them are better than candidate 1, whose interval tops out at 74. A difference of one example is noise. To tell 20/20 from 19/20 you would need far more than twenty examples.
The winner's curse
There is a second problem, and it comes from the search itself. When you pick the best of six noisy scores, the best one is partly the luckiest. This is selection bias, sometimes called the winner's curse: the winning score is higher than the winner's true accuracy, on average, because winning rewarded luck as well as quality.
A simulation shows its size. Take six candidates that are all exactly 80 per cent accurate. Score each on 20 examples, keep the best, and repeat 10,000 times with a fixed random seed.
import numpy as np rng = np.random.default_rng(7) TRUE_ACC, N_DEV, N_CAND, TRIALS = 0.80, 20, 6, 10_000 # every candidate is equally good: its true accuracy is 0.80 dev = rng.binomial(N_DEV, TRUE_ACC, size=(TRIALS, N_CAND)) / N_DEV best = dev.max(axis=1) print(f"each candidate's true accuracy {TRUE_ACC:.2f}") print(f"mean dev accuracy of one candidate {dev.mean():.3f}") print(f"mean dev accuracy of the best of {N_CAND} {best.mean():.3f}") print(f"best of {N_CAND} reads 0.90+ in {np.mean(best >= .9):.0%} " "of trials") print(f"one dev example moves accuracy by {1 / N_DEV:.2f}")
each candidate's true accuracy 0.80 mean dev accuracy of one candidate 0.800 mean dev accuracy of the best of 6 0.906 best of 6 reads 0.90+ in 75% of trials one dev example moves accuracy by 0.05
Output from winners_curse.py; seeded, so it repeats exactly.
A single candidate averages 0.800, as it should. The best of six averages 0.906, and reads 0.90 or more in 75 per cent of the trials, although every candidate is 0.80. A development score of 20/20 after a search over six candidates is therefore less impressive than the same score for one candidate chosen in advance. That is the reason the test set exists and why it must be looked at once. The simulation models candidates with independent noise. Real candidates share the same 20 examples, so their scores are correlated and the bias is smaller, but the direction is the same.
A third kind of leak is quieter. The agent in the next lesson reads the mistakes on the development set and changes the prompt in response. Each round of that is a small fit to those 20 messages. A prompt that names the exact words of a failed message would score well on the development set and tell you nothing about new messages. The defences are the ones already in place: the test set stays out of the loop, and shots are drawn without the example being scored. A fourth defence is how you report. Say "19 to 20 of 20 on development (76 to 100 per cent), 10 of 10 on test (72 to 100 per cent), after a search over six candidates", and not "100 per cent".
Cost and caching
Every candidate costs one model call per example. The estimate for this search is simple arithmetic, and the run confirms it: 130 calls, 120 on the development set and 10 on the test set.
Average per call: about 4 s (515 s over 130 calls)
Read it as steps
Calls multiply: candidates, examples and calls per example.
cand calls prompt tok completion tok seconds 1 20 704 7257 160 2 20 3969 5091 117 3 20 744 240 58 4 20 3640 144 54 5 20 1944 214 48 6 20 4077 285 52 test 10 1815 72 25
Output from percand.py over the call log of the same run: calls, tokens and seconds per candidate, and the test run.
The cost is not spread evenly. Candidates 1 and 2 used thinking and wrote 7,257 and 5,091 completion tokens, against 144 to 285 for the others, and took about two to three times as long. Candidate 4, the winner, spent its cost on prompt tokens instead: its three examples made each prompt about five times longer than the zero-shot one (3,640 against 704 tokens for 20 calls). Retrieval also calls the embedding model, which is not in this log.
Caching
Caching removes repeated cost. After the search, a second pass over the same six candidates and the same examples is run with a fresh log.
second pass over 6 candidates: same scores, 0.55 s
Output from rerun.py. The time varies on this machine. All 120 calls were answered from the cache.
calls logged 120 cache hits 120 model calls 0
The summary of the fresh log, from cost.py.
All 120 calls hit the cache and the scores matched exactly. Time fell from minutes to half a second. The same cache serves the agent in the next lesson, which tries some of the same configurations again. It is valid only because the call is deterministic here, with temperature 0, and because the key includes everything that affects the answer.
Why are the intervals for 20/20 and 19/20 almost the same?
- With 20 examples, one example moves the score by 5 points and the sampling error is much larger. The data cannot separate them.
A search keeps the best of six candidates. Why is its development score biased upward?
- The best of several noisy scores is partly the luckiest. In the simulation, six 80 per cent candidates averaged 0.906 for the best.
What must a cache key include for the cache to be safe?
- Everything that can change the answer: the model, the full configuration and the exact messages. If any changes, the key changes.
Part 5 · An agent that tunes the pipeline
An agent that chooses what to try next
So far the search was a fixed script: propose six, test six, pick one. An agent version lets the model choose what to try next after it sees the mistakes of the last attempt. That is the propose, train, reflect loop of the reward design case study, with a test run in place of training, applied to prompts. The model gets two tools. evaluate runs a configuration on the development set and returns the accuracy and up to three messages it got wrong. finish names the final configuration.
The agent never sees the test set. It cannot call any tool that reads it. After finish, ordinary code checks the chosen configuration on the test set once, outside the loop.
def run(max_evals=5, max_steps=10, temperature=0.7): msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": "Start."}] seen, evals, log, best = set(), 0, [], None for _ in range(max_steps): r = client.chat.completions.create( model=MODEL, messages=msgs, tools=TOOLS, reasoning_effort="none", temperature=temperature, max_tokens=400) m = r.choices[0].message if not m.tool_calls: log.append("no tool call: stop") return (best[0] if best else None), evals, log, "no_call" msgs.append(m) for c in m.tool_calls: out = {"error": "unknown tool"} try: cfg = Config(**json.loads(c.function.arguments)) except (ValueError, ValidationError, TypeError) as e: out = {"error": f"invalid config: {str(e)[:90]}"} log.append(f"{c.function.name}: invalid config") cfg = None if cfg and c.function.name == "finish": if cfg.key() not in seen: out = {"error": "finish with a configuration you " "evaluated"} log.append("rejected: finish on unevaluated config") else: log.append("finish") return cfg, evals, log, "finished"
if cfg and c.function.name == "evaluate": if cfg.key() in seen: out = {"error": "already evaluated"} log.append("rejected: repeat") elif evals >= max_evals: out = {"error": "budget used; call finish"} log.append("rejected: budget") else: seen.add(cfg.key()) evals += 1 ev = evaluate(cfg, DEV) wrong = [e["text"] for e in DEV if classify(cfg, e) != e["label"]][:3] out = {"accuracy": ev["acc"], "mistakes": wrong} log.append(f"evaluate #{evals}: {ev['correct']}/" f"{ev['n']} {short(cfg)}") if best is None or ev["acc"] > best[1]: best = (cfg, ev["acc"]) msgs.append({"role": "tool", "tool_call_id": c.id, "content": json.dumps(out)}) return (best[0] if best else None), evals, log, "steps"
Limits, tests and a real run
The loop adds the same guard pattern as the other cases. Every limit is code:
- The arguments of both tools are the configuration schema, so an invalid configuration is rejected before anything runs.
- A configuration that was already evaluated is refused, so the agent cannot spend its budget on repeats.
finishmust name a configuration that was evaluated, so the final choice always has a measured score.- At most five evaluations are allowed. A sixth call gets an error that says to call
finish. - At most ten model steps are allowed in total.
Those limits are tested with a scripted model and a fake evaluator, so they run without the real model: a repeated configuration is evaluated once, an invalid one (99 shots) is rejected and never evaluated, a sixth evaluation is refused, a finish on an unevaluated configuration is refused, and a reply with no tool call ends the run and returns the best configuration so far.
Feeding the loop bad replies of your own is the quickest way to trust it. The replies tried here were arguments that are not JSON, a JSON list, null, shots of -1, 2.7 and an effort of high, seven evaluate calls in one reply, a finish before anything was evaluated, and fifty repeated calls of one configuration. Every one ended without a crash. The invalid ones were rejected before any evaluation, the seven calls ran five evaluations and refused two, the early finish was refused twice, and the repeats were refused until the ten-step limit ended the run with one evaluation. Two details are worth knowing. A tool name the loop does not know is ignored without a log line, and an extra field in the arguments is dropped silently, because Pydantic ignores extra fields unless told otherwise.
15 passed in 1.44s
Output from `uv run python -m pytest -q test_pipe.py`; 15 tests, of which 6 cover the agent loop and 9 cover the split, the schema, the shots and the limit on proposals. Timing varies on this machine.
A real run of the agent
A run of the agent on the real model follows. It used 4 of its 5 evaluations and then finished. Its final configuration is checked on the test set once, outside the loop.
evaluate #1: 15/20 bare, 1 shots, retrieved, label, effort none evaluate #2: 18/20 rules, 3 shots, retrieved, label, effort none evaluate #3: 19/20 definitions, 3 shots, retrieved, label, effort none evaluate #4: 19/20 definitions, 3 shots, retrieved, reason_then_label, effort none finish stopped: finished | evaluations used: 4 chosen: {"style": "definitions", "shots": 3, "retrieval": true, "output": "label", "effort": "none"} test (checked once): 10/10
Output from agent_search.py, one run at temperature 0.7 on this machine. Long lines are wrapped here.
The run above is one of five logged runs, each at temperature 0.7. Four had nearly the same shape. Each began with a bare prompt and a single shot (15 or 16 of 20), moved to the safety rule (18), then to the definitions style with 3 retrieved shots (19), and in two of them tried a fourth variant that changed the output form (19). All four finished before the budget, with 3 or 4 of the 5 evaluations used, and all four chose the definitions style with 3 retrieved shots. All four scored 10 out of 10 on the test set. They did not find the 20 out of 20 candidate that the fixed script found. One example separates them, which the interval table shows is noise.
Three more runs from a fresh cache followed the same path. Two went 15, 18, 19 of 20 and one went 17, 18, 20, each finishing after three evaluations with 10 of 10 on the test set. None of the three reached the budget or triggered a refusal.
The fifth run, and what it found
The fifth run went differently and is the most useful one. Its three evaluations scored 15, 18 and 20 of 20, all with effort: low. Then the model called finish twice on a configuration it had not evaluated, and the guard refused both calls. On its third attempt it replied with no tool call at all, so the loop stopped. Then the script crashed. The fallback path for a reply with no tool call returned the best configuration as a pair of configuration and score, and the test-set code expected a configuration. No test had covered that path. The run found a real bug, the fix is one line, and two tests now cover it: no tool call returns the best configuration so far, or nothing if none was evaluated.
Two more things are worth saying. The four similar paths were close to identical although the temperature was above zero, so the proposals are less varied than the setting suggests. And the two earliest runs were made before the rule that finish must name an evaluated configuration existed. A check afterwards showed that in the one of them that chose a reason-first configuration, all 20 of its development calls were in the log, so it had been evaluated.
Why does the agent never see the test set?
- Anything it can read can steer its choice. The test set is checked by code once, after
finish.
The agent calls finish with a configuration it never evaluated. What does the guard do?
- It rejects the call with an error, so the final choice is always one with a measured development score. A test with a scripted model covers this case, and in one real run the guard refused such a call twice.
The fifth run crashed after the model stopped calling tools. What does that show about testing?
- A path that no test covers can hide a bug that only a real model reaches. The fix was one line and two tests, one for each case of the fallback.
Part 6 · Mapping to optimisers, and a design review
Optimiser libraries and where they fit
Libraries exist for this job. DSPy describes itself as a framework for programming, not prompting, language models: you write the steps of a pipeline as code, and an optimiser searches for good instructions and examples against a metric and a development set. Its paper, "DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines" (Khattab et al., 2023), gives the idea. The lab here is a small version of it with every moving part visible: a typed search space, a metric in code, a split, a budget and a cache. The optimiser libraries add smarter search than six guesses and a catalogue of pipeline modules. They do not remove the need for any of the limits above.
A practical way to use such a library is to treat it as a second opinion. Run its optimiser on the same split and the same metric, then compare its candidates with yours in the same table and with the same intervals. If it wins by a margin the interval cannot explain, it earned its place. If not, the simpler system is easier to debug and cheaper to run.
The other name often met in this area is AutoGen, a framework for multi-agent conversations (Wu et al., 2023). Its repository now says it is archived and no longer actively maintained by Microsoft, and points new users to Microsoft Agent Framework, so treat it as history. The design question it raises is still current: should a pipeline builder be one agent with tools, as here, or several agents, such as a proposer, a runner and a critic? The agent design chapter's advice applies: start with one agent and add structure only when a measured failure shows that one cannot cope. Here the proposer and the runner share one search state, so one agent is simpler.
| Decision | Chosen here | Alternative | Trade-off |
|---|---|---|---|
| Search | Six proposals, then an agent loop | Grid or random search | Cheap and readable; a grid would cover all 168 at a cost of at most about 3,400 calls |
Where the design stops working
Every choice above has a boundary. The cache assumes that the same request gives the same answer, which holds here because the temperature is 0. At a higher temperature the key would have to include a sample number, or the cache would hide the variation that a repeat should show. The exact-match score assumes one right label per message. A message that mixes a leak with a billing question has two, and the score would punish a reasonable answer. The leave-one-out rule assumes the examples are independent. If two messages are near copies, one still leaks the other, and the rule only removes the message itself.
Cost has a boundary too. A search that spends 130 calls on a small set is cheap. The same search over 2,000 examples and 20 candidates would be 40,000 calls, and the budget in code is what stops a loop from reaching that number by accident. The point of the case is not that the lab's numbers are right for your task. It is that each limit above is a line of code you can read, test and change.
Review prompts
Review prompts, to answer on paper first:
- Ten times more labelled data. What changes in the intervals and in the winner's curse? The intervals narrow roughly as the square root of the sample, so 200 examples would cut the interval to about a third of its width, which still would not reliably separate candidates a point apart. The bias from picking the best of six also shrinks.
- Drift. The residents start writing in a new way. Keep new messages with their labels, re-run the search on a schedule, and compare the new score with the old one on the same split.
- A task that needs more than a label. Extraction of fields needs a scorer for each field, and a field that is allowed to be missing needs a rule. The loop and the budget stay the same.
- A cheaper model. Run the search again for the cheaper model. A configuration that is best for one model is not best for another.
An optimiser library reports a better pipeline than yours. What do you check before switching?
- Run both on the same split and metric, compare the scores with their intervals, and count the model calls each one needed. A win the interval cannot explain, at a similar cost, is worth taking.
When would you add a second agent to this system?
- When a measured failure shows one agent cannot cope: a context too large, parts that can run in parallel, or a need for an independent check. A proposer and a runner that share one search state do not need to be separate agents.
All chapters · Previous: Case study: a smart parking agent system