python --version
pip install pydantic openai
export OPENAI_API_KEY=sk-...
Use the OpenAI structured output feature with Pydantic models to guarantee LLM responses conform to your expected schema.
1 from typing import Literal 2 from pydantic import BaseModel, field_validator 3 from openai import OpenAI 4 5 client = OpenAI() 6 7 class ProductReview(BaseModel): 8 rating: int 9 sentiment: Literal["positive", "negative", "neutral"] 10 summary: str 11 key_points: list[str] 12 13 @field_validator("rating") 14 @classmethod 15 def validate_rating(cls, v: int) -> int: 16 if not 1 <= v <= 5: 17 raise ValueError(f"Rating must be 1-5, got {v}") 18 return v 19 20 def analyze_review(review_text: str, max_retries: int = 3) -> ProductReview | None: 21 for attempt in range(max_retries): 22 try: 23 resp = client.beta.chat.completions.parse( 24 model="gpt-4o-mini", 25 messages=[ 26 {"role": "system", "content": "Analyze the product review and extract structured information."}, 27 {"role": "user", "content": review_text}, 28 ], 29 response_format=ProductReview, 30 ) 31 if resp.choices[0].message.refusal: 32 print(f"Refusal on attempt {attempt + 1}: {resp.choices[0].message.refusal}") 33 continue 34 return resp.choices[0].message.parsed 35 except Exception as e: 36 print(f"Attempt {attempt + 1} failed: {e}") 37 return None 38 39 # Test 40 reviews = [ 41 "Amazing product! Works perfectly and arrived quickly. 5 stars.", 42 "Terrible quality. Broke after one day. Very disappointed.", 43 "It's okay, nothing special. Does what it says.", 44 ] 45 46 for review in reviews: 47 result = analyze_review(review) 48 if result: 49 print(f"Rating: {result.rating}/5 | {result.sentiment} | {result.summary}") 50
Sign in to share your feedback and join the discussion.