How to beginner · 3 min read

How to use structured outputs for sentiment analysis

Quick answer
Use the structured_output parameter in AI API calls to define a JSON schema for sentiment analysis, enabling the model to return sentiment labels and scores in a predictable format. This approach improves reliability and parsing ease compared to free-text responses.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python package and set your API key as an environment variable.

  • Install the SDK: pip install openai>=1.0
  • Set environment variable: export OPENAI_API_KEY='your_api_key' (Linux/macOS) or setx OPENAI_API_KEY "your_api_key" (Windows)
bash
pip install openai>=1.0

Step by step

This example uses the OpenAI SDK to send a chat completion request with a response_format JSON schema for sentiment analysis. The model returns sentiment and confidence in a structured JSON format.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

schema = {
    "type": "object",
    "properties": {
        "sentiment": {
            "type": "string",
            "enum": ["positive", "neutral", "negative"]
        },
        "confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
        }
    },
    "required": ["sentiment", "confidence"]
}

messages = [
    {"role": "user", "content": "I love this product! It works perfectly."}
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    response_format={"type": "json_schema", "json_schema": schema}
)

result = response.choices[0].message.content
import json
result_json = json.loads(result)
print("Sentiment:", result_json["sentiment"])
print("Confidence:", result_json["confidence"])
output
Sentiment: positive
Confidence: 0.95

Common variations

You can adapt this approach by:

  • Using different models like gpt-4o-mini for faster, cheaper inference.
  • Applying the same structured output schema with Anthropic's claude-3-5-sonnet-20241022 model using its system and messages parameters.
  • Implementing asynchronous calls or streaming if supported by your SDK.
python
import anthropic
import os

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

schema = {
    "type": "object",
    "properties": {
        "sentiment": {
            "type": "string",
            "enum": ["positive", "neutral", "negative"]
        },
        "confidence": {
            "type": "number",
            "minimum": 0,
            "maximum": 1
        }
    },
    "required": ["sentiment", "confidence"]
}

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    system="You are a sentiment analysis assistant. Return output strictly as JSON matching the schema.",
    messages=[{"role": "user", "content": "I love this product! It works perfectly."}],
    max_tokens=200
)

print("Sentiment:", response.content)
output
Sentiment: {"sentiment": "positive", "confidence": 0.95}

Troubleshooting

  • If the model returns free text instead of structured JSON, verify your response_format parameter is correctly set and the model supports structured outputs.
  • For JSON parsing errors, ensure the schema is valid JSON Schema and the model response matches it.
  • If confidence scores seem off, adjust prompt instructions or try a more capable model like gpt-4o or claude-3-5-sonnet-20241022.

Key Takeaways

  • Use response_format with a JSON schema to get reliable sentiment analysis results.
  • Structured outputs simplify parsing and downstream processing compared to free-text responses.
  • Both OpenAI and Anthropic SDKs support structured outputs with similar JSON schema definitions.
Verified 2026-04 · gpt-4o, gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗