Structured Output with Pydantic

A language model answers in text, but a program needs values: a number it can compare, a word it can look up, a field it can store. Structured output closes that gap. You describe the answer you want as a typed Python model and send that description with the request. The reply comes back as JSON in exactly that shape, and your code turns it into a checked object instead of a paragraph to pick apart.

Why code cannot read a free-text answer

Suppose a program asks a model to rate a product review from 1 to 5 and say whether it is positive, neutral or negative. A person reading the reply has no trouble. Code has to find the number and the word inside the text, and the text is written fresh on every call: the same request can come back phrased differently each time, because the model chooses each next token with some randomness.

A first attempt often looks like this: take the first word of the reply and turn it into an integer.

text = completion.choices[0].message.content
rating = int(text.split()[0])  # works only if the reply starts with the number

That line encodes a guess about how the model will word its answer. The table shows replies a model could plausibly give to the same request, and what the line does with each.

Reply textWhat the code gets
4. The reviewer is mostly happy.4
I would give this a 4 out of 5.ValueError: invalid literal for int()
Rating: 4/5, positive.ValueError: invalid literal for int()
5 stars would be too many; I say 4.5 (wrong, and no error)

The last row is the worst case. A crash at least tells you something went wrong; a wrong number that parses cleanly flows on into the rest of the program. Writing more careful text-matching code only moves the problem, because there is always another way to phrase the same answer. What the program needs is for the reply to arrive in a fixed, machine-readable shape that it can check.

True or false?

If a prompt says "answer with just the number", code can safely read the reply with int().

False. An instruction in the prompt makes the wanted form more likely, but nothing guarantees it. The model can still add a word, a full stop or a sentence, and the conversion then fails or reads the wrong value.

Describing the answer with a Pydantic model

The fixed shape starts as a description of the data you want. Pydantic is a Python library for exactly that: you write a small class that lists the fields of the data and the type of each one, and Pydantic checks any data against it. A class here is just a named template. Writing class Review(BaseModel): says "a Review is a kind of Pydantic model", and each indented line below it declares one field.

from typing import Literal

from pydantic import BaseModel, Field


class Review(BaseModel):
    """A product review reduced to the facts a program needs."""

    rating: int = Field(description="Stars from 1 to 5")
    sentiment: Literal["positive", "neutral", "negative"]
    summary: str = Field(description="One sentence in plain words")

Each part of the class carries meaning:

  • Fields and types. rating: int says there is a field called rating and its value is an integer. summary: str is text. A field written without a default value is required.
  • A fixed set of values. Literal["positive", "neutral", "negative"] allows exactly those three strings and nothing else. "Mostly positive" or "Positive" with a capital letter is rejected.
  • Descriptions. Field(description=...) and the class docstring are text written for a reader. They travel with the description of the data, so the language model can read them too and learn what each field means, which matters for things the type alone cannot say, such as the range of the rating.

Checking data against the class is called validation. Review.model_validate(data) checks a dictionary, and Review.model_validate_json(text) checks a string of JSON. When the data fits, you get a Review object and read its values as attributes: review.rating, review.sentiment. When it does not fit, Pydantic raises one ValidationError that lists every problem it found, each with the field and the reason.

review = Review.model_validate_json(
    '{"rating": "4", "sentiment": "positive", "summary": "Sturdy and cheap."}'
)
print(review.rating + 1)  # 5: the string "4" became the integer 4

Review.model_validate_json(
    '{"rating": 4, "sentiment": "mostly positive", "summary": "Fine."}'
)
# ValidationError: sentiment
#   Input should be 'positive', 'neutral' or 'negative' [type=literal_error, ...]

The first call shows that Pydantic is forgiving by default. In this default behaviour, called lax mode, it converts a value when the conversion is unambiguous, so the string "4" becomes the integer 4. A Literal gets no such leniency: the value must equal one of the allowed values exactly, which is why the second call fails.

True or false?

By default, Pydantic rejects the string "4" for a field declared as int.

False. In the default lax mode Pydantic converts "4" to the integer 4. Only strict mode, switched on with strict=True, rejects it.

A value of "Positive" fails validation for a field typed Literal["positive", "neutral", "negative"].

True. A Literal value must equal one of the listed values exactly, and string comparison is case-sensitive, so "Positive" raises a literal_error.

JSON Schema: the description in a form any service reads

A Pydantic class is Python, and a model provider's server does not run your Python. To send the description of the answer over HTTP, it has to become data. The common format for that is JSON Schema, a declarative language for describing the structure of JSON data and the constraints on it. A schema is itself a JSON document: it says the data is an object, names its properties, gives each a type, and can list which properties are required. The current version of the standard is 2020-12.

For the review, a JSON Schema looks like this:

{
  "type": "object",
  "description": "A product review reduced to the facts a program needs.",
  "properties": {
    "rating": {"type": "integer", "description": "Stars from 1 to 5"},
    "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
    "summary": {"type": "string", "description": "One sentence in plain words"}
  },
  "required": ["rating", "sentiment", "summary"]
}

You do not write this by hand. Review.model_json_schema() generates it from the class as a Python dictionary, ready for json.dumps. Pydantic's version also adds a title to each field, made from the field name, but the meaning is the same. Each Python type has a JSON Schema counterpart:

In the Pydantic modelIn the JSON Schema
int"type": "integer"
float"type": "number"
str"type": "string"
bool"type": "boolean"
list[str]"type": "array" with "items" for the element type
Literal["a", "b"]"enum": ["a", "b"]
Field(description=...) or a docstring"description"
another model used as a fieldan entry under "$defs", pointed to with "$ref"

Two defaults of JSON Schema surprise people. A property listed under properties is optional unless it also appears in required. And an object may carry extra properties the schema never mentions, unless the schema says "additionalProperties": false. A schema that is meant to pin an answer down tightly sets both.

True or false?

In JSON Schema, every property listed under "properties" must be present in the data.

False. Properties are optional by default. Only the ones named in the "required" list must be present.

A field described with Field(description=...) produces a "description" that the language model can read in the schema.

True. The description is copied into the generated JSON Schema, and the schema is sent with the request, so it becomes part of what the model sees.

Structured output: the schema as the response format

With the schema in hand, the request can ask for an answer in that shape. In a Chat Completions request this goes in the response_format parameter, next to the model name and the messages. The value names the kind of format (json_schema), gives the schema a name, and carries the schema itself.

"response_format": {
  "type": "json_schema",
  "json_schema": {
    "name": "Review",
    "strict": true,
    "schema": {
      "type": "object",
      "properties": {
        "rating": {"type": "integer", "description": "Stars from 1 to 5"},
        "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
        "summary": {"type": "string", "description": "One sentence in plain words"}
      },
      "required": ["rating", "sentiment", "summary"],
      "additionalProperties": false
    }
  }
}

The reply then carries no prose at all. Its content is a string of JSON such as {"rating": 4, "sentiment": "positive", "summary": "Sturdy and cheap."}, with the keys in the order the schema lists them.

  • Review class Pydantic
  • JSON Schema model_json_schema()
  • Request response_format
  • Language model writes JSON
  • JSON text message.content
  • Review object validated
  • Review class to JSON Schema
  • JSON Schema to Request
  • Request to Language model
  • Language model to JSON text
  • JSON text to Review object: validate

This "strict" is a setting of the request, read by the endpoint. It has nothing to do with Pydantic's strict mode from earlier, which only decides how Pydantic converts values when it validates.

With "strict": true, an endpoint that supports it constrains generation itself: at each step the model may only produce tokens that keep the reply valid against the schema, so the reply cannot leave out a required field or invent a sentiment. That strict mode comes with rules for the schema:

  • the top level must be an object;
  • every object must set "additionalProperties": false;
  • every property must be listed in required. A field that may be empty gets a type that also allows null, so the model still returns the field, with null as its value when there is nothing to say.

Structured output is a step beyond an older setting called JSON mode ({"type": "json_object"}). Both produce valid JSON, but JSON mode does not hold the reply to any particular schema: the keys and types are whatever the model chose.

Support for json_schema also varies between endpoints. Some providers and local servers enforce it, some accept it only for certain models, and some do not offer it at all.

One limit always remains. The schema constrains the shape of the answer, not its truth. A reply can be perfectly valid and still give a glowing review a rating of 2.

True or false?

A reply that matches the schema exactly is guaranteed to be a correct answer.

False. The schema fixes the keys, types and allowed values. The values themselves are still generated by the model and can be wrong.

JSON mode and structured output both return valid JSON, but only structured output holds the reply to a given schema.

True. JSON mode guarantees only that the text parses as JSON. Structured output also makes it follow the schema sent with the request.

From JSON text to a validated object

The reply's content is still a string. The last step turns it into a Review object, and there are two ways to do it with the openai Python client.

The parse helper of the client

client.chat.completions.parse() wraps the ordinary create() call. You pass the Pydantic class itself as response_format, and the helper does the rest: it converts the class into a strict JSON Schema named after the class, sends it, and validates the reply's content back into the class. The object is waiting on message.parsed.

completion = client.chat.completions.parse(
    model=model_name,
    messages=[
        {"role": "system", "content": "Rate the product review you are given."},
        {"role": "user", "content": review_text},
    ],
    response_format=Review,
)

message = completion.choices[0].message
if message.parsed:
    review = message.parsed
    print(review.rating, review.sentiment)
else:
    print("No answer:", message.refusal)

To meet the strict rules, the helper adjusts the schema Pydantic generates. It adds "additionalProperties": false to every object and lists every property as required, including fields that have a default value in Python. A default therefore does not make a field optional for the model: it must always send a value.

If the content still does not fit the class, the helper does not hide it. Pydantic's ValidationError comes out of the parse() call, where your code can catch it.

Older examples call this helper as client.beta.chat.completions.parse. That was its earlier location. The documented place is now client.chat.completions.parse, so use that one.

The model class itself

When you build the response_format dictionary yourself, or use an endpoint where the helper does not fit, call create() as usual and validate the content with the class. With a dictionary as response_format, the client has no class to parse into, so this is your job.

from pydantic import ValidationError

message = completion.choices[0].message
try:
    review = Review.model_validate_json(message.content)
except ValidationError as error:
    print(error)  # which field failed and why

Both routes end in the same place: either a Review object whose fields have the declared types and allowed values, or a clear error. From here on, review.rating is an integer the program can compare, with no text matching anywhere.

True or false?

A field declared with a default value, such as summary: str = "", stays optional in the schema the parse helper sends.

False. The helper's strict conversion lists every property in "required", so the model must return every field, defaults included.

If the reply's JSON does not fit the class, parse() raises a Pydantic ValidationError.

True. The helper validates with the class and lets the ValidationError propagate, so the calling code sees it.

When there is nothing to parse

Some replies contain no answer in the schema's shape at all, and code that goes straight to message.parsed or model_validate_json will either fail or carry on with nothing. Two cases need a check before the result is trusted.

A refusal. When the model declines a request, for example for safety reasons, its reply does not follow the schema. Endpoints that support this put the explanation in a separate refusal field on the message instead of in content. The parse helper then leaves message.parsed as None, which is why the code above tests parsed before using it and prints refusal otherwise.

A cut-off reply. If the reply reaches its token cap, generation stops mid-JSON and the finish reason is length. Half an object such as {"rating": 4, "sentiment": "posi is not valid JSON. The parse helper checks the finish reason before it parses anything and raises LengthFinishReasonError; it raises ContentFilterFinishReasonError in the same way when the finish reason is content_filter.

  • Reply arrives
  • finish_reason?
  • Cut off or filtered no complete JSON
  • refusal set?
  • Model declined show or log refusal
  • Validate content against the class
  • ValidationError shape does not fit
  • Review object safe to use
  • Reply arrives to finish_reason?
  • finish_reason? to Cut off or filtered: length / content_filter
  • finish_reason? to refusal set?: stop
  • refusal set? to Model declined: yes
  • refusal set? to Validate content: no
  • Validate content to ValidationError: fails
  • Validate content to Review object: fits

With the parse helper, these checks come out as exceptions plus one test of parsed. One detail matters when you catch them. The two finish-reason errors are kinds of openai.OpenAIError, the client's most general error, but not kinds of openai.APIError, the error for a failed HTTP call. A handler written as except openai.APIError therefore lets them through, so name them in their own except clauses.

import openai
from pydantic import ValidationError

try:
    completion = client.chat.completions.parse(
        model=model_name,
        messages=messages,
        response_format=Review,
    )
except openai.LengthFinishReasonError:
    print("The reply was cut off before the JSON was complete.")
except openai.ContentFilterFinishReasonError:
    print("The reply was stopped by the content filter.")
except ValidationError as error:
    print("The reply did not fit the Review model:", error)
else:
    message = completion.choices[0].message
    if message.parsed:
        print(message.parsed.rating)
    else:
        print("The model declined:", message.refusal)

Without the helper, the same order applies by hand: look at completion.choices[0].finish_reason first, then at message.refusal, and only then validate message.content with the class.

True or false?

After a successful call to parse(), message.parsed always holds an object.

False. It is None when the model refused or the content was empty. A cut-off or filtered reply does not return at all: it raises an exception.

except openai.APIError catches a LengthFinishReasonError from a cut-off structured reply.

False. LengthFinishReasonError derives from OpenAIError, not APIError, so it passes straight through an APIError handler.

A reply that stopped at its token cap usually cannot be parsed, because the JSON ends in the middle.

True. Generation stops wherever the cap falls, so closing quotes and braces are missing and the text is not valid JSON.