Build a Sentiment Analysis Tool with the Claude API
Building a sentiment analysis tool with the Claude API means sending text to a Claude model with a prompt that forces structured output (positive/negative/neutral, a score, key phrases), then parsing that response in your application. Unlike classic sentiment libraries trained on narrow datasets, Claude understands sarcasm, mixed emotions, and domain-specific language out of the box — you just need the right prompt and a reliable way to call the API in production.
This guide walks through designing the prompt, enforcing structured JSON output, handling batches of reviews or support tickets, and deploying the tool behind a stable API endpoint.
Why use an LLM instead of a traditional sentiment model
Traditional sentiment models (VADER, TextBlob, fine-tuned BERT classifiers) are fast and cheap but brittle. They struggle with:
- Sarcasm ("great, another outage, love this product")
- Mixed sentiment in one message ("the UI is beautiful but support never replies")
- Domain jargon (medical, legal, financial text)
- Multiple languages without retraining
Claude handles all of these natively because it reasons over the full context of the sentence rather than matching keyword lists. The tradeoff is latency and cost per request, which is fine for support tickets, reviews, and feedback forms, but something to consider at very high volume (millions of rows/day).
Step 1: Design a prompt that returns structured output
The biggest mistake when building a sentiment tool on top of an LLM is accepting free-text responses. You want deterministic, parseable JSON every time. Be explicit about the schema and give Claude a fallback for ambiguous text.
You are a sentiment analysis engine. Analyze the text below and
respond with ONLY valid JSON in this exact shape:
{
"sentiment": "positive" | "negative" | "neutral" | "mixed",
"score": <number from -1.0 to 1.0>,
"confidence": <number from 0 to 1>,
"key_phrases": [<up to 5 short strings>]
}
Do not include any text outside the JSON object.
Text: "{{input_text}}"
Keeping the instruction tight ("respond with ONLY valid JSON") is what makes this reliable enough to parse with JSON.parse() without a fragile regex cleanup step.
Step 2: Call the API and parse the response
Here's a minimal Node.js example using Claude directly:
const Anthropic = require("@anthropic-ai/sdk");
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
async function analyzeSentiment(text) {
const prompt = `You are a sentiment analysis engine...\nText: "${text}"`;
const response = await client.messages.create({
model: "claude-sonnet-4",
max_tokens: 300,
messages: [{ role: "user", content: prompt }],
});
const raw = response.content[0].text.trim();
return JSON.parse(raw);
}
This works, but running it directly against the Anthropic API in a production app means you're also responsible for key rotation, rate-limit handling across environments, and giving teammates access without sharing a raw secret key.
Step 3: Put it behind a stable API layer
If you're building this sentiment tool for internal use across a team — a Slack bot that tags incoming feedback, a dashboard that scores support tickets, a CRM plugin — you generally don't want every service calling the raw Anthropic API with one shared key. SubToAPI sits in between: you keep using your existing Claude access, but each service or environment (staging sentiment worker, production dashboard, internal Slack bot) gets its own sub_live_... key, with usage tracked per key so you can see exactly which tool is consuming the most tokens.
The call shape is nearly identical to the Anthropic Messages API, so migrating the sentiment function above is a one-line change:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4",
"max_tokens": 300,
"messages": [
{"role": "user", "content": "Analyze sentiment: \"shipping was fast but the box arrived crushed\""}
]
}'
Full request/response details are in the docs and Messages API reference. For a first working call, the quickstart covers getting a key and making your first request in a few minutes.
Step 4: Batch processing for reviews or tickets
Analyzing a single message at a time is fine for a chatbot, but if you're scoring a CSV of 500 customer reviews, batch and rate-limit your requests:
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;
}
Keep concurrency modest (5–10 parallel requests) to avoid hitting rate limits, and add retry logic with exponential backoff for any 429 responses.
Step 5: Add streaming for live feedback dashboards
If you're building a live dashboard that scores incoming support messages in real time, streaming lets you show partial analysis as it's generated instead of waiting for the full response. Claude's streaming works over server-sent events — see the streaming docs for implementation details if you want partial-token updates in your UI rather than a single blocking call.
Step 6: Extract structured fields reliably with tool use
For higher-stakes pipelines (e.g., feeding sentiment scores into a BI tool), tool use (function calling) is more robust than parsing raw text, because Claude is forced to call a function with a defined schema rather than freeform JSON that might occasionally break. Check the tools documentation for defining a record_sentiment tool with sentiment, score, and key_phrases parameters — this removes JSON-parsing failures almost entirely.
Common pitfalls
- Not validating the JSON. Even with strict instructions, occasionally wrap the parse in a try/catch and log failures — don't let one bad response crash a batch job.
- Ignoring mixed sentiment. Real customer feedback is often both positive and negative in the same sentence; include a "mixed" category rather than forcing binary classification.
- Sending huge blocks of text. Trim reviews/tickets to the relevant excerpt before sending — shorter inputs are cheaper and often produce more focused sentiment scores.
- Sharing one API key across every service. Separate keys per environment make debugging and cost attribution much easier once you're running multiple sentiment jobs in parallel.
Getting started
If you already have Claude access and want to turn it into an API your sentiment tool can call with proper key management and usage tracking, you can start a free trial at signup and compare Solo, Team, and Scale plans based on how many services or team members need their own key.
questions
Can Claude analyze sentiment in languages other than English? Yes. Claude handles sentiment analysis across many languages without extra setup — just send the text in its original language and request the same structured JSON output.
How accurate is Claude compared to a dedicated sentiment model? For nuanced text (sarcasm, mixed emotions, domain-specific language), Claude generally outperforms classic sentiment libraries. For simple, high-volume classification at minimal cost, a lightweight traditional model may still be more efficient.
Should I use tool use or plain JSON prompting for sentiment scoring? Plain JSON prompting is simpler and works well for low-volume use. For production pipelines where parsing failures are costly, tool use enforces a strict schema and is more reliable at scale.