Sub topic 7
Getting predictable output formats
This chapter assumes you can read short Python snippets, know basic JSON, and have written a few prompts that state a task and constraints. Here you will learn how to make a model's replies consistent enough for a program to read them.
Why format matters
In a chat window, a reply that is slightly different each time is fine, because a person reads it. When code reads the reply, small differences cause failures. Consider a prompt that asks for a sentiment label. The model might answer in any of these ways:
positivePositive.The sentiment is positive.Sure! Here is the answer: positive
A person understands all four. A line like if reply == "positive" matches only the first. Predictable output means you decide the shape of the reply in advance. Then you check that the reply has that shape before you use it.
Two separate jobs are involved:
- Request the format in the prompt, so most replies already match.
- Validate the reply in code, so the rest are caught instead of silently passing through.
The prompt makes the right format likely. It does not guarantee it. Treat the model's reply as untrusted input, like data from a web form.
Ways to request a format
Describe the format in words
The simplest method is to state the format in the output specification part of the prompt. Be specific about what appears, what does not, and the allowed values.
Classify the sentiment of the review below.
Output rules:
- Reply with exactly one word: positive, negative, or neutral.
- Use lowercase.
- Do not add punctuation or explanation.
Review:
"""
{review_text}
"""Each rule closes a gap that models commonly fill on their own. "Do not add explanation" removes the chatty lead-in. "Use lowercase" removes Positive. Listing the allowed values removes inventions such as mixed.
If a value can be missing, say what to write in that case. The ticket-summary prompt in this tutorial's examples does this with "Cause unknown". Without such a rule, the model tends to guess, and a guess in a required field looks the same as a real answer.
Ask for JSON with named fields
When you need more than one value, ask for JSON. Name every key, give its type, and say what to do when information is absent.
Extract the following from the support ticket and reply with a single JSON object.
Keys:
- "sentiment": one of "positive", "negative", "neutral"
- "product": string, or null if no product is named
- "urgent": true or false
Reply with the JSON object only. No text before or after it.
Ticket:
"""
{ticket_text}
"""Three details make this work better:
- Fixed key names. If you do not name the keys, the model chooses them, and the names change between calls.
- Explicit null. Saying "or null" gives the model a legal way to say "not stated". Without it, the model may invent a product name to fill the field.
- "Only the JSON object". This reduces, but does not remove, the habit of wrapping the answer in a sentence or a Markdown code fence.
Show the format with an example
Describing a format and showing it are different. A sample output is often the clearest specification. This connects to few-shot prompting: each example ends with an output in exactly the shape you want.
Extract the sentiment and product from each ticket. Reply with JSON only.
Ticket: "My Model X router drops the connection every hour."
Output: {"sentiment": "negative", "product": "Model X router"}
Ticket: "Thanks, the issue is fixed."
Output: {"sentiment": "positive", "product": null}
Ticket: "{ticket_text}"
Output:The last line ends with Output: and nothing else. This cues the model to continue with the same kind of text as the examples. Keep your examples consistent. If one example uses null and another uses the word none, the model may use either.
Use platform features when they exist
Many model APIs offer a JSON mode or a way to supply a schema, which constrains the model so that the output parses. These features reduce syntax errors a lot. Check what your provider supports. Two limits remain:
- A reply can parse and still be wrong. A valid JSON object can carry the wrong label or a made-up value.
- Constraints can force a well-formed answer even when the model should have said it does not know. Keep an explicit "unknown" or
nulloption in your schema.
So the validation code in the next section is still needed, even with these features.
Validate in code
A format request is a request. Your program should check the reply and decide what to do when it fails. This chapter's example validator does two checks: the reply must parse as JSON, and the sentiment value must be in an allowed set.
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 text is not JSON.
Notice the order of checks. json.loads can raise an error, so it sits in a try block. The isinstance check matters because valid JSON can be a list, a number, or a string, and calling .get on those would crash. The in ALLOWED check catches values like "Positive" or "mixed". A real validator should also check types and required keys for every field you asked for.
Common formatting failures
| Failure | Example reply | Typical fix |
|---|---|---|
| Text around the JSON | `Here is the result: {...}` | Say "JSON only", and extract the object in code |
| Markdown code fence around JSON | A fenced block with `json` on its first line | Strip the fence before parsing |
| Wrong key names | `"label"` instead of `"sentiment"` | Name keys in the prompt, add an example |
| Value outside the allowed set | `"mixed"` | List allowed values, add an "unknown" option |
| Trailing comma or single quotes | `{'sentiment': 'positive',}` | Retry, or use a schema-constrained mode |
| Truncated reply | JSON cut off mid-string | Raise the output length limit, shorten the output |
| Invented value for missing data | A made-up product name | Allow `null` and say when to use it |
Truncation deserves attention. Most APIs cap the reply length. If the cap is reached in the middle of a JSON object, the result will not parse. Long lists and long explanatory fields are the usual cause.
Tolerate harmless noise
Some noise is safe to remove. The most common is a Markdown fence around the JSON, or a sentence before the object. A small helper handles both cases.
def extract_json(reply):
text = reply.strip()
fence = "`" * 3
if text.startswith(fence):
lines = text.splitlines()[1:]
if lines and lines[-1].strip() == fence:
lines = lines[:-1]
text = "\n".join(lines).strip()
start = text.find("{")
end = text.rfind("}")
if start != -1 and end > start:
return text[start:end + 1]
return textThis drops a surrounding fence and then takes everything from the first { to the last }. It is a heuristic. If the model writes two separate objects, or puts braces inside prose after the object, the result will be wrong. In that case json.loads will fail and the validator will reject it. That is the intended behavior, because it is better to reject than to guess.
Retry with feedback
When validation fails, a common response is to call the model again. Appending a short correction to the prompt often helps. Cap the number of attempts so a persistent failure cannot loop forever.
def classify(call_model, prompt, retries=2):
for _ in range(retries + 1):
reply = call_model(prompt)
data = parse_reply(extract_json(reply))
if data is not None:
return data
prompt = (
prompt
+ "\n\nYour previous reply was not valid. "
+ 'Reply with only a JSON object like {"sentiment": "positive"}.'
)
return None
replies = iter([
"Sure! The sentiment is positive.",
'{"sentiment": "positive"}',
])
fake_model = lambda prompt: next(replies)
print(classify(fake_model, "Classify: I love it."))The fake model fails on the first call and succeeds on the second, so this prints {'sentiment': 'positive'}. After the final failed attempt the function returns None. The caller must handle that case. Common choices are to log the input for review, route it to a person, or use a safe default.
The overall flow looks like this:
Choosing a format
JSON is not always the best choice. Pick the simplest format your program can read.
| Format | Good for | Watch out for |
|---|---|---|
| A single label or word | Classification into a small set | Extra words, capitalization |
| JSON | Several fields, nested data | Syntax errors, missing keys |
| A list with a fixed marker per line | Short lists a person also reads | Models adding numbering or extra lines |
| Delimited text (for example CSV) | Flat tables | Commas inside values |
| Free text with required sections | Human-facing reports | Hard to parse, sections may be reordered |
For a single label, ask for the bare word instead of a JSON object. There is less to get wrong. For output that a person reads, such as a summary, fixed section headings and a length limit (for example "at most 3 bullet points") give structure without needing a parser.
Order of fields and reasoning
If you also want the model to reason step by step, field order matters. The model writes its reply from start to end, so a field written first cannot depend on reasoning that comes after it. For tasks where the answer benefits from reasoning, ask for a "reasoning" field first and the "answer" field last. Your code then ignores the reasoning, or logs it for debugging.
Reply with a JSON object with these keys, in this order:
- "reasoning": two or three sentences explaining your decision
- "sentiment": one of "positive", "negative", "neutral"Do not rely on key order inside the JSON when you parse it. JSON objects are read by key name, so order does not affect your code. The order only affects what the model writes first.
Checking that your format prompt works
A format prompt is a prompt like any other, so test it on a set of cases. Measure two things separately: how often the reply is valid, and how often the valid reply is correct. A prompt can be 100% valid and still wrong half the time, or the reverse. The evaluation function from the testing chapter's approach can be adapted to count valid replies:
def valid_rate(call_model, build_prompt, inputs):
valid = 0
for text in inputs:
reply = call_model(build_prompt(text))
if parse_reply(extract_json(reply)) is not None:
valid += 1
return valid / len(inputs)Include awkward inputs in your test set: empty text, very long text, text in another language, and text that contains instructions or JSON of its own. These are the cases where format failures show up first.
Edge cases to plan for
- Input that looks like output. If the ticket text contains a JSON object or the word "Output:", the model may copy it. Put the input inside delimiters and tell the model that the content between them is data.
- Empty or irrelevant input. Decide what the correct reply is, for example
{"sentiment": "neutral"}ornull, and state it in the prompt. Otherwise the model improvises. - Free-text fields. A string field can hold quotes and newlines. These must be escaped in valid JSON, and models sometimes forget. Keep free-text fields short, or avoid them if you can.
- Numbers and booleans. The model may return
"true"(a string) instead oftrue. Check the type in the validator. - Format drift across model versions. A prompt that worked reliably can change behavior after a model update. Keep your test cases and rerun them.
Summary of the method
- Choose the simplest format your code can read.
- State the format in the prompt: keys, allowed values, and what to write when data is missing.
- Add one or two examples that show the exact output shape.
- Parse and validate every reply. Reject anything that fails.
- Retry a limited number of times, then use a defined fallback.
- Measure the valid-reply rate and the accuracy on a test set whenever you change the prompt.
Exercise
A prompt asks for JSON with the keys "sentiment" and "product". A reply arrives as: {"sentiment": "Positive", "product": "Model X"}. Using the parse_reply function from this chapter, what is returned, and what two changes would you make so this reply is handled correctly?
Show answer
parse_reply returns None, because "Positive" (capital P) is not in the ALLOWED set. Two possible changes: in the prompt, state that values must be lowercase and list the allowed values; in the code, normalize the value before checking (for example, lowercase and strip it). Normalizing in code is safe for this harmless difference, but values that are truly outside the set should still be rejected.
Exercise
Why should a schema for extracted data allow null for a field like "product", and what can go wrong if it does not?
Show answer
Some inputs do not contain the information. If null is not allowed, the model has no legal way to say "not stated" and may invent a plausible value. The invented value passes validation because it has the right type, so the error goes unnoticed in later steps.
Exercise
Your classify function returns None after all retries for some inputs. Name two reasonable ways the calling code can handle this, and one reason not to simply raise the retry limit to a large number.
Show answer
The caller can log the input and route it to a person for review, or return a safe default value that is clearly marked as unclassified. A large retry limit adds cost and delay, and if the failure comes from the prompt or the input, every retry is likely to fail in the same way.