Exercise: Structured Outputs¶
Objective¶
Get typed, validated responses from the LLM using Pydantic models and chat.completions.parse().
Concepts Covered¶
- Structured outputs with Pydantic models
client.chat.completions.parse()withresponse_format- Guaranteed schema conformance from the model
How It Works¶
Instead of chat.completions.create(), this script uses chat.completions.parse() with a ReviewAnalysis Pydantic model. The model returns JSON that is automatically validated and parsed into a typed Python object with fields like sentiment, rating, keywords, and recommended.
flowchart LR
Review["Review text"] --> LLM["chat.completions.parse()<br/>response_format=ReviewAnalysis"]
LLM --> Parsed["ReviewAnalysis object<br/>• sentiment: positive<br/>• rating: 4<br/>• keywords: [...]<br/>• recommended: true"]
Structured output: Yes — this is the first exercise that uses client.chat.completions.parse() with a Pydantic model as response_format. The model's output is guaranteed to match the schema.
Interactive Message Flow¶
File¶
03_structured_outputs.py— Extract structured data usingclient.chat.completions.parse()
How to Run¶
Expected Output¶
Structured logging showing the parsed ReviewAnalysis object with typed fields like sentiment, rating, keywords, and recommended.