Auto Summary Function

Official(made by Sanity team)

By Kevin Green

AI-Powered Content Summary from Long Form Content

schemaTypes/post.ts

defineField({
  name: 'autoSummary',
  title: 'Auto Summary',
  type: 'text',
  description: 'Summary will be automatically generated when you publish a post',
}),

functions/auto-summary/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',
    useCdn: false,
  })
  const {data} = event
  const {local} = context // local is true when running locally

  try {
    const result = await client.agent.action.generate({
      noWrite: local ? true : false, // if local is true, we don't want to write to the document, just return the result for logging
      instructionParams: {
        content: {
          type: 'field',
          path: 'body',
        },
      },
      instruction: `Based on the $content, write a summary no more than 250 words.`,
      target: {
        path: 'autoSummary',
      },
      documentId: data._id,
      schemaId: '_.schemas.default',
      forcePublishedWrite: true,
    })
    console.log(
      local
        ? 'Generated summary (LOCAL TEST MODE - Content Lake not updated):'
        : 'Generated summary:',
      result.autoSummary,
    )
  } catch (error) {
    console.error('Error occurred during summary generation:', error)
  }
})

sanity.blueprint.ts

import {defineBlueprint, defineDocumentFunction} from '@sanity/blueprints'

export default defineBlueprint({
  resources: [
    defineDocumentFunction({
      type: 'sanity.function.document',
      src: './functions/auto-summary',
      memory: 2,
      timeout: 30,
      name: 'auto-summary',
      event: {
        on: ['create', 'update'],
    filter:
         "_type == 'post' && (delta::changedAny(content) || (delta::operation() == 'create' && defined(content)))",
    projection: '{_id}',
      },
   }),
  ],
})

This Sanity Function solves a common content management challenge: the time-consuming task of summarizing long form content. Content creators could spend 5-10 minutes summarizing a completed article, which can lead reduced productivity in editorial workflows.

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 auto-summary

Then deploy: npx sanity blueprints deploy

How It Works

When a content editor publishes a new blog post without a summary, the function automatically:

  1. Triggers on the publish event for post documents without an existing summary
  2. Analyzes the post's content field using AI
  3. Generates a summary of the document body content (with some language directives and a word count)
  4. Applies the summary directly to the published document

Key Benefits

  • Saves 5-10 minutes per post by eliminating manual summary
  • Improves content readability through consistent summary language
  • Reduces editorial overhead for content teams

Technical Implementation

The function uses Sanity's AI capabilities to analyze the portable text content and generate contextually relevant summary. It's built with:

  • Event-driven architecture (triggers on document publish)
  • Smart filtering to only process posts without autoSummary
  • Direct document updates using Sanity's AI agent

Perfect For

  • Content-heavy sites with regular blog publishing
  • Teams looking to improve content generation
  • Editorial workflows needing automation

The function is compatible with any of Sanity's official "clean" templates and can be easily customized to adjust summary length, format, or target different document types.

Contributor

Official Recipes by Sanity

First Published Timestamp Function

Featured contribution
Official(made by Sanity team)

Automatically track when content was first published with a timestamp that sets once and never overwrites, providing reliable publication history for analytics and editorial workflows.

Knut Melvær
Go to First Published Timestamp Function

Automatically tag blog posts

Featured contribution
Official(made by Sanity team)

AI-powered automatic tagging for Sanity blog posts that analyzes content to generate 3 relevant tags, maintaining consistency by reusing existing tags from your content library.

Go to Automatically tag blog posts