Exercises — Code-generation agents
Before we start, one reused tool, stated from zero so nobody is stuck:

Level 1 — Recognition
Exercise 1.1 (L1)
Which single property most sharply separates a code-generation agent from a plain code-completion model?
Recall Solution
The feedback loop with the environment. A completion model does one-shot generation (predict the next tokens, done). An agent runs its code, reads outputs and errors, and feeds that back in — the sense–decide–act loop from Tool use in AI systems. Everything else (bigger model, more tokens) is a difference of degree; the loop is a difference of kind.
Exercise 1.2 (L1)
Match each of the four agent components to its one-line job: Task understanding, Code synthesis, Execution & verification, Iterative refinement.
Recall Solution
- Task understanding ::: turn natural-language requirements into structured goals.
- Code synthesis ::: produce syntactically and semantically correct code.
- Execution & verification ::: run code in a sandbox, capture outputs and errors.
- Iterative refinement ::: debug failures, adapt to feedback, converge to a working solution.
Exercise 1.3 (L1)
The agent keeps a memory of everything it has tried, called the execution history and written — a growing list where each row is one triple : the action it took, the output it saw, and the error it hit at step . At the next step this memory grows by one row, following the state-update rule where (say "union") just means "add this new row to the set we already had." Name what each of the three stored things inside a row is.
Recall Solution
- ::: the execution history at step — the full list of past rows; it is the agent's memory.
- ::: the action the LM produced at step (usually a code snippet or edit).
- ::: the output the sandbox printed (stdout).
- ::: the error trace, if any (stderr / exception). Together the three form one row of — "what I tried and what happened."
Level 2 — Application
Exercise 2.1 (L2)
A code agent has single-attempt success rate . Compute the probability of solving the task in 3 or fewer attempts.
Recall Solution
Use with , : What it looks like: on the s01 curve, walk along the pale-yellow () line from (its label) up to (its label) — that visible jump is a single agent given three tries.
Exercise 2.2 (L2)
Same agent, but now with . How many attempts are needed so that success probability first reaches at least 95%?
Recall Solution
Solve . We need to pull down from the exponent. A logarithm is exactly the tool for that, and here is why it works as a picture: think of as starting at and shrinking by a factor at each step — a chain of equal-ratio shrinks. Plot those values on a ruler whose tick marks are spaced by multiplication (a "log ruler," like a piano where each octave doubles): equal multiplicative steps become equally-spaced marks. On that ruler, "multiply by , times" turns into "take equal steps," i.e. repeated multiplication becomes repeated addition of step-sizes. The size of one step is and the total distance to travel is , so the number of steps is their ratio: Since must be a whole number of attempts, round up: . Check: . ✓ (And gives , so is the first that works — matching where the yellow curve crosses the dashed line in s01.)
Exercise 2.3 (L2)
For the prime-checker, why does the loop stop at instead of ? Verify the reasoning for .
Recall Solution
If with both and , then — a contradiction. So any factor pair must contain a member ; checking up to can never miss a factor. For : . Factors found by checking : (since ). We catch it immediately, never needing to test — their partners are all .
Exercise 2.4 (L2)
Compute for a task where you drew samples and were correct.
Recall Solution
Meaning: if you randomly grab of your generations, there is a chance at least one is correct.
Level 3 — Analysis
Exercise 3.1 (L3)
An agent ranks files in a codebase against a search query using a hybrid retrieval score. Here stands for a candidate file (its code text) and for the query the user typed (e.g. "find login function"); and are their embedding vectors (numeric summaries of meaning). The score is where BM25 measures keyword overlap between file and query , embedding_sim measures meaning-similarity, and balances the two. Explain, with a concrete example, why a keyword-only search () can miss the right file, and why an embedding-only search can also miss.
Recall Solution
- Keyword-only miss (): query "find login function." The real handler file defines
authenticate_user(). BM25 scores on shared tokens; "login" never appears in , so it ranks low — a synonym gap. - Embedding-only miss: query "call
process_v2" where two files are semantically about "processing." Embeddings judge them nearly equal and may rank the wrong one first; they blur the exact identifier that a keyword match would nail. Combining them (Retrieval-Augmented Generation style) lets exact names and meaning both vote. tunes how loud the semantic voter is.
Exercise 3.2 (L3)
An agent hits IndexError: list index out of range and immediately wraps every list access in a bounds check. The error disappears but the output is silently wrong. Diagnose what really happened and give the correct debugging order.
Recall Solution
The bounds check masked a symptom without fixing the cause. The true bug was almost certainly an off-by-one or a wrong loop bound producing a bad index; by clamping the access, the agent now reads/writes the wrong element instead of crashing — worse, because it fails silently. Correct order (from the parent's error-recovery section):
- Print the list length and the offending index.
- Inspect the loop's termination condition (
range(...)bounds). - Verify counter initialization.
- Only then, add a defensive check if the logic genuinely needs one. This is reasoning about data flow, not pattern-matching the error keyword.
Exercise 3.3 (L3)
Two agents solve the same benchmark. Agent A: per attempt, allowed attempts. Agent B: per attempt, allowed attempts. Which has the higher chance of eventually succeeding? Compute both.
Recall Solution
- Agent A: .
- Agent B: . Agent A wins (97.2% vs 90.9%), despite a much weaker single attempt. The lesson: iteration budget compounds — a mediocre agent that gets many tries can beat a strong agent that gets few. This is exactly why the loop matters.
Level 4 — Synthesis
Exercise 4.1 (L4)
Design a test-first agent workflow for the task "write clamp(x, lo, hi) that returns x bounded into [lo, hi]." Write the tests the agent should generate (covering edge cases), then the implementation, and state which case each test defends.
Recall Solution
Step 1 — tests (formalize the spec, expose edge cases):
assert clamp(5, 0, 10) == 5 # inside range -> unchanged
assert clamp(-3, 0, 10) == 0 # below lo -> snaps to lo
assert clamp(42, 0, 10) == 10 # above hi -> snaps to hi
assert clamp(0, 0, 10) == 0 # on the lower boundary
assert clamp(10, 0, 10) == 10 # on the upper boundary
assert clamp(5, 5, 5) == 5 # degenerate lo == hiStep 2 — implementation:
def clamp(x, lo, hi):
if x < lo:
return lo
if x > hi:
return hi
return xStep 3 — case coverage: the six tests defend, in order: interior value, below-range, above-range, lower boundary (inclusive), upper boundary (inclusive), and the degenerate collapse. Boundaries and the degenerate case are exactly where off-by-one and < vs <= bugs live — writing tests first forces the agent to name them before coding, per Automated testing discipline.
Exercise 4.2 (L4)
Sketch (in words + a small mermaid diagram) a multi-agent pipeline for building a small REST endpoint, and justify one place where parallelism is safe and one place where it is not.
Recall Solution
flowchart LR
A["Architect agent"] -->|plan| B["Implementation agent 1"]
A -->|plan| C["Implementation agent 2"]
B -->|code| D["Testing agent"]
C -->|code| D
D -->|results| E["Review agent"]
E -->|approve or revise| A
- Safe parallelism: two implementation agents writing independent modules (e.g., a data model file and a route handler file) can run at once — they touch disjoint files in the shared workspace.
- Unsafe parallelism: the architect deciding the shared interface (function signatures both modules import). If two agents each invent the signature in parallel, they diverge and the code will not link. This must be a serial, single-source-of-truth step before fan-out.
Level 5 — Mastery
Exercise 5.1 (L5)
An agent samples code independently at per attempt, but each failed attempt costs compute unit and each success ends the loop. You have a hard budget of attempts. (a) What is the probability of success within budget? (b) What is the expected number of attempts consumed (counting the successful one, and counting all if it never succeeds)?
Recall Solution
(a)
(b) Let . First, why the summation looks the way it does. An expectation is "each possible value of , weighted by how likely that value is, all added up" — a weighted average. So we list every outcome, its probability, and its cost, then sum probability × cost.
- The loop reaches attempt only if the first attempts all failed (probability ) and then attempt succeeds (probability ). That outcome consumes exactly attempts. So its contribution is . This is a truncated geometric distribution — "geometric" because each extra failure multiplies in another factor ; "truncated" because we cut it off at the budget .
- The one leftover outcome is "never succeeded in tries," probability , which still consumes all attempts — contributing . Adding the success-outcomes plus the never-succeed outcome gives the whole distribution: Term by term with :
- :
- :
- :
- :
- never: Interpretation: even with a 4-attempt cap, you expect to spend only ~2.18 attempts, because most runs finish early. This is the compute-cost side of the iteration story: high success and modest average cost.
Exercise 5.2 (L5)
You can generate samples for a task, of which turn out correct. Compare , , and , and explain the shape of the trend.
Recall Solution
With , non-correct pool :
- .
- .
- . Trend: — rising and concave (each extra pick adds less than the previous, because it gets harder to draw an all-wrong subset once the pool of wrong ones is small). This mirrors the diminishing-returns curve on figure s01: the first extra try buys the most.

The bars above show the 5.2 result: notice the shrinking gaps between — concavity you can see.
Recall Self-check: could you re-derive these from scratch?
One-attempt-vs-k relationship ::: , because all-fail is and success is its complement. Why bounds the prime loop ::: any factor pair has a member , else the product exceeds . Why pass@k uses combinations not powers ::: it draws from a fixed pool of samples without replacement.
Parent: Code-generation agents · related tools: Program synthesis, Prompt engineering.