Pieter Brinkman
VP Product & Developer Marketing
Automatically analyze and categorize the emotional tone of user comments
import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'
export default defineBlueprint({
resources: [
defineDocumentFunction({
type: 'sanity.function.document',
name: 'sentiment-analysis',
src: './functions/sentiment-analysis',
memory: 2,
timeout: 30,
event: {
on: ['publish'],
filter: "_type in ['review', 'comment', 'feedback'] && !defined(sentiment)",
projection: '{_id}',
},
}),
],
})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)
}
})// ... 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.
npx sanity blueprints initnpx sanity blueprints add function --example sentiment-analysisnpx sanity blueprints deployHow It Works
When a comment document is added (published) to the Content Lake, the function automatically:
Key Benefits
Technical Implementation
The function uses Sanity's AI Agent Actions to analyze comment text and generate sentiment scores. It's built with:
Perfect For
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.
VP Product & Developer Marketing