New Tool Radar

AI Concepts

How to Define a Response Schema as a Pydantic Model in Python

Define the schema in code with a Pydantic BaseModel, parse the structured reply, and read the typed result.

Schematic with three steps: Define the schema as a BaseModel; Pass it as the text format; Read the typed result.

The OpenAI libraries for Python and JavaScript let you define object schemas using pydantic.BaseModel and z.object respectively, instead of writing raw JSON Schema by hand. Defining the schema in code keeps the schema and the types in your program in one place, and the parsed reply comes back as a typed object you can read directly. The published example extracts a calendar event with a name, a date and a list of participants.

What you need

  • Python with the OpenAI library and Pydantic installed
  • An API key and a model that supports Structured Outputs
  • The fields the reply must contain

Step 1: Define the schema as a BaseModel

Write a class that inherits from pydantic.BaseModel with typed fields, for example name as a string, date as a string and participants as a list of strings. The class is the schema.

Step 2: Pass it as the text format

Call the parse method with the model, the messages and text_format set to your class. The response object carries the parsed result.

Step 3: Read the typed result

Read the parsed output from the response and use its fields directly. If parsing fails, the raw output is still available for inspection.

Worked example: synthetic Pydantic extraction

The table below is a synthetic example. It shows the expected result of parsing a Pydantic schema; no API call was made.

Field Type Parsed value
name str Science fair
date str Friday
participants list[str] Alice, Bob
Result object CalendarEvent Typed, ready to use

Expected result (UNTESTED). the reply parses into a CalendarEvent object with all three fields typed and ready to use. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Use the native SDK schema helpers where available, so the JSON Schema and the types in your code cannot diverge.
  • If you specify the JSON Schema directly, add a CI rule that flags when either the schema or the underlying data objects are edited.
  • The model will always try to adhere to the schema, which can produce hallucinations if the input is completely unrelated to it.
  • For user-generated input, tell the prompt what to return when the input cannot produce a valid response.

Sources

See all