Sentiment Analyzer
Analyze text sentiment with Workers AI at the edge
Classify text sentiment as positive or negative using Workers AI and DistilBERT. Returns a label and confidence score for any short text input.
Features
- Classify text as positive or negative with confidence scores
- Workers AI DistilBERT model at the edge
- Single GET endpoint with a
textquery parameter - No external ML API keys required
API Reference
GET /sentiment
Analyzes the sentiment of the provided text.
Prop
Type
Example Request
curl "https://your-worker.workers.dev/sentiment?text=This%20pizza%20is%20great!"Success Response
text string
The original input text
label string
Sentiment label (e.g. POSITIVE or NEGATIVE)
score number
Confidence score for the predicted label (0–1)
{
"text": "This pizza is great!",
"label": "POSITIVE",
"score": 0.9998
}Error Response
{
"error": "Missing or invalid query parameter: text",
"code": "INVALID_TEXT"
}Error Codes
400- Missing or invalidtext(INVALID_TEXT)502- Workers AI model run failed (AI_ERROR)
Use Cases
- Score customer feedback and reviews at the edge
- Filter or route messages by sentiment in real time
- Learn Workers AI classification models in a stateless Worker
- Build moderation or analytics pipelines without external ML APIs
Limitations
- Workers AI is subject to usage limits by plan
- Input text length is capped
- Accuracy varies on very short, sarcastic, or multilingual text
Deployment
Deploy
Enable the Workers AI binding (AI) in your Worker settings. The deploy button configures this automatically via wrangler.json. Requires a Cloudflare account with Workers AI enabled.
Test your deployment
curl "https://your-worker.workers.dev/sentiment?text=This%20pizza%20is%20great!"Local Development
cd apps/experiments/sentiment-analyzer
npm install
npm run devTest locally:
curl "http://localhost:8787/sentiment?text=This%20pizza%20is%20great!"Cloudflare Features Used
- Workers - Edge compute runtime
- Workers AI -
@cf/huggingface/distilbert-sst-2-int8sentiment classification model