Sub topic 7
Getting predictable output formats
This chapter assumes you can write a clear instruction, use delimiters to separate input from instructions, and read short Python snippets. You should also know basic JSON. The goal is to get replies that code can read without manual cleanup.
Why format matters
A person can read a friendly paragraph. A program cannot. If your code expects positive and the model replies Sure! I'd say the review is positive., the program breaks. Output format is part of the prompt's output specification, and you have to state it.
Three levers help, and they work best together:
- Describe the format in words.
- Show the format with an example.
- Check the reply in code.
Describe the format explicitly
Name the format, the fields, and the allowed values. Also say what to leave out.
Classify the review below as positive, negative, or neutral.
Reply with only a JSON object in this form:
{"sentiment": "<positive|negative|neutral>"}
Do not add any text before or after the JSON.
Review:
"""
Setup was confusing but support helped.
"""This prompt gives the exact keys, lists the allowed values, and bans extra text. Each of these removes a way for the reply to vary.
Show the format with examples
Few-shot examples, covered in the previous chapter, double as format examples. The model copies the shape of what it sees. If every example ends with a bare label, the reply is likely to be a bare label.
Keep examples consistent. If one example uses Positive and another uses positive, you invite both. The same applies to spacing, quotes, and key order.
Pick a format that fits the job
| Format | Good for | Risk |
|---|---|---|
| Single label | Classification | Model adds explanation |
| JSON | Several fields, nested data | Invalid syntax, wrong keys |
| Bulleted list | Summaries for people | Count and length drift |
| Table | Comparing items | Misaligned columns |
Use the simplest format that carries the data. A single label is easier to get right than a JSON object with six fields.
Validate in code
A prompt reduces format errors but does not remove them. The model might wrap JSON in a sentence, add a markdown fence, or invent a label. Treat the reply as untrusted input and check it.
import json
ALLOWED = {"positive", "negative", "neutral"}
def parse_reply(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or data.get("sentiment") not in ALLOWED:
return None
return data
print(parse_reply('{"sentiment": "positive"}'))
print(parse_reply('Sure! Here is the answer: positive'))The first call returns the dictionary. The second returns None, because the reply is not JSON. The function checks two things: that the text parses, and that the value is an allowed label. Parsing alone is not enough, since {"sentiment": "great"} is valid JSON with a bad value.
Handle failures
When parse_reply returns None, you have a few options:
- Retry the same prompt. This often works, but only if sampling gives a different reply.
- Retry with a repair message that quotes the bad reply and restates the format rule.
- Fall back to a default or send the item to a person.
Cap the number of retries. An unbounded loop turns one bad reply into a cost problem.
Common errors
- Extra prose around the data. Fix by saying "only" and "no text before or after," then strip known wrappers such as a markdown fence before parsing.
- Values outside the label set. List the allowed values in the prompt and check them in code.
- Missing fields. Name every required key. Validate that each is present.
- Unstated "unknown" case. If the input may not contain the answer, give the model a permitted value such as
"unknown"ornull. Without one, it may guess. - Format drift across inputs. A prompt that works on three test inputs may fail on the fiftieth. Test on varied inputs, including odd ones.
Summary of the approach
State the format and the allowed values. Show it with consistent examples. Parse and validate every reply. Decide in advance what happens when validation fails.
Exercise
A prompt asks for {"sentiment": "<positive|negative|neutral>"}. The model replies {"sentiment": "mixed"}. Does json.loads raise an error, and does parse_reply accept the reply? What should your code do next?
Show answer
json.loads does not raise an error, because the reply is valid JSON. parse_reply rejects it and returns None, because "mixed" is not in ALLOWED. The code should follow its failure plan: retry a limited number of times, possibly with a repair message restating the allowed values, then fall back to a default or manual review.
Exercise
Your prompt asks for a summary in JSON, but some tickets contain no stated cause. Describe one change to the prompt and one change to the validation code that handle this case.
Show answer
In the prompt, allow an explicit value such as "Cause unknown" or null for the cause field, so the model is not pushed to guess. In the validation code, accept that value as valid for the field, and still reject replies with missing keys or invalid JSON.