Code beginner · 3 min read

How to do sentiment analysis with Python

Direct answer
Use the OpenAI Python SDK to send text to a chat model like gpt-4o with a prompt instructing it to classify sentiment, then parse the response from response.choices[0].message.content.

Setup

Install
bash
pip install openai
Env vars
OPENAI_API_KEY
Imports
python
import os
from openai import OpenAI

Examples

inI love this product! It works perfectly.
outSentiment: Positive
inThe service was okay, nothing special.
outSentiment: Neutral
inI'm very disappointed with the quality.
outSentiment: Negative

Integration steps

  1. Import the OpenAI SDK and initialize the client with the API key from os.environ
  2. Create a chat completion request with model 'gpt-4o' and a prompt asking for sentiment classification
  3. Send the user text as a message in the chat completion request
  4. Receive the response and extract the sentiment label from response.choices[0].message.content
  5. Print or use the sentiment result in your application

Full code

python
import os
from openai import OpenAI

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

text_to_analyze = "I love this product! It works perfectly."

messages = [
    {"role": "user", "content": f"Classify the sentiment of this text as Positive, Neutral, or Negative:\n\n{text_to_analyze}"}
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages
)

sentiment = response.choices[0].message.content.strip()
print(f"Sentiment: {sentiment}")
output
Sentiment: Positive

API trace

Request
json
{"model": "gpt-4o", "messages": [{"role": "user", "content": "Classify the sentiment of this text as Positive, Neutral, or Negative:\n\nI love this product! It works perfectly."}]}
Response
json
{"choices": [{"message": {"content": "Positive"}}], "usage": {"prompt_tokens": 20, "completion_tokens": 1, "total_tokens": 21}}
Extractresponse.choices[0].message.content

Variants

Streaming sentiment analysis ›

Use streaming to get partial sentiment results faster or for UI with live updates.

python
import os
from openai import OpenAI

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

text_to_analyze = "I love this product! It works perfectly."

messages = [
    {"role": "user", "content": f"Classify the sentiment of this text as Positive, Neutral, or Negative:\n\n{text_to_analyze}"}
]

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    stream=True
)

sentiment = ""
for chunk in stream:
    delta = chunk.choices[0].delta.content or ""
    sentiment += delta
print(f"Sentiment: {sentiment.strip()}")
Async sentiment analysis ›

Use async when integrating sentiment analysis into asynchronous Python applications or web servers.

python
import os
import asyncio
from openai import OpenAI

async def analyze_sentiment():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    text_to_analyze = "I love this product! It works perfectly."
    messages = [
        {"role": "user", "content": f"Classify the sentiment of this text as Positive, Neutral, or Negative:\n\n{text_to_analyze}"}
    ]
    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=messages
    )
    sentiment = response.choices[0].message.content.strip()
    print(f"Sentiment: {sentiment}")

asyncio.run(analyze_sentiment())
Using Anthropic Claude for sentiment analysis ›

Use Anthropic Claude models if you prefer Claude's style or have an Anthropic API key.

python
import os
from anthropic import Anthropic

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

text_to_analyze = "I love this product! It works perfectly."

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    system="You are a helpful assistant that classifies sentiment.",
    messages=[{"role": "user", "content": f"Classify the sentiment of this text as Positive, Neutral, or Negative:\n\n{text_to_analyze}"}]
)

sentiment = response.content.strip()
print(f"Sentiment: {sentiment}")

Performance

Latency~800ms for gpt-4o non-streaming
Cost~$0.002 per 500 tokens for gpt-4o
Rate limitsTier 1: 500 RPM / 30K TPM
  • Keep prompts concise to reduce token usage.
  • Avoid sending unnecessary system messages for simple classification.
  • Cache repeated sentiment results for identical inputs.
ApproachLatencyCost/callBest for
Standard chat completion~800ms~$0.002Simple sentiment classification
Streaming chat completion~500ms initial~$0.002UI with live updates
Async chat completion~800ms~$0.002Concurrent or web apps
Anthropic Claude~900msCheck Anthropic pricingAlternative model style
✓

Quick tip

Frame your prompt clearly to classify sentiment as 'Positive', 'Neutral', or 'Negative' for consistent results.

⚠

Common mistake

Beginners often forget to strip whitespace from the model's response, leading to parsing errors.

Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.