Structured Output
How to get model replies that a program can parse, including JSON schemas, allowed values, null for missing data, and checking every reply in code.
On this page
Structured output means asking a model to reply in a fixed, machine-readable format, usually JSON, instead of in conversational prose. It matters whenever a program reads the reply, for example to fill a database, count categories or call another function, because code cannot cope with a friendly opener, markdown bullets or a field that is named differently each time.
Without it, a script that expects three clean fields per email will fail on the first reply that starts with "Sure, here are the details". The format has to be specified in the prompt, and the program has to check that the model followed it.
Specifying the shape in the prompt
An instruction such as "extract the name, order number and issue" says what to find but not how to write it down, so the model falls back on the usual chat style.
None of this reply is usable by a program. It has a conversational opener, markdown formatting, a # added to the order number, and an issue written as a free sentence that cannot be counted. A prompt for structured output needs to settle five things.
- The format. JSON is the usual choice because every language can parse it.
- The field names and types. For example,
order_idis a string of digits, not a label such as "Order number". - The allowed values for any field you will group or count by.
- What to do when a value is missing. Tell the model to use
nulland not to guess. - That nothing else may appear. The reply must contain no text before or after the JSON.
The template acts like an example of the output, and the rules around it set the limits. The instruction about null matters most. If every field must be filled and the email has no order number, the model tends to produce a plausible-looking number, which is worse than an empty field because nothing marks it as wrong.
Checking every reply in code
A model follows a format well but not perfectly. Over hundreds of calls, some replies will arrive wrapped in a markdown code fence, with a value that is not on your list, or with a field missing. Treat model output the way you treat user input: parse it, validate it, and only then use it.
strip a ```json fence if presentparse as JSON; check every field is presentcheck name: string or nullcheck order_id: digits or nullcheck issue_type: in the allowed listif any check failed: report the errors- checks
check result fence found parse name order_id issue_type - errors
- 0
1A reply for a different email starts with
```json: a markdown code fence, which models sometimes add even when told not to. - checks
check result fence stripped parse ok name order_id issue_type - errors
- 0
2The program expects fences and removes them. The rest parses, and all three fields are present.
- checks
check result fence stripped parse ok name ok order_id issue_type - errors
- 0
3
nameis"Sam Ortiz", which is a string, so the check passes. - checks
check result fence stripped parse ok name ok order_id ok (null) issue_type - errors
- 0
4
order_idisnull. This email had no order number, so that is exactly what the prompt asked for. - checks
check result fence stripped parse ok name ok order_id ok (null) issue_type not allowed - errors
- 1
5
issue_typeis"late delivery". This is close tolatebut is not on the allowed list, so counting by type would put it in a group of its own. - checks
check result fence stripped parse ok name ok order_id ok (null) issue_type not allowed - errors
- 1
- result
- rejected
6There is one error, so the program rejects the reply and records a message that names the problem. It can then retry with that message or set the reply aside for a person, and the bad value never reaches the spreadsheet.
The same checks written as a function return either the clean data or a list of errors, which you can show to a person or send back to the model.
const FIELDS = ["name", "order_id", "issue_type"];
const ISSUE_TYPES = ["damaged", "late", "wrong-item", "other"];
function parseTicket(reply) {
const text = reply.trim().replace(/^```(json)?\s*/, "").replace(/\s*```$/, "");
let data;
try { data = JSON.parse(text); } catch { return { ok: false, errors: ["not valid JSON"] }; }
if (typeof data !== "object" || data === null || Array.isArray(data)) {
return { ok: false, errors: ["expected one JSON object"] };
}
const missing = FIELDS.filter((f) => !(f in data));
if (missing.length) return { ok: false, errors: missing.map((f) => "missing " + f) };
const errors = [];
const { name, order_id: orderId } = data;
if (name !== null && typeof name !== "string") errors.push("name must be a string or null");
if (orderId !== null && !(typeof orderId === "string" && /^[0-9]+$/.test(orderId))) {
errors.push("order_id must be digits or null");
}
if (!ISSUE_TYPES.includes(data.issue_type)) errors.push("issue_type must be one of " + ISSUE_TYPES.join(", "));
return errors.length ? { ok: false, errors } : { ok: true, value: data };
}
const reply = '```json\n{"name": "Sam Ortiz", "order_id": null, "issue_type": "late delivery"}\n```';
console.log(parseTicket(reply)); // { ok: false, errors: [ 'issue_type must be one of ...' ] }import json, re
FIELDS = ["name", "order_id", "issue_type"]
ISSUE_TYPES = ["damaged", "late", "wrong-item", "other"]
def parse_ticket(reply):
text = re.sub(r"^```(json)?\s*|\s*```$", "", reply.strip())
try:
data = json.loads(text)
except json.JSONDecodeError:
return {"ok": False, "errors": ["not valid JSON"]}
if not isinstance(data, dict):
return {"ok": False, "errors": ["expected one JSON object"]}
missing = [f for f in FIELDS if f not in data]
if missing:
return {"ok": False, "errors": ["missing " + f for f in missing]}
errors = []
if data["name"] is not None and not isinstance(data["name"], str):
errors.append("name must be a string or null")
order_id = data["order_id"]
if order_id is not None and not (isinstance(order_id, str) and re.fullmatch(r"[0-9]+", order_id)):
errors.append("order_id must be digits or null")
if data["issue_type"] not in ISSUE_TYPES:
errors.append("issue_type must be one of " + ", ".join(ISSUE_TYPES))
return {"ok": False, "errors": errors} if errors else {"ok": True, "value": data}
reply = '```json\n{"name": "Sam Ortiz", "order_id": null, "issue_type": "late delivery"}\n```'
print(parse_ticket(reply)) # {'ok': False, 'errors': ['issue_type must be one of ...']}There is a difference between null and a missing key. "order_id": null means the email had no order number, which is the behaviour you asked for. A reply with no order_id key at all means the model skipped part of the format, and the code treats that as an error.
Three ways to get structured output
Asking in the prompt
The simplest approach is the one shown above: describe the shape in the prompt and validate the reply. It works with any model and needs no special API. Its weakness is that nothing enforces the format, so you will see occasional fences, extra commentary and invalid JSON, and your code must handle each of them. It is a good starting point for prototypes and for small volumes where an occasional retry is acceptable.
Schema-constrained output
Many model APIs let you pass a JSON schema and constrain the reply so that it always matches that schema. This removes almost all format errors: the reply parses, the required keys are present, and enumerated fields contain only allowed values. Use it when your provider offers it and the reply feeds a program. It still guarantees only the shape. The model can produce a valid value that is wrong, such as "damaged" for an email about a late parcel, so values that matter still need checking. Schemas also support a limited set of features, so a very complex schema may need to be simplified.
Some APIs offer a weaker option, often called JSON mode, which guarantees only that the reply is valid JSON. It does not guarantee that the keys, types or allowed values match what you asked for, so you still describe the shape in the prompt and validate it in code. Check which of the two your provider actually offers before you rely on it.
Tool calls with arguments
Another option is to define a tool whose parameters are the fields you want, and have the model "call" it. The model fills in the arguments, and your code receives them as a structured object. This is the natural choice when the reply is meant to trigger an action, and it is how agents pass parameters to functions (see Tool Use). For plain extraction it behaves much like schema-constrained output, and the validation advice is the same.
Designing a shape that works
- Keep the shape small and flat. Five clear fields are more reliable than twenty nested ones, because each extra field is another chance for a mistake.
- Use plain field names.
delivery_datetells the model what belongs there, anddddoes not. - Add a catch-all to every category field. A value such as
"other"gives unusual inputs a place to go, so the model does not force them into a wrong category. - Put reasoning before the answer. If you want the model to reason, add a field for it ahead of the answer fields. The model writes fields in order, so reasoning that comes first can influence the answer (see Give the Model Room to Think).
Pitfalls when parsing model replies
What this changes in practice
When a program will read the reply, write the output format into the prompt as carefully as you write the task. Give the exact fields, the allowed values and the rule for missing data. If your provider offers schema-constrained output, use it, and keep a validation function anyway for the values that matter. Log every reply that fails validation, because those logs show you which inputs or instructions are causing the problems.
A shopping-list app needs each ingredient's name, amount and unit so that it can add up amounts across recipes. The prompt below returns a list that a person can read but the app cannot. Rewrite it.
Show a sample answer
Amounts can only be added up when the units match, so the prompt fixes the allowed units and says how to convert. The null value covers ingredients such as "salt to taste" without inventing an amount. Singular lowercase names put "Eggs" and "egg" on the same line of the list. The instruction "nothing else" keeps the reply parseable, although your code should still validate it.
An email has no order number, and your prompt does not mention missing values. What is the risk?
You use an API mode that guarantees replies match your JSON schema. Do you still need to check the replies?
You want the model to reason before it picks a category, inside the JSON. Where should the reasoning field go?
A long extraction reply fails to parse, and the JSON ends in the middle of a value. What is the most likely cause?
What to practise next
Rules that must apply to every message in a conversation or app belong in a system prompt. To see how a model passes structured arguments to functions, read Tool Use.