← Blog

Claude API Sentiment Analysis Implementation Guide

2026-11-19 · 5 min read · SubToAPI Team

Sentiment analysis with the Claude API means sending text to Claude with a prompt that asks it to classify emotional tone (positive, negative, neutral, or more granular categories) and return structured output you can parse programmatically. Unlike traditional sentiment models trained on fixed label sets, Claude understands context, sarcasm, mixed sentiment, and domain-specific language without any fine-tuning — you just need the right prompt and output format.

This guide covers a production-ready implementation: prompt structure, getting consistent JSON back, handling batches of text, and dealing with edge cases like neutral/mixed sentiment and non-English input.

Why use an LLM instead of a traditional sentiment model

Classic sentiment classifiers (VADER, TextBlob, fine-tuned BERT models) are fast and cheap but brittle. They struggle with:

Claude handles all of these out of the box because it reasons about meaning rather than matching keyword patterns. The tradeoff is latency and cost per request, which matters if you're analyzing millions of rows — more on that below.

Prompt design for reliable classification

The key to usable sentiment analysis output is forcing a strict, parseable format. Don't ask Claude to "analyze the sentiment" in free text — ask for JSON with a fixed schema.

System: You are a sentiment classification engine. For each input text,
return ONLY a JSON object with this exact shape, no other text:

{
  "sentiment": "positive" | "negative" | "neutral" | "mixed",
  "confidence": 0.0 to 1.0,
  "reasoning": "one short sentence"
}

Do not include markdown formatting or code fences in your response.

Then the user message is just the text to classify. This pattern works reliably because Claude follows structural constraints well when they're stated explicitly and reinforced by example.

Example request

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 150,
    "system": "You are a sentiment classification engine. Return ONLY JSON: {\"sentiment\": \"positive|negative|neutral|mixed\", \"confidence\": 0.0-1.0, \"reasoning\": \"short sentence\"}",
    "messages": [
      {"role": "user", "content": "The onboarding was smooth but support took five days to respond."}
    ]
  }'

Expected output:

{"sentiment": "mixed", "confidence": 0.85, "reasoning": "Positive onboarding experience contrasted with slow support response."}

Parsing the response safely

Even with a strict prompt, models occasionally add stray text or wrap output in code fences. Always parse defensively:

function parseSentiment(rawText) {
  const cleaned = rawText.trim().replace(/^```json\s*|\s*```$/g, "");
  try {
    const result = JSON.parse(cleaned);
    if (!["positive", "negative", "neutral", "mixed"].includes(result.sentiment)) {
      throw new Error("Invalid sentiment value");
    }
    return result;
  } catch (err) {
    return { sentiment: "unknown", confidence: 0, reasoning: "Parse failure" };
  }
}

Log parse failures separately — a sudden spike usually means your prompt drifted (e.g., a new system prompt change) or the model changed behavior across a version.

Batch processing for high volume

If you're analyzing reviews, support tickets, or social mentions at scale, don't send one request per item sequentially — that's slow and burns through rate limits. Two approaches work well:

1. Concurrent requests with a concurrency cap

async function analyzeBatch(texts, concurrency = 5) {
  const results = [];
  for (let i = 0; i < texts.length; i += concurrency) {
    const chunk = texts.slice(i, i + concurrency);
    const chunkResults = await Promise.all(chunk.map(analyzeSentiment));
    results.push(...chunkResults);
  }
  return results;
}

2. Batch multiple texts per single prompt

For short texts (tweets, one-line reviews), you can pack several into one request and ask for an array of results keyed by index. This cuts request count dramatically but requires careful prompt engineering to keep output aligned with input order — always include an explicit index field in the schema so a dropped or reordered item is detectable.

Handling confidence and edge cases

Ask Claude to return a confidence score and treat low-confidence results (below ~0.6) as "needs review" rather than auto-classifying them. This is especially important for:

For domain-specific classification (e.g., financial sentiment, medical feedback), add a few labeled examples directly in the system prompt rather than relying on zero-shot classification — three to five examples usually stabilizes output significantly.

Running this through a simple HTTPS API

If you're building sentiment analysis as a feature inside a product rather than a one-off script, you need key management, usage tracking per customer, and streaming support if you're processing long documents interactively. SubToAPI turns your existing Claude access into an HTTPS API with application keys (sub_live_...), so you can issue a separate key per environment or customer and see usage without building that infrastructure yourself.

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 150,
    "system": "Return ONLY JSON: {\"sentiment\": \"positive|negative|neutral|mixed\", \"confidence\": 0.0-1.0}",
    "messages": [{"role": "user", "content": "Shipping was late but the product quality is excellent."}]
  }'

The request/response shape matches the Messages API exactly, so existing sentiment analysis code works unchanged. See the quickstart and messages docs for setup, or pricing if you're evaluating plans for a team rolling this out.

Testing your implementation

Before shipping, build a small evaluation set of 30–50 hand-labeled examples covering your actual data distribution — not generic sentiment benchmarks. Run them through your prompt and measure agreement against your labels. This catches prompt issues (overly aggressive "mixed" classification, missed sarcasm) before they hit production traffic.

Questions

Can Claude classify sentiment into more than positive/negative/neutral? Yes — define any label set in your prompt (e.g., urgency levels, emotion categories, satisfaction scores 1–5) and Claude will follow it as long as the schema is explicit and consistent.

Is Claude accurate enough for sarcasm detection? It performs noticeably better than keyword-based sentiment tools because it reasons about context, but accuracy still depends on how much surrounding context you include in the prompt — a single short message with no context is harder than a full conversation thread.

How do I keep output format consistent at scale? Use a strict JSON schema in the system prompt, parse defensively with fallback handling, and periodically run a labeled evaluation set to catch drift after model or prompt updates.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →