Skip to Content

Controlling the output

Asking a model to "please return JSON" is a request it can bend. Watch it break a parser, then see a JSON Schema turn the format into a rule, and learn what your own code must still check.

10 minFree

Controlling the output
  1. Build the request
  2. Generate
  3. Parse and check
  4. Result
FIG. PE-OUTPUT-FORMAT / 06 PARTSFront deskclinic WhatsAppPrompttask + messageJSON SchemaAPI parameterModelany LLMYour codeparse + checkCalendarappointments

Press Play to watch it run, or step through with ← →. Then switch to Practice and run it yourself.

00/06
Read this WhatsApp message sent to Asha Clinic and pull out the
appointment details. Please return JSON.

Message: Hello, I want to bring my son Arjun to Dr Rao tomorrow
evening. He has had fever since Monday.

What came back

Nothing yet. Press Play.

Background: the idea in plain words2 min read

When a person reads a model's answer, the format hardly matters. A greeting, a paragraph, a list: a person copes with all of them. When code reads the answer, the format is everything. Code looks for exact names in exact places, and one extra word can stop it.

So you need to control the shape of the output. There are three levels of control, from loose to strict.

The first level is to ask in the prompt (the text you send to the model). You can ask for a table, a bulleted list, three sentences, or a data format such as JSON. JSON is a simple text format that writes data as names and values, like {"slot": "evening"}. Asking works well for output that people read. For output that code reads, it is fragile: "please return JSON" does not say which names to use, and nothing stops the model from adding a friendly sentence around the data.

The second level is to show the format: give an example of the exact output, as in the lesson Few-shot examples. This closes many gaps, but it is still only a strong hint.

The third level is structured output. You write a JSON Schema, which is a description of the fields the answer must have: their names, their types (text, number, true or false) and which are required. You send the schema to the API in its own parameter, next to the prompt. The API then lets the model produce only text that fits the schema. The format stops being a request and becomes a rule.

One thing does not change at any level. A schema checks the shape of the answer. It cannot check that the values make sense for your business. That stays your code's job.

The running example is the front desk of Asha Clinic. Patients ask for appointments on WhatsApp, and the app turns each message into a record with a patient name, a doctor, a date, a slot and a reason. Press Play to watch "Please return JSON" break the parser. Then switch Try it to After: a clear prompt plus a JSON Schema, and finally to Edge case: valid JSON, value your rules reject.

What to notice

  1. "Please return JSON" leaves most of the format open. No field names, no types, and no rule against extra words. The model understood the message perfectly and the parser still failed at the first character.
  2. A schema is enforced while the text is written. It travels in an API parameter, not in the prompt text. The vendors describe it as constraining the output to your schema, so a greeting in front of the JSON cannot happen.
  3. The prompt still explains the content. The schema says date is a string. The prompt says which date, in which form, and what today's date is. You need both.
  4. Use enum for fixed choices. doctor and slot can each be only one of a short list of values. Your code can then compare values exactly, with no guessing about spelling.
  5. Valid JSON is not a correct booking. In the third run the reply matches the schema and the clinic is still closed that day. Parse first, then check your own rules.
Go deeper

Asking for a format in words

1 min read

Most output is read by people, and for that a clear request is enough. Google's prompting guide gives examples such as asking for a table, a bulleted list or an elevator pitch. Three habits make such requests work better:

  • Say what you want, not what you do not want. "Answer in two short paragraphs of plain text" works better than "do not use bullet points". Anthropic's guide gives this as its first tip for steering format.
  • Start the answer yourself. Google's guide calls this the completion strategy: end the prompt with the first words of the output, such as a heading or a label, and the model continues in that form.
  • Show one example of the finished output when the layout is exact.

Google's guide also draws the line clearly: you can specify simple JSON in a prompt, but for a more complex JSON Schema it recommends the structured output feature.

Go deeper

Where the schema goes, vendor by vendor

1 min read

The idea is the same everywhere. The parameter names are not. These are the names in each vendor's documentation at the time of writing:

VendorWhere the schema goes in the request
Google (Gemini API)response_format, with mime_type set to application/json and the schema in schema
Anthropic (Claude API)output_config.format, with type set to json_schema and the schema in schema
OpenAI (Responses API)text.format, with type set to json_schema, strict set to true, and the schema in schema

Each vendor supports only a part of the full JSON Schema standard, and the parts differ. Two examples from the docs:

  • Google does not enforce some keywords during generation, including minLength and maxLength. It removes them without an error, so you must check those limits yourself.
  • Anthropic requires additionalProperties to be false on objects, does not support keywords such as minLength, maxLength, minimum and maximum, and returns a 400 error if you send an unsupported feature.

The schema in this lesson uses only plain types, enum, required and additionalProperties: false, which is a safe core. Before you add anything more, read your vendor's list of supported keywords. For a walk through the Gemini version with code, see Structured output.

Descriptions are part of the prompt The model reads the names and descriptions in your schema. Google's docs say to use the description field to guide the model, and OpenAI's say to name keys clearly and add descriptions for important keys. A field called date with the description "Requested day as YYYY-MM-DD" will be filled better than a field called d.

Go deeper

What your code should still check

1 min read

Structured output removes one kind of failure: the wrong shape. These are left, and they are yours:

  1. Did the reply finish? If the model reaches the output token limit, the reply is cut off and the JSON may be incomplete. Anthropic reports this as stop_reason: "max_tokens". OpenAI reports the response status as incomplete.
  2. Did the model refuse? A model can decline a request for safety reasons, and a refusal does not have to match your schema. Anthropic reports stop_reason: "refusal". OpenAI returns a refusal item in the response.
  3. Are the values real? A string that looks like a date may not be a real date. The check.py file turns it into a calendar date, which fails for a day that does not exist.
  4. Do the values follow your business rules? The clinic is closed on Sundays. No schema knows that. OpenAI's guide says your app must validate any business rules that the schema does not express, and Google's says to handle output that fits the schema but is wrong in meaning.

When a check fails, decide in advance what happens: ask the patient, send it to a person, or call the model once more with the error. Do not quietly save the bad record.

Go deeper

What it costs

1 min read

A schema is not free of trade-offs. Anthropic's docs note that the first request with a new schema has extra latency while the schema is compiled, and that the compiled form is then cached. Very large or deeply nested schemas can be rejected: both Google and Anthropic say so. And a strict schema can only return the fields you thought of. If the model has something useful to say that fits no field, it has nowhere to say it. Keep schemas small and flat, and add a field only when your code will use it.

Go deeper

Words to know

1 min read
WordMeaning in simple words
JSONA simple text format that writes data as names and values
ParseTo read text and turn it into data that code can use
JSON SchemaA description of the fields an answer must have, with their names and types
Structured outputAn API feature that makes the model's reply fit your schema
EnumA fixed list of allowed values for a field
ValidateTo check in your own code that the values follow your rules

Check your understanding

1. Your prompt ends with “Please return JSON” and the reply starts with “Sure! Here are the details”. What is the most reliable fix?
2. The reply matches your schema exactly, and the date is a Sunday when the clinic is closed. What does this show?
3. You move your schema from one vendor to another and the API rejects it, or silently ignores a length limit. Why can that happen?
Sources: the official documentation4 links

Something wrong or unclear in this lesson? Tell us, it gets fixed.