DEV Community

shashank ms
shashank ms

Posted on

Sentiment Analysis using LLM: A Guide to Product Review Analysis

Product teams drown in unstructured review text. In this guide we will build a lightweight sentiment analyzer that reads product reviews, scores them, and extracts specific complaints and praise. We will wire it to Oxlo.ai and run it against a real batch of sample reviews.

What you'll need

You need Python 3.10 or newer, the OpenAI SDK, and an Oxlo.ai API key. Grab your key from the Oxlo.ai portal and install the SDK.

pip install openai

Step 1: Configure the Oxlo.ai client

I start by importing the SDK and instantiating the client against Oxlo.ai. I pick Llama 3.3 70B because it handles classification and JSON formatting consistently.

from openai import OpenAI
import json

client = OpenAI(base_url="https://api.oxlo.ai/v1", api_key="YOUR_OXLO_API_KEY")

Step 2: Write the system prompt

The system prompt forces the model to return strict JSON with a sentiment label, confidence score, and a list of themes. Keeping the prompt explicit prevents hallucinated keys.

SYSTEM_PROMPT = """You are a product review sentiment analyzer.
Read the review and respond with a single JSON object. Do not include markdown formatting or explanations.

Required JSON schema:
{
  "sentiment": "positive" | "neutral" | "negative",
  "confidence": 0.0 to 1.0,
  "themes": ["short phrase", "another phrase"],
  "summary": "one sentence describing the core feedback"
}

Rules:
- sentiment must be exactly one of the three allowed strings.
- confidence reflects how obvious the sentiment is.
- themes extracts specific product aspects mentioned (battery, ui, price, etc.).
- summary must be under 20 words."""

Step 3: Build the analyzer function

This helper takes a raw review string, sends it to Oxlo.ai, and parses the returned JSON. I wrap the call in a small try block so one malformed response does not kill the entire batch.

def analyze_review(review_text: str):
    response = client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": review_text},
        ],
    )
    
    raw = response.choices[0].message.content.strip()
    
    # Remove markdown code fences if the model emits them
    if raw.startswith("

```"):
        raw = raw.split("```

")[1]
        if raw.startswith("json"):
            raw = raw[4:]
        raw = raw.strip()
    
    return json.loads(raw)

Step 4: Process a batch of reviews

Now I feed a list of real sample reviews through the analyzer. I collect the structured results into a list so I can tally them in the next step.

reviews = [
    "Battery life is amazing, easily lasts two days. The camera is just okay.",
    "Worst update ever. App crashes every time I open settings. Completely unusable.",
    "It does what it says. Nothing special but fair for the price.",
    "Love the new dark mode. Navigation feels snappy and intuitive.",
    "Shipping was fast, but the charger stopped working after a week.",
]

results = []
for r in reviews:
    try:
        parsed = analyze_review(r)
        results.append(parsed)
        print(f"Processed: {parsed['sentiment']} | {parsed['summary']}")
    except Exception as e:
        print(f"Failed on review: {r[:50]}... Error: {e}")

Run it

Executing the full script against Oxlo.ai produces structured JSON for every review. Because Oxlo.ai uses request-based pricing, the cost stays flat even when reviewers write long paragraphs. See the pricing page for details.

if __name__ == "__main__":
    for item in results:
        print(json.dumps(item, indent=2))

Example output:

{
  "sentiment": "positive",
  "confidence": 0.85,
  "themes": ["battery life", "camera quality"],
  "summary": "Great battery life but average camera."
}
{
  "sentiment": "negative",
  "confidence": 0.95,
  "themes": ["app crashes", "settings bug"],
  "summary": "Recent update causes frequent crashes."
}
{
  "sentiment": "neutral",
  "confidence": 0.75,
  "themes": ["value for price"],
  "summary": "Adequate product for the price point."
}
{
  "sentiment": "positive",
  "confidence": 0.9,
  "themes": ["dark mode", "navigation speed"],
  "summary": "Dark mode and fast navigation praised."
}
{
  "sentiment": "negative",
  "confidence": 0.8,
  "themes": ["charger defect", "shipping speed"],
  "summary": "Fast shipping but defective charger."
}

Wrap-up

You now have a working analyzer that turns raw text into structured product insights. A concrete next step is to schedule this as a daily job that pulls fresh reviews from your app store API and writes the JSON into a data warehouse. If you need deeper reasoning on complex or mixed reviews, swap the model to DeepSeek R1 671B or Kimi K2.6 on Oxlo.ai without changing any other code.

Top comments (0)