Sub topic 9
Code generation and review helpers
This chapter assumes you can write Python, read JSON, and have used a model API through a complete(prompt) function like the one in the classification chapter. Code assistance applies the text-task and prompting patterns to source code, so the same working model holds: the model predicts likely text, and your program must check what comes back.
What code helpers do
Most code features fall into a few patterns:
- Generation: write a function from a description or a signature plus docstring.
- Review: read a diff and point out bugs, risks, or style problems.
- Explanation: describe what unfamiliar code does.
- Transformation: convert between languages, add types, write tests, or refactor.
Code is a good fit because it is plentiful in training data and has a built-in checker: you can run it. That makes code one of the few outputs you can verify automatically.
The generate, check, retry loop
Never trust generated code because it looks right. Models produce plausible code that may call functions that do not exist, miss edge cases, or solve a slightly different problem. Run the output against tests, and feed failures back.
Example: a generate-and-test helper
The function below asks for code, extracts it from the reply, runs it with a test, and retries with the error message. It uses exec, which is unsafe on untrusted output. Run it only in a sandbox in real systems.
import re
def extract_code(reply: str) -> str:
match = re.search(r"```(?:python)?\n(.*?)```", reply, re.DOTALL)
return match.group(1) if match else reply
def generate_function(task: str, test, complete, attempts: int = 3) -> str:
prompt = (
"Write a Python function for this task. "
"Reply with one code block and nothing else.\n\nTask: " + task
)
for _ in range(attempts):
code = extract_code(complete(prompt))
namespace = {}
try:
exec(code, namespace)
test(namespace)
return code
except Exception as err:
prompt += f"\n\nYour previous code failed with: {err!r}\nFix it."
raise RuntimeError("no passing code after retries")
def fake_complete(prompt):
return "```python\ndef add(a, b):\n return a + b\n```"
def test_add(ns):
assert ns["add"](2, 3) == 5
print(generate_function("add two numbers", test_add, fake_complete))Review helpers
For review, give the model the diff, not the whole repository, and ask for a fixed format so you can parse it. Ask for line references and a severity per finding. Tell it to report nothing when the change is fine, or it will invent issues to fill the space.
Common errors
| Problem | Cause | Mitigation |
|---|---|---|
| Invented functions or packages | The model pattern-matches names | Run the code; check imports resolve |
| Outdated API usage | Training data is older than the library | Put current docs in the prompt |
| Passing tests that are wrong | The model wrote both code and tests | Write or review tests yourself |
| Insecure code | Common examples are insecure | Run linters and security scanners |
| Missing context | Prompt lacks surrounding files | Include related signatures and types |
Exercise
In the generate-and-test helper, why is it risky to ask the model to write both the function and the test that checks it?
Show answer
A wrong understanding of the task can appear in both, so the test passes while the code is still wrong. The test should come from you or be reviewed by you, because it is the independent check on the output.
Exercise
A review helper keeps reporting problems on clean diffs. Name two prompt changes that reduce this.
Show answer
Tell the model explicitly to return an empty list when it finds no real problems, and require each finding to cite a specific line and severity. Both limit the model's tendency to produce findings it cannot support.