Sub topic 5
Specify the output format
This chapter assumes you have called an LLM chat API, can read JSON, and can read basic Python. It also assumes you know what a system prompt is and how to state a task and rules.
Why the format needs its own section
Your application code reads the model's reply. A person can tolerate "Sure! Here's the answer:" before the content, but a JSON parser cannot. If the format is vague, the model chooses one, and it may choose differently on the next call. Most output bugs come from this gap between what the prompt left open and what the code expects.
Treat the output format as a contract with three parts:
- The shape: JSON object, bullet list, a single label, or prose.
- The fields: names, types, and what each one means.
- The boundaries: what must never appear outside that shape.
Describe the format precisely
Put the format under its own heading, close to the end of the prompt. Name every field and its type, and say what to do when a value is missing.
# Output
Reply with one JSON object: {"answer": string, "sources": [integer]}.
"sources" lists the indexes of the documents you used. Output no text outside the JSON.Three details make this work:
- The type of each field is stated (
string,[integer]). - The meaning of
sourcesis stated, so the model does not guess whether it holds titles or indexes. - The last sentence forbids text outside the JSON. This blocks preambles such as "Here is the JSON:" and closing remarks.
Also decide what an empty result looks like. For example: "If no document was used, return an empty list for sources." Without that line, the model might omit the field or write null.
Choose a format for the consumer
| Consumer | Good format | Reason |
|---|---|---|
| Your code | JSON with fixed keys | Easy to parse and validate |
| A classifier step | One label from a fixed list | Easy to compare and count |
| A person reading a UI | Short prose or Markdown | Readable without processing |
| Another prompt | Tagged sections | Easy to split and reuse |
If your provider offers structured output or JSON mode, use it as well. These features constrain the syntax but not the meaning, so the prompt still has to say which fields exist and what they hold.
Validate every reply
Even a clear prompt produces an occasional bad reply. Check the output in code before using it.
import json
def check_reply(raw: str) -> list[str]:
"""Return a list of problems found in a model reply; empty means it passed."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return ["reply is not valid JSON"]
if not isinstance(data, dict):
return ["reply is not a JSON object"]
problems = []
if not isinstance(data.get("answer"), str):
problems.append("'answer' must be a string")
sources = data.get("sources")
if not isinstance(sources, list) or not all(isinstance(s, int) for s in sources):
problems.append("'sources' must be a list of integers")
return problems
print(check_reply('{"answer": "Your invoice is due on 5 May.", "sources": [1]}'))
print(check_reply('Here is the JSON: {"answer": "Due 5 May.", "sources": [1]}'))
print(check_reply('{"answer": "Due 5 May.", "sources": ["1"]}'))The first call returns an empty list. The second returns the "not valid JSON" problem, because of the preamble. The third reports that sources must be a list of integers, because "1" is a string.
The same function works in production and in your prompt tests, which a later chapter covers.
Common mistakes
- Describing the format only in prose, such as "answer in JSON", without field names or types.
- Asking for JSON while also asking for a friendly greeting. The two instructions conflict.
- Letting the model add commentary, then writing a regex to strip it. State the boundary in the prompt and validate the result.
- Changing the format in the prompt without updating the validator, or the reverse.
Exercise
Your prompt says "Return JSON with the customer's sentiment." Replies sometimes say "positive", sometimes "Positive sentiment", and sometimes include a paragraph. Rewrite the output instruction so that your code can count results reliably.
Show answer
Fix the shape, the allowed values, and the boundary. For example: "Reply with one JSON object: {"sentiment": "positive" | "neutral" | "negative"}. Use exactly one of these three lowercase values. Output no text outside the JSON." Then validate in code that the value is in the allowed set.