Build a Code Explainer
The Goal
A code explainer reads a piece of source code and describes it in plain language, for a reader who is learning. It is useful in training, in code review, and in documentation, and it is a good project because the output has a clear structure that the application can check. An explanation that skips the risks of a piece of code is incomplete in a way the reader may not notice, so the application verifies that every required section is present, and asks again when one is missing.
The project combines three earlier ideas: input validation (Lesson 174), prompting with tagged content (Lesson 37), and a checked response with a bounded retry (Lesson 105). The model is asked for free text, and the application treats the required headings as a contract.
What You Will Build
An explain function that:
- accepts a source file's name and contents,
- rejects inputs that are empty or too large,
- identifies the language from the file extension,
- asks for an explanation with required headings,
- checks the answer for the headings, and asks again, with the missing headings named, up to a limit.
Project Structure
code_explainer/
├── explainer.py # validation, language detection, the check, and the retry loop
└── demo.py # a stand-in client that first forgets a heading, then includes it
Step 1: Validating and Identifying the Input
The explainer accepts only input it can handle. The contents must be non-empty and within a size limit, and the language is taken from the extension. An unknown extension is labeled as plain text rather than guessed, because a wrong language label would mislead the explanation:
"""explainer.py: explain source code with a required structure, checked before it is returned."""
from pathlib import Path
MAX_CHARS = 20_000
REQUIRED_HEADINGS = ["Purpose", "How it works", "Risks"]
LANGUAGES = {".py": "Python", ".js": "JavaScript", ".sql": "SQL", ".java": "Java"}
def language_for(filename: str) -> str:
return LANGUAGES.get(Path(filename).suffix.lower(), "plain text")
def validate(code: str) -> list[str]:
problems = []
if not code.strip():
problems.append("the file is empty")
if len(code) > MAX_CHARS:
problems.append(f"the file has {len(code)} characters; the limit is {MAX_CHARS}")
return problems
Step 2: Asking for the Structure
The prompt names the headings and wraps the code in tags, so the model knows exactly what to produce and what is data. Each retry adds one sentence naming the headings that were missing, which is more useful to the model than repeating the whole request:
def build_prompt(code: str, language: str, missing: list[str] | None = None) -> str:
prompt = (f"Explain this {language} code for a beginner. Use exactly these headings, "
f"in this order: {', '.join(REQUIRED_HEADINGS)}.\n\n<code>\n{code}\n</code>")
if missing:
prompt += f"\n\nYour previous answer lacked these headings: {', '.join(missing)}. Include them."
return prompt
def missing_headings(answer: str) -> list[str]:
return [heading for heading in REQUIRED_HEADINGS if heading not in answer]
Step 3: The Checked Loop
The loop asks, checks, and retries. Each attempt's missing headings are recorded, so the caller can see how the explanation was reached. The loop stops after a fixed number of attempts, and then returns the last answer with its gaps stated, rather than pretending the answer is complete:
def explain(client, filename: str, code: str, attempts: int = 2) -> dict:
problems = validate(code)
if problems:
return {"ok": False, "problems": problems}
language = language_for(filename)
missing: list[str] | None = None
answer = ""
for attempt in range(1, attempts + 1):
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=800,
messages=[{"role": "user", "content": build_prompt(code, language, missing)}],
)
answer = "".join(block.text for block in response.content if block.type == "text")
missing = missing_headings(answer)
if not missing:
return {"ok": True, "language": language, "explanation": answer, "attempts": attempt}
return {"ok": False, "language": language, "explanation": answer,
"attempts": attempts, "missing": missing}
How It Works
- Validation runs before any call, so an empty or oversized file costs nothing.
- The language comes from the extension, and an unknown one becomes plain text.
- Each answer is checked for every heading, using the exact names from the contract.
- A retry names only the missing headings, which keeps the correction short and specific.
- After the last attempt, the answer is returned with its gaps. The caller sees
ok: Falseand the missing list, so the explanation is never presented as complete when it is not.
Step 4: A Demonstration
The stand-in client returns a first answer that omits the risks, and a second answer that includes every heading, which exercises the retry path:
"""demo.py: the explainer, with a stand-in that first omits the Risks heading."""
from types import SimpleNamespace
from explainer import explain
class ForgetfulClient:
def __init__(self):
self.messages = self
self.turn = 0
def create(self, **request):
self.turn += 1
if self.turn == 1:
text = "Purpose: sums two numbers.\n\nHow it works: it adds them."
else:
text = ("Purpose: sums two numbers.\n\nHow it works: it adds them.\n\n"
"Risks: none for this small function.")
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
if __name__ == "__main__":
code = "def add(a, b):\n return a + b\n"
result = explain(ForgetfulClient(), "add.py", code)
print("ok:", result["ok"], "language:", result["language"], "attempts:", result["attempts"])
print(result["explanation"].splitlines()[0])
Output:
ok: True language: Python attempts: 2
Purpose: sums two numbers.
How It Works
- The first answer fails the check, because it has no Risks heading. The loop does not return it.
- The retry prompt names the missing heading, and the stand-in responds with the complete structure.
- The result reports two attempts, so a cost report can see that this explanation required a second call.
- The language is Python, because the file ends in
.py, and the first line of the explanation confirms the answer is the one that passed the check.
Going Live
The stand-in is replaced by the SDK client in the same call, explain(Anthropic(), filename, code). The validation, the language detection, and the checked loop are unchanged.
Testing the Project
The validation and the checks are pure functions, so they are tested as Lesson 181 described. Cases to cover include an empty file, a file over the limit, an unknown extension, an answer with all headings, and an answer missing one. The explanation's accuracy is evaluated separately with a set of reviewed examples (Lesson 110), since a structured answer can still be wrong.