Build AI Apps with Python: Product Review Analyzer with JSON | Episode 5
Video: Build AI Apps with Python: Product Review Analyzer with JSON | Episode 5 by Taught by Celeste AI - AI Coding Coach
Watch full page →Build AI Apps with Python: Product Review Analyzer with JSON
In this tutorial, we create a product review analyzer that processes any review text and returns a structured JSON response containing sentiment, rating, key points, and a summary. By crafting a precise system prompt and setting the AI temperature to 0.0, we ensure consistent, parseable outputs that can be easily handled in Python.
Code
import openai
import json
# Define a detailed system prompt to enforce JSON output format
system_prompt = """
You are a product review analyzer. Given a product review, respond ONLY with a JSON object in the following format:
{
"sentiment": "positive" | "neutral" | "negative",
"rating": 1-5,
"key_points": ["point1", "point2", "..."],
"summary": "A concise summary of the review."
}
Do not add any other text or explanation.
"""
def analyze_review(review_text):
# Compose messages for the chat completion
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": review_text}
]
# Call OpenAI API with temperature=0.0 for deterministic output
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.0
)
# Extract the JSON string from the AI response
json_str = response.choices[0].message.content
# Parse the JSON string into a Python dictionary
result = json.loads(json_str)
return result
# Example usage with a sample review
sample_review = "This product exceeded my expectations! The build quality is excellent and it works flawlessly."
analysis = analyze_review(sample_review)
# Pretty-print the structured analysis
print(json.dumps(analysis, indent=2))
Key Points
- Use a detailed system prompt to strictly define the JSON output format for AI responses.
- Set temperature=0.0 in the API call to ensure consistent and reliable structured outputs.
- Parse the AI's JSON response using Python's json.loads() for easy data manipulation.
- Pretty-print parsed JSON with json.dumps(indent=2) for readable output.
- This approach enables predictable, structured data extraction from freeform product reviews.