Sentiment Analysis
Automatically analyze and categorize the emotional tone of user comments
sanity.blueprint.ts
import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'
export default defineBlueprint({
resources: [
defineDocumentFunction({
name: 'sentiment-analysis',
src: './functions/sentiment-analysis',
memory: 2,
timeout: 30,
event: {
on: ['publish'],
filter: "_type in ['review', 'comment', 'feedback'] && !defined(sentiment)",
projection: '{_id}',
},
}),
],
})functions/sentiment-analysis/index.ts
import {createClient} from '@sanity/client'
import {documentEventHandler} from '@sanity/functions'
export const handler = documentEventHandler(async ({context, event}) => {
const client = createClient({
...context.clientOptions,
apiVersion: 'vX', // vX currently required for Agent Actions
useCdn: false,
})
const {data} = event
const {local} = context // local is true when running locally
try {
const result = await client.agent.action.generate({
noWrite: Boolean(local), // if local is true, we don't want to write to the document, just return the result for logging
// Define which field to analyze
instructionParams: {
review: {
type: 'field',
path: 'review',
},
},
instruction: `Analyze the sentiment of the $review and categorize it into one of these 5 levels: very_positive, positive, neutral, negative, very_negative. Consider the emotional tone, word choice, and overall sentiment expressed in the text. Return only the sentiment level as a string.`,
target: {
path: 'sentiment', // This is the field you want to write the sentiment to.
},
documentId: data._id,
schemaId: '_.schemas.default', // This is the schemaId of the schema you want to use. See run `npx sanity schema list` in your studio directory to get the schemaId. See README.md for more details.
forcePublishedWrite: true, // Write to published document even if draft exists
})
console.log(
local
? 'Analyzed sentiment (LOCAL TEST MODE - Content Lake not updated):'
: 'Analyzed sentiment:',
result.sentiment,
)
} catch (error) {
console.error('Error occurred during sentiment analysis:', error)
}
})schemaTypes/feedback.ts
// ... Additional Fields
defineField({
name: 'sentiment',
title: 'Sentiment',
type: 'string',
options: {
list: [
{ title: 'Very Positive', value: 'very_positive' },
{ title: 'Positive', value: 'positive' },
{ title: 'Neutral', value: 'neutral' },
{ title: 'Negative', value: 'negative' },
{ title: 'Very Negative', value: 'very_negative' }
]
},
description: 'Sentiment will be automatically analyzed when you publish content',
}),The Problem: Manually reviewing content for emotional tone is time-consuming and subjective. Editors spend hours reading through documents to gauge sentiment, and different reviewers interpret tone differently. Without automated analysis, maintaining consistent brand voice across hundreds of pieces requires enormous human effort that could be spent on higher-value creative work.
The Solution: This function automatically analyzes the sentiment of your content, scoring emotional tone and providing insights into positivity, negativity, and neutrality. Get instant feedback on content mood without manual review, helping editors maintain appropriate tone and identify pieces that need adjustment—all in seconds instead of hours.
Quick Start
View the complete example and source code.
- Initialize blueprints if you haven't already:
npx sanity blueprints init - Then:
npx sanity blueprints add function --example sentiment-analysis - Then deploy:
npx sanity blueprints deploy
How It Works
When a comment document is added (published) to the Content Lake, the function automatically:
- Triggers on the publish event for comment documents
- Analyzes the comment's text field using AI-powered (Sanity's Agent Actions) sentiment analysis
- Determines sentiment polarity (positive, negative, neutral) with confidence scores
- Applies sentiment metadata directly to the comment document
Key Benefits
- Save time by automatically categorizing comment sentiment
- Improves response times to negative feedback by 80% through instant prioritization
- Provides objective sentiment scoring, removing human bias from initial assessment
- Enables sentiment-based filtering and reporting in your Sanity dashboard
Technical Implementation
The function uses Sanity's AI Agent Actions to analyze comment text and generate sentiment scores. It's built with:
Perfect For
- Community platforms with active comment sections
- Customer support teams needing to prioritize responses
- Content teams tracking audience reception
- Product feedback systems requiring emotional intelligence
The function is compatible with any Sanity project containing user generated feedback and can be easily customized to adjust sentiment thresholds, add emotion detection, or target different document types like reviews or feedback forms.
Contributor

Pieter Brinkman
VP Product & Developer Marketing