Sub topic 6
Ask for the output shape you need
This chapter assumes you can write a prompt with a goal, context, and constraints (earlier chapters). It also assumes you can read short Python and run a script. The topic here is the last line of the prompt template, Output format. It controls what comes back, and it often decides whether the reply is usable or needs cleanup.
Why the shape of the reply matters
An assistant is trained to be helpful in conversation. Unless told otherwise, it tends to greet you, explain its approach, show code, and add notes about alternatives. That is fine when you read the reply. It is a problem when the reply goes somewhere else: into a file, a script, a code review, or a diff tool.
The shape of the reply is a requirement like any other constraint. It has two parts:
- Content selection: which parts of the answer you want (only code, code plus a short rationale, three options with trade-offs).
- Format: how those parts are written (a unified diff, a JSON object, a single Python file, a Markdown table).
If you leave both unspecified, the assistant guesses. It will guess differently on different days, so any tool that consumes the reply will break unpredictably.
Name the destination first
Start by asking where the reply is going. The answer picks the format.
| Destination | Shape to request | Why |
|---|---|---|
| Pasting into an existing file | Only the changed function | Less to review, no unrelated edits |
| Applying to a repository | A unified diff | `git apply` can check and apply it |
| Saving as a new module | One complete file in one code block | Nothing to stitch together |
| Read by a script | JSON with named keys | A parser can validate it |
| Choosing between designs | A table of options with trade-offs | Easy to compare |
| Learning or review | Code plus a short explanation | You need the reasoning |
The stronger prompt from the earlier slugify example already does this in its final line:
Return only the function, with no explanation.That one sentence selects content (the function) and excludes content (explanation). It is the smallest useful output-format instruction.
Specify the shape precisely
Vague format words such as "clean," "short," or "structured" leave room for interpretation. Replace them with checkable statements.
Weak:
Give me the result in a nice format.Stronger:
Output format: a single Python code block containing the complete function, with type hints and a one-line docstring. No text before or after the code block.Things worth stating when they matter:
- Number of code blocks. "Exactly one code block" lets you extract the code with a simple rule.
- Language tag. "Label the block
python" helps editors and extractors. - Presence of prose. Say "no text outside the code block" or "at most two sentences of explanation after the code."
- Ordering. For example, "first the code, then a list of assumptions."
- Length limits. "Under 40 lines" or "explanation under 80 words."
- Naming. Exact function names, file names, and JSON key names.
Ask for assumptions separately
When a prompt leaves something open, the assistant fills the gap silently. If you still want a code-only reply, you can ask for assumptions in a labeled section, so they stay out of the code:
Task: Write a Python function parse_duration(text: str) -> int that returns seconds.
Constraints: standard library only; accept "1h30m", "45s", "2h".
Output format: one python code block with only the function, then a section titled "Assumptions" with at most three bullet points.You get machine-extractable code and a short list of decisions to confirm, such as how the function treats an empty string.
Common output formats
Only the changed code
For small edits, ask for the changed function and nothing else. This keeps your review small and reduces the chance of silent changes elsewhere. Add "do not change the function signature" when callers depend on it.
A unified diff
For edits across a file, a unified diff shows exactly what changed. A request might read:
Output format: only a unified diff against the file I pasted, with no explanation. Keep unchanged lines as context. Do not reformat code you did not change.You can then check the diff before applying it:
git apply --check assistant.patch && git apply assistant.patchgit apply --check reports whether the patch fits the current files without changing anything. Assistants sometimes produce hunk headers (the @@ -10,6 +10,8 @@ lines) with wrong line counts, especially in long files. When --check fails, paste the error back and ask for a corrected diff, or fall back to asking for the whole changed function.
Structured data such as JSON
When a program will read the reply, request JSON and name the keys:
Task: Review the function below for bugs.
Output format: a JSON object and nothing else, with keys:
"summary" (string, one sentence),
"risk" (one of "low", "medium", "high"),
"files" (array of strings, may be empty).Never trust the reply to match. Parse and validate it, as the next section shows.
A table of options
For decisions, ask for a table with fixed columns: option, benefit, cost, when to choose it. A fixed set of columns forces comparable answers.
Enforce the shape in code
A format request is a request, not a guarantee. If a script depends on the shape, the script should check it and fail loudly. Here is an extractor for the "exactly one code block" rule. It builds the fence characters from a string so the regular expression stays readable:
import re
FENCE = "`" * 3
BLOCK = re.compile(FENCE + r"[\w+-]*\n(.*?)" + FENCE, re.DOTALL)
def extract_code(reply: str) -> str:
blocks = BLOCK.findall(reply)
if len(blocks) != 1:
raise ValueError(f"expected exactly 1 code block, found {len(blocks)}")
return blocks[0]
if __name__ == "__main__":
reply = f"Here you go:\n{FENCE}python\ndef f():\n return 1\n{FENCE}\n"
print(extract_code(reply))This prints the function body without the surrounding chatter. If the assistant returns two blocks, the script raises an error instead of guessing which one you meant.
For JSON, a small validator checks parsing, key presence, types, and allowed values:
import json
REQUIRED = {"summary": str, "risk": str, "files": list}
RISK_LEVELS = {"low", "medium", "high"}
def parse_review(reply: str) -> dict:
data = json.loads(reply)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
for key, kind in REQUIRED.items():
if not isinstance(data.get(key), kind):
raise ValueError(f"missing or wrong type for key: {key}")
if data["risk"] not in RISK_LEVELS:
raise ValueError(f"unexpected risk level: {data['risk']}")
return data
if __name__ == "__main__":
good = '{"summary": "Off-by-one in loop", "risk": "medium", "files": ["app.py"]}'
print(parse_review(good))
try:
parse_review("Sure! Here is the JSON: {}")
except ValueError as exc:
print("rejected:", exc)
except json.JSONDecodeError as exc:
print("rejected: not valid JSON:", exc)The second call fails because the reply starts with prose. In the script above, json.JSONDecodeError is a subclass of ValueError, so the first except clause catches it and prints the generic rejection. That is acceptable here, and it shows the point: prose around JSON is an error, not something to be tolerated silently.
If an assistant often adds prose, you can strengthen the prompt ("the first character of your reply must be {") and still keep the validator. Use both.
The loop between prompt and check
When a check fails, resist fixing the reply by hand. Fix the prompt. Hand edits solve one reply, while a better format line solves every future one, and you can later fold it into a reusable template.
Edge cases and failure modes
- Code fences around code you meant to save. If you pipe a reply straight into a file, a leading fence line breaks the file. Either extract the block as shown above or ask for "raw code with no Markdown fences," and accept that extraction is still the safer path.
- "Only the code" returning partial code. Assistants sometimes abbreviate with comments such as
# rest unchanged. If you need the full file, say "the complete file with no omissions or placeholder comments." - Truncated replies. Long outputs can be cut off at a length limit. Signs include a missing closing brace, an unterminated string, or JSON that fails to parse. Ask for a smaller unit (one function or one file per reply) or request the remaining part by name.
- Explanation that contradicts the code. If you ask for both, read the code, not the explanation. The explanation describes what the assistant intended, and the code is what runs.
- Invented structure. In JSON, the assistant may add extra keys or rename yours. Reject unknown keys in your validator if downstream code is strict.
- Format drift in a long conversation. After many turns, earlier format instructions lose influence. Restate the
Output formatline in each prompt where it matters. - Conflicting instructions. "Return only code" together with "explain your reasoning" forces a guess. Resolve it yourself: choose one, or ask for code followed by a separate explanation section.
Putting it together
The earlier template ends with Output format. Here is a filled-in version for a task that produces a patch you will apply:
Task: Make parse_duration raise ValueError on empty input.
Context: Python 3.10; the function is in durations.py, pasted below.
Constraints: do not change the function signature; do not touch other functions; no new imports.
Examples: parse_duration("") -> raises ValueError; parse_duration("45s") -> 45
Output format: only a unified diff for durations.py, with no text before or after it.Each line narrows the reply. The format line lets you run git apply --check on the result. The constraints keep the diff small. The examples give you a test to run afterward, which the verification chapter covers.
Exercises
Exercise
You plan to pipe the assistant's reply directly into a script that calls json.loads. Write the Output format line you would add to the prompt, and name one check the script should perform in addition to parsing.
Show answer
Example: "Output format: a single JSON object and nothing else, with keys "name" (string) and "tags" (array of strings). The first character of the reply must be { and the last must be }." After json.loads succeeds, the script should validate that the keys exist, have the right types, and have allowed values, and reject the reply with an error otherwise. Checking for extra unknown keys is also acceptable.
Exercise
An assistant returned a unified diff, but git apply --check reports "patch does not apply." Give two reasonable next steps, and say why fixing the reply by hand is the weaker choice.
Show answer
Next steps: paste the exact git error back and ask for a corrected diff against the file as it currently stands (re-pasting the current file if it changed), or ask for only the changed function and edit the file yourself. Hand-fixing hunk headers fixes just this one reply and leaves the prompt unchanged, so the same failure will return. Adjusting the prompt, for example by asking for fewer or smaller hunks or including the current file, helps every later request.