Sub topic 9
Code generation and review helpers
This chapter assumes you have read the chapters on prompting and on structured output, and that you can write basic Python and run it from a terminal. It covers coding helpers built on a language model. These are tools that write, explain, review, and modify source code.
Why code is a good fit
Code is text with strict rules, and a huge amount of it is public. Models have seen many examples of common languages, libraries, and idioms, so they write plausible code quickly.
Code also has a property most text lacks. You can check it mechanically. A parser tells you whether it is valid, a test suite tells you whether it behaves correctly, and a linter or type checker finds a further class of mistakes. A code helper built around these checks is far more reliable than the model alone.
Kinds of code helpers
| Helper | Input | Output | Main risk |
|---|---|---|---|
| Completion | Code before and after the cursor | A few lines or a function body | Plausible but wrong logic |
| Generation from a spec | A description and an interface | A new function or module | Invented APIs, missed edge cases |
| Explanation | A snippet or file | Plain-language summary | Confident misreading of unusual code |
| Review | A diff plus context | Comments on bugs and style | Noise and false alarms |
| Test writing | A function and its spec | Test cases | Tests that copy the code's bugs |
| Refactoring or migration | Old code and a target | Rewritten code | Silent behavior changes |
Explanation and review are the safest to start with, because the output is advice that a human reads. Generation and migration are riskier, because their output may run.
The generate-and-verify loop
The most useful design pattern is a loop. The model proposes code, your program checks it, and failures go back to the model as feedback. You stop when checks pass or when you reach an attempt limit.
Two points about this design matter. The tests come from you, not from the model, so the model cannot grade its own work. And a pass sends the code to human review. It does not send it straight to production.
Implementing the loop
The first function checks a candidate. It parses the code, writes it and the tests to a temporary directory, and runs the tests in a separate process with a time limit.
import ast
import re
import subprocess
import sys
import tempfile
from pathlib import Path
FENCE = "`" * 3
CODE_BLOCK = re.compile(re.escape(FENCE) + r"(?:python)?\n(.*?)" + re.escape(FENCE), re.DOTALL)
def extract_code(reply: str) -> str:
match = CODE_BLOCK.search(reply)
return match.group(1) if match else reply
def check_generated(code: str, tests: str, timeout: int = 10) -> tuple[bool, str]:
try:
ast.parse(code)
except SyntaxError as exc:
return False, f"Syntax error: {exc}"
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, "solution.py").write_text(code)
Path(tmp, "test_solution.py").write_text(tests)
try:
result = subprocess.run(
[sys.executable, "test_solution.py"],
cwd=tmp, capture_output=True, text=True, timeout=timeout,
)
except subprocess.TimeoutExpired:
return False, "Tests timed out"
return result.returncode == 0, result.stdout + result.stderr
def generate_with_repair(spec: str, tests: str, complete, max_attempts: int = 3) -> str:
prompt = (
"Write a Python module named solution.py that satisfies this spec.\n"
"Reply with one code block and nothing else.\n\nSpec: " + spec
)
for _ in range(max_attempts):
code = extract_code(complete(prompt))
ok, report = check_generated(code, tests)
if ok:
return code
prompt += "\n\nYour previous attempt failed:\n" + report + "\nFix it."
raise RuntimeError("No passing solution after %d attempts" % max_attempts)
SOLUTION = (
"import re\n\n"
"def slugify(text):\n"
" return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')\n"
)
TESTS = (
"from solution import slugify\n"
"assert slugify('Hello, World!') == 'hello-world'\n"
"assert slugify(' a b ') == 'a-b'\n"
)
def fake_complete(prompt: str) -> str:
# Stands in for a real model API call.
return "Here you go:\n" + FENCE + "python\n" + SOLUTION + FENCE
print(generate_with_repair("slugify(text) returns a URL slug", TESTS, fake_complete))Replace fake_complete with a function that calls your model API. Each failed attempt appends the report to the prompt, so the model sees what went wrong.
The attempt limit is not optional. Without it, a bad spec or an impossible test makes the loop run forever and spend money on every pass.
Review helpers
A review helper reads a diff and returns comments. The loose text a model writes is hard to attach to lines in a pull request. Ask for JSON instead, then validate it the same way you validate any structured output. The check below also discards comments that point at lines outside the diff, which is a common failure.
import json
SEVERITIES = {"info", "warning", "error"}
def parse_review(raw: str, max_line: int) -> list[dict]:
findings = json.loads(raw)
if not isinstance(findings, list):
raise ValueError("review must be a JSON list")
valid = []
for item in findings:
if (
isinstance(item, dict)
and isinstance(item.get("line"), int)
and 1 <= item["line"] <= max_line
and item.get("severity") in SEVERITIES
and isinstance(item.get("comment"), str)
):
valid.append(item)
return valid
raw = (
'[{"line": 3, "severity": "error", "comment": "Division by zero when count is 0"},'
' {"line": 99, "severity": "info", "comment": "Refers to a line that does not exist"}]'
)
print(parse_review(raw, max_line=20))Good review prompts share a few habits:
- Give the model the changed lines and the surrounding code, not just the diff.
- State what to look for: bugs, missing error handling, security issues. Say what to ignore, such as formatting that a linter already covers.
- Ask for a confidence or severity level so you can filter low-value comments.
- Tell the model to return an empty list when it finds nothing. Models asked for feedback tend to invent some.
What goes wrong
- Invented APIs. The model calls a method or imports a package that does not exist. Attackers can register such package names, so install only dependencies you recognize. Running the code catches the failed import.
- Outdated knowledge. The model may write code for an old version of a library. Put the version in the prompt and include relevant documentation excerpts.
- Tests that mirror bugs. If the model writes both the code and its tests, the tests often assert the code's actual behavior, including its mistakes. Write tests from the spec, or review model-written tests as carefully as the code.
- Missing context. The model cannot see your repository unless you show it. Include function signatures, types, and house conventions. Retrieval over your codebase, covered in the retrieval chapters, helps when the code is too large to paste.
- Silent behavior changes in refactors. Before a refactor, make sure tests exist that cover the current behavior, then run them afterward.
- Review fatigue. A helper that posts ten weak comments per pull request trains people to ignore it. Measure how often developers act on its comments, and tune the prompt toward precision.
Exercise
A team's helper asks the model to write a function and then asks the same model to write tests for it. All tests pass on the first try. Why is this weak evidence that the function is correct, and what two changes would make the check stronger?
Show answer
The model writes tests that match what its own code does, so shared misunderstandings and bugs pass unnoticed. Stronger checks: (1) write or review the tests from the spec before generation, so they are independent of the model's code; (2) add checks that do not depend on the model, such as a type checker, a linter, and tests of edge cases like empty input and large values. Running the code in a sandbox with a timeout is also part of the check.
Exercise
A review helper returns a JSON comment attached to line 140, but the diff only covers lines 1 to 60. What should your code do with the comment, and why?
Show answer
Discard it, and optionally log it. A comment on a line outside the diff is evidence the model misread or invented the context. Showing it would reduce trust in the helper, so validation should drop findings whose line numbers are not in range.