pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
pythonPress β/Ctrl + Shift + C to copy
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.
typescriptintermediate
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
Best for: data extraction
#openai#zod
typescriptbeginner
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.
Best for: AI art generation
#openai#dall-e
typescriptbeginner
Content Moderation with OpenAI
Check user input for harmful content using the OpenAI Moderation API before processing.
Best for: user input safety
#openai#moderation
typescriptintermediate
Next.js AI Streaming Route Handler
Stream OpenAI responses from a Next.js App Router route handler using the Vercel AI SDK.
Best for: AI chatbot backend
#nextjs#openai