Skip to content

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() with response_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

You are a product review analyst. Extract structured data from customer reviews.
Analyze this review: 'Great headphones! Sound quality is amazing, comfortable for long sessions. Battery could be better though.'
Generating structured response matching the ReviewAnalysis schema...
sentiment: positive | rating: 4 | keywords: [sound quality, comfortable, battery] | summary: Positive review praising audio and comfort with minor battery concern | recommended: true

File

  • 03_structured_outputs.py — Extract structured data using client.chat.completions.parse()

How to Run

python exercises/01_llm_basics/03_structured_outputs.py

Expected Output

Structured logging showing the parsed ReviewAnalysis object with typed fields like sentiment, rating, keywords, and recommended.

Next

Exercise: Function Calling