OPENAI WORKFLOW · 07 / 10
Parse structured OpenAI output with Pydantic
Define an output shape for application data instead of extracting fields from prose.
Documentation checked · Loomwell editorial guide · Examples have not been live API tested.
Steps
- Use a model that supports Structured Outputs. Install pydantic alongside openai in your project environment.
- Pass a Pydantic model as text_format to responses.parse. Handle refusals and incomplete responses before consuming parsed data.
Example
Python · Python API examples require OPENAI_API_KEY and OPENAI_MODEL in your server environment. API calls may incur OpenAI charges.
import os
from openai import OpenAI
from pydantic import BaseModel
class Summary(BaseModel):
title: str
points: list[str]
response = OpenAI().responses.parse(
model=os.environ["OPENAI_MODEL"],
input="Summarize why HTTP timeouts matter.", text_format=Summary,
)
if response.status != "completed" or response.output_parsed is None:
raise RuntimeError("No completed structured result; inspect refusal or failure")
print(response.output_parsed.model_dump())Check the result
Expect a title and a list of points. Schema conformance does not prove the facts are correct; validate the content before using it for a consequential action.
Official source
Check current provider documentation and model support before deployment. This guide is separate from the approved evidence records listed in the catalog.
Use Loomwell with your coding agent
Inspect the published record coverage before starting a trial or connecting MCP.