pythonintermediate

OpenAI Structured Output with Pydantic

Force GPT to return validated JSON matching a Pydantic schema.

python
from openai import OpenAI
from pydantic import BaseModel
from typing import List, Optional

client = OpenAI()

class ProductReview(BaseModel):
    sentiment: str  # positive, negative, neutral
    score: float    # 0.0 to 1.0
    key_points: List[str]
    suggested_improvements: Optional[List[str]] = None

class ReviewAnalysis(BaseModel):
    reviews: List[ProductReview]
    overall_sentiment: str
    summary: str

response = client.beta.chat.completions.parse(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Analyze product reviews."},
        {"role": "user", "content": """
            Review 1: Great product! Fast shipping, works perfectly.
            Review 2: Broke after 2 weeks. Terrible quality.
            Review 3: Decent value for the price, nothing special.
        """}
    ],
    response_format=ReviewAnalysis
)

analysis = response.choices[0].message.parsed
print(f"Overall: {analysis.overall_sentiment}")
for review in analysis.reviews:
    print(f"  {review.sentiment}: {review.score:.1f}")

Use Cases

  • Review analysis
  • Data extraction
  • Automated classification

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.