> For AI agents: the complete Sanity documentation index is available at [https://www.sanity.io/docs/llms.txt](https://www.sanity.io/docs/llms.txt).

# Cookbook: AI content pipeline

An AI content pipeline built on Workflows: effect handlers call generation APIs while editors approve results through workflow actions.

> [!WARNING]
> Early access
> Workflows is in early access, built in public. Read [How early access works](https://www.sanity.io/docs/workflows/prerelease) before you rely on it.



In this pipeline, an AI agent writes the draft and automated checks review it. A person steps in only when a check flags the piece. The pipeline runs in five stages:

![Workflow stages: Drafting leads to Automated checks. Flagged work goes through Human verification and may return to Drafting; clean or approved work proceeds through Publishing to Published.](https://cdn.sanity.io/images/3do82whm/next/57891f6670eb4af6cb570bc553cf0ea132fab177-3075x474.png)

1. **Drafting**: a triggered action queues an AI effect whose handler calls the Agent Actions `generate` action to write the [draft](https://www.sanity.io/docs/content-lake/drafts-and-versions). When the effect finishes, a second triggered action marks the work done.
2. **Checks**: a triggered action queues check effects (Agent Actions `prompt`) for brand voice, SEO, links, and facts.
3. **Verification**: the engine moves the instance into this stage only when a check flagged the piece. A person approves the piece or sends it back. Pieces that pass every check go straight to publishing.
4. **Publishing**: triggered actions queue an effect that publishes the [document](https://www.sanity.io/docs/content-lake/documents), then an effect that writes an idempotent notification outbox record.
5. **Published**: the final stage. Reaching it completes the instance, so the stage has no activities.

## Before you get started

- **Packages**: `@sanity/workflows`, [`@sanity/client`](https://www.sanity.io/docs/apis-and-sdks/js-client-getting-started) (v7.8.2+, the Prompt action needs it), and, for the generated runtime, `@sanity/functions` and `@sanity/blueprints`.
- **A deployed schema and its schemaId**: Agent Actions write through your schema ([schema deployment](https://www.sanity.io/docs/apis-and-sdks/schema-deployment)).
- **Tokens and clients**: an editor token for the content [dataset](https://www.sanity.io/docs/content-lake/datasets) (Agent Actions and publishing), plus the engine’s own client.
- **Datasets**: the content dataset that holds the articles, and usually a separate `workflows` dataset for the engine’s instances. One dataset also works. The subject is a [global document reference](https://www.sanity.io/docs/workflows/global-document-references), so it records which project and dataset the article lives in.

## Define the workflow

The whole pipeline is one `defineWorkflow` call:

**ai-content-pipeline.ts**

```typescript
import {
  defineAction,
  defineActivity,
  defineField,
  defineStage,
  defineTransition,
  defineWorkflow,
} from '@sanity/workflows/define'

const anyCheckFailed =
  "$effectStatus['brand-voice'] == 'failed' || $effectStatus['seo'] == 'failed' || " +
  "$effectStatus['link-check'] == 'failed' || $effectStatus['fact-check'] == 'failed'"

export const aiContentPipeline = defineWorkflow({
  name: 'ai-content-pipeline',
  title: 'AI content pipeline',
  initialStage: 'drafting',
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      initialValue: {type: 'input'},
      required: true,
    }),
    defineField({type: 'actor', name: 'verifiedBy'}),
    defineField({type: 'string', name: 'revisionNote'}),
    defineField({type: 'boolean', name: 'brandVoiceFlagged'}),
    defineField({type: 'boolean', name: 'seoFlagged'}),
    defineField({type: 'boolean', name: 'linkFlagged'}),
    defineField({type: 'boolean', name: 'factFlagged'}),
  ],
  stages: [
    defineStage({
      name: 'drafting',
      title: 'Drafting',
      activities: [
        defineActivity({
          name: 'draft',
          title: 'Generate the draft',
          fields: [defineField({type: 'progress', name: 'generationProgress'})],
          actions: [
            defineAction({
              name: 'generate',
              title: 'Generate the draft',
              when: 'true',
              effects: [
                {
                  name: 'ai-draft',
                  bindings: {
                    subject: '$fields.subject._id',
                    revisionNote: '$fields.revisionNote',
                  },
                },
              ],
            }),
            defineAction({
              name: 'drafted',
              title: 'Draft ready',
              when: "$effectStatus['ai-draft'] == 'done'",
              status: 'done',
            }),
            defineAction({
              name: 'draft-failed',
              title: 'Draft generation failed',
              when: "$effectStatus['ai-draft'] == 'failed'",
              status: 'failed',
            }),
          ],
        }),
      ],
      transitions: [defineTransition({name: 'to-checks', to: 'checks'})],
    }),
    defineStage({
      name: 'checks',
      title: 'Automated checks',
      activities: [
        defineActivity({
          name: 'run-checks',
          title: 'Run the automated checks',
          actions: [
            defineAction({
              name: 'run',
              title: 'Run the checks',
              when: 'true',
              effects: [
                {name: 'brand-voice', bindings: {subject: '$fields.subject._id'}},
                {name: 'seo', bindings: {subject: '$fields.subject._id'}},
                {name: 'link-check', bindings: {subject: '$fields.subject._id'}},
                {name: 'fact-check', bindings: {subject: '$fields.subject._id'}},
              ],
            }),
            defineAction({
              name: 'checked',
              title: 'Checks complete',
              when:
                "$effectStatus['brand-voice'] == 'done' && $effectStatus['seo'] == 'done' && " +
                "$effectStatus['link-check'] == 'done' && $effectStatus['fact-check'] == 'done'",
              status: 'done',
            }),
            defineAction({
              name: 'checks-failed',
              title: 'Automated checks failed',
              when: anyCheckFailed,
              status: 'failed',
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({
          name: 'needs-human',
          to: 'verification',
          when:
            '$allActivitiesDone && ($fields.brandVoiceFlagged || $fields.seoFlagged || ' +
            '$fields.linkFlagged || $fields.factFlagged)',
        }),
        defineTransition({name: 'clean', to: 'publishing', when: '$allActivitiesDone'}),
      ],
    }),
    defineStage({
      name: 'verification',
      title: 'Human verification',
      fields: [defineField({type: 'string', name: 'decision'})],
      activities: [
        defineActivity({
          name: 'verify',
          title: 'Verify the flagged piece',
          actions: [
            defineAction({
              name: 'approve',
              title: 'Approve',
              status: 'done',
              ops: [
                {
                  type: 'field.set',
                  target: {field: 'decision'},
                  value: {type: 'literal', value: 'approve'},
                },
                {
                  type: 'field.set',
                  target: {field: 'verifiedBy'},
                  value: {type: 'actor'},
                },
              ],
            }),
            defineAction({
              name: 'send-back',
              title: 'Send back to redraft',
              status: 'done',
              params: [
                {
                  type: 'string',
                  name: 'note',
                  title: 'What to fix',
                  required: true,
                },
              ],
              ops: [
                {
                  type: 'field.set',
                  target: {field: 'decision'},
                  value: {type: 'literal', value: 'send-back'},
                },
                {
                  type: 'field.set',
                  target: {field: 'revisionNote'},
                  value: {type: 'param', param: 'note'},
                },
              ],
            }),
          ],
        }),
      ],
      transitions: [
        defineTransition({
          name: 'to-publishing',
          to: 'publishing',
          when: "$allActivitiesDone && $fields.decision == 'approve'",
        }),
        defineTransition({
          name: 'redraft',
          to: 'drafting',
          when: "$allActivitiesDone && $fields.decision == 'send-back'",
        }),
      ],
    }),
    defineStage({
      name: 'publishing',
      title: 'Publishing',
      activities: [
        defineActivity({
          name: 'publish',
          title: 'Publish and notify',
          actions: [
            defineAction({
              name: 'publish',
              title: 'Publish',
              when: 'true',
              effects: [{name: 'publish-doc', bindings: {subject: '$fields.subject._id'}}],
            }),
            defineAction({
              name: 'notify',
              title: 'Queue the notification',
              when: "$effectStatus['publish-doc'] == 'done'",
              effects: [{name: 'notify', bindings: {subject: '$fields.subject._id'}}],
            }),
            defineAction({
              name: 'finished',
              title: 'Published and notification queued',
              when:
                "$effectStatus['publish-doc'] == 'done' && $effectStatus['notify'] == 'done'",
              status: 'done',
            }),
            defineAction({
              name: 'publishing-failed',
              title: 'Publishing automation failed',
              when:
                "$effectStatus['publish-doc'] == 'failed' || $effectStatus['notify'] == 'failed'",
              status: 'failed',
            }),
          ],
        }),
      ],
      transitions: [defineTransition({name: 'to-published', to: 'published'})],
    }),
    defineStage({name: 'published', title: 'Published'}),
  ],
})

```

![Workflow stages: Drafting leads to Automated checks. Flagged work goes through Human verification and may return to Drafting; clean or approved work proceeds through Publishing to Published.](https://cdn.sanity.io/images/3do82whm/next/57891f6670eb4af6cb570bc553cf0ea132fab177-3075x474.png)

The draft activity declares a `progress` field named `generationProgress`. It shows generation progress from 0 to 100 while the handler runs. The handler calls `ctx.setProgress(...)` before and after generation. A bare field name in a handler refers to the activity whose action queued the effect, so the value lands on the draft activity. See [Effects and runtimes](https://www.sanity.io/docs/workflows/engine).

The engine keeps each automated stage open until its effects finish. If an effect fails, the engine marks the activity failed and the instance stays in that stage, so you can see the failure.

Each check handler writes its verdict to a workflow field. The engine reads those fields in the transitions out of the checks stage to choose between publishing and human review. When a person sends the piece back, their note goes into the next draft generation.

## Write the effect handlers

Put each handler in its own file, next to a shared content client. A registry file maps the effect names in the definition to the handlers.

### Shared content client

The content client uses `apiVersion: 'vX'`, the experimental API version, because the Prompt action is experimental. The Generate and Prompt docs use the same version.

**content.ts**

```typescript
import {createClient} from '@sanity/client'
import {extractDocumentId} from '@sanity/workflows'

export const content = createClient({
  projectId: 'yourprojectid',
  dataset: 'production',
  apiVersion: 'vX',
  token: process.env.SANITY_EDITOR_TOKEN!,
  useCdn: false,
})

export const SCHEMA_ID = '_.schemas.production'

export function subjectId(params: Record<string, unknown>): string {
  if (typeof params.subject !== 'string') throw new Error('subject must be a GDR URI')
  return extractDocumentId(params.subject)
}

```

### Draft generation

**ai-draft.ts**

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {content, SCHEMA_ID, subjectId} from './content'

export const aiDraft: EffectHandler = async (params, ctx) => {
  const revisionNote = typeof params.revisionNote === 'string' ? params.revisionNote : ''
  await ctx.setProgress('generationProgress', 0)
  await content.agent.action.generate({
    schemaId: SCHEMA_ID,
    documentId: subjectId(params),
    instruction:
      'Write the article body from the brief in $brief. Keep it on-brand and well structured. ' +
      'Apply this review feedback when it is present: $revisionNote',
    instructionParams: {
      brief: {type: 'field', path: 'brief'},
      revisionNote,
    },
    target: {include: ['title', 'body']},
  })
  await ctx.setProgress('generationProgress', 100)
}

```

### Automated checks

**checks.ts**

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {content, subjectId} from './content'

type CheckVerdict = {flagged: boolean; reason: string}

export function requireCheckVerdict(value: unknown): CheckVerdict {
  if (
    typeof value !== 'object' ||
    value === null ||
    !('flagged' in value) ||
    typeof value.flagged !== 'boolean' ||
    !('reason' in value) ||
    typeof value.reason !== 'string'
  ) {
    throw new Error('check returned an invalid JSON verdict')
  }
  return {flagged: value.flagged, reason: value.reason}
}

const check =
  (question: string, verdictField: string): EffectHandler =>
  async (params) => {
    const verdict = requireCheckVerdict(
      await content.agent.action.prompt({
        instruction:
          `${question} Use $doc as the content. ` +
          'Respond in JSON: {"flagged": boolean, "reason": string}.',
        instructionParams: {
          doc: {type: 'document', documentId: `drafts.${subjectId(params)}`},
        },
        format: 'json',
      }),
    )
    return {
      ops: [
        {
          type: 'field.set',
          target: {scope: 'workflow', field: verdictField},
          value: {type: 'literal', value: verdict.flagged},
        },
      ],
    }
  }

export const brandVoice = check('Does this match our brand voice?', 'brandVoiceFlagged')
export const seo = check('Are the SEO basics (title, meta, headings) covered?', 'seoFlagged')
export const linkCheck = check('Are all links valid and unbroken?', 'linkFlagged')
export const factCheck = check(
  'Are the factual claims supported and free of hallucination?',
  'factFlagged',
)

```

### Publishing

**publish-doc.ts**

```typescript
import type {PublishAction} from '@sanity/client'
import type {EffectHandler} from '@sanity/workflows'
import {content, subjectId} from './content'

type PublishState = {
  draft?: {_id: string; _rev: string}
  published?: {_id: string}
}

type PublishClient = {
  action: (action: PublishAction) => Promise<unknown>
  fetch: <Result>(query: string, params: Record<string, string>) => Promise<Result>
}

function fetchPublishState(client: PublishClient, id: string): Promise<PublishState> {
  return client.fetch(
    `{
      "draft": *[_id == $draftId][0]{_id, _rev},
      "published": *[_id == $publishedId][0]{_id}
    }`,
    {draftId: `drafts.${id}`, publishedId: id},
  )
}

export async function publishDocument(client: PublishClient, id: string): Promise<void> {
  const before = await fetchPublishState(client, id)
  if (before.draft == null) {
    if (before.published != null) return
    throw new Error(`no draft exists for ${id}`)
  }

  try {
    await client.action({
      actionType: 'sanity.action.document.publish',
      publishedId: id,
      draftId: before.draft._id,
      ifDraftRevisionId: before.draft._rev,
    })
  } catch (error) {
    const after = await fetchPublishState(client, id)
    if (after.draft == null && after.published != null) return
    throw error
  }
}

export const publishDoc: EffectHandler = async (params) => {
  await publishDocument(content, subjectId(params))
}

```

### Notification outbox

**notify.ts**

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {content, subjectId} from './content'

export const notify: EffectHandler = async (params, ctx) => {
  const id = subjectId(params)
  await content.createIfNotExists({
    _id: `workflow-notification.${ctx.effectKey}`,
    _type: 'workflowNotification',
    kind: 'articlePublished',
    subjectId: id,
    createdAt: new Date().toISOString(),
  })
  ctx.log(`queued publication notification for ${id}`)
}

```

### Map effects to handlers

**effect-handlers.ts**

```typescript
import type {EffectHandler} from '@sanity/workflows'
import {aiDraft} from './ai-draft'
import {brandVoice, factCheck, linkCheck, seo} from './checks'
import {notify} from './notify'
import {publishDoc} from './publish-doc'

export {content} from './content'

export const effectHandlers: Record<string, EffectHandler> = {
  'ai-draft': aiDraft,
  'brand-voice': brandVoice,
  seo,
  'link-check': linkCheck,
  'fact-check': factCheck,
  'publish-doc': publishDoc,
  notify,
}

```

Learn more in the [Generate](https://www.sanity.io/docs/agent-actions/generate-cheatsheet) and [Prompt](https://www.sanity.io/docs/agent-actions/prompt-quickstart) docs (Prompt is experimental), and in the [Actions API](https://www.sanity.io/docs/content-lake/dispatch-actions) reference.

## Configure the engine

`createEngine` receives the Sanity client, the workflow resource, the environment `partition`, and the object that maps effect names to their handlers.

A reader model is the lowest stored-data model version an engine must support to read a definition. This workflow needs reader model 13, because its triggers read `$effectStatus`. Its required subject field alone would need 10. Upgrade every runtime that shares the workflow resource, then set `expectedMinReaderModel` to `13` and deploy. Follow the model-13 rollout in [Upgrade Workflows packages](https://www.sanity.io/docs/workflows/upgrade).

**engine.ts**

```typescript
import {createClient} from '@sanity/client'
import {createEngine, ENGINE_API_VERSION, type ParsedGdr} from '@sanity/workflows'
import {aiContentPipeline} from './ai-content-pipeline'
import {effectHandlers, content} from './effect-handlers'

// the engine's own client: the `workflows` dataset where instances live
const workflowClient = createClient({
  projectId: 'yourprojectid',
  dataset: 'workflows',
  apiVersion: ENGINE_API_VERSION, // any apiVersion satisfies createClient; the engine rebinds all its own traffic onto ENGINE_API_VERSION
  token: process.env.SANITY_AUTH_TOKEN,
  useCdn: false,
})

export const engine = createEngine({
  client: workflowClient,
  workflowResource: {type: 'dataset', id: 'yourprojectid.workflows'},
  partition: 'prod',
  effects: {handlers: effectHandlers},
  // serving 'production' declares it in the deployment's ref surface (admitting the caller-supplied subject ref) and routes subject reads onto the editor-token content client
  resourceClients: (parsed: ParsedGdr) =>
    parsed.scheme === 'dataset' && parsed.dataset === 'production' ? content : undefined,
})

// Deploy the definition once (a setup script or CI step).
await engine.deployDefinitions({
  expectedMinReaderModel: 13,
  definitions: [aiContentPipeline],
})
```

## Run the pipeline autonomously

Generate the runtime with [Generate Functions from your workflow definitions](https://www.sanity.io/docs/workflows/generate-functions). Because the pipeline has effects, the generator creates a drain. The generated heartbeat re-queues effects that no drain picked up. Point each generated stub in `effect-handlers/` at its handler from this recipe’s `effectHandlers`.

The drain Function runs only when an unclaimed effect is waiting. In one `drainEffects()` call, the engine runs every queued effect it can claim. Each finished effect can move the instance forward, and the same call picks up any effect that queues as a result.

Set the drain’s timeout long enough for the longest full drain. A slow effect, such as `ai-draft`, can get its own drain: set `runtime: {kind: 'function', timeout}` on the effect, in whole seconds from 1 to 900. See [runtime hosting configuration](https://www.sanity.io/docs/workflows/deployments-and-resources). Handlers must be safe to run more than once, because the engine can run a handler again after an earlier claim expires.

## Deploy it

The CLI reads the deployment from `sanity.workflow.ts`. This config acknowledges reader model 13, like the `engine.deployDefinitions` call. Upgrade every runtime sharing the workflow resource before you deploy it:

**sanity.workflow.ts**

```typescript
// sanity.workflow.ts
import {defineWorkflowConfig} from '@sanity/workflows/define'
import {aiContentPipeline} from './ai-content-pipeline'

export default defineWorkflowConfig({
  deployments: [
    {
      name: 'production',
      partition: 'prod',
      expectedMinReaderModel: 13,
      workflowResource: {type: 'dataset', id: 'yourprojectid.workflows'},
      definitions: [aiContentPipeline],
    },
  ],
})
```

Log in and deploy:

**npm**

```shell
npx sanity@latest login
npx sanity-workflows deploy
```

**pnpm**

```shell
pnpm dlx sanity@latest login
pnpm dlx sanity-workflows deploy
```

**yarn**

```shell
yarn dlx sanity@latest login
yarn dlx sanity-workflows deploy
```

**bun**

```shell
bunx sanity@latest login
bunx sanity-workflows deploy
```

Once the shared runtimes can read model 13, regenerate with `npx @sanity/workflows-cli blueprints generate` and deploy both stacks as [Generate Functions from your workflow definitions](https://www.sanity.io/docs/workflows/generate-functions) describes.

## Run it

Start an instance on an article:

**start-pipeline.ts**

```typescript
import {refDataset} from '@sanity/workflows'
import {engine} from './engine'

// Commission a piece. `subject` is a draft document carrying a `brief` field.
const started = await engine.startInstance({
  definition: 'ai-content-pipeline',
  initialFields: [
    {type: 'subject', name: 'subject', value: refDataset({projectId: 'yourprojectid', dataset: 'production', documentId: 'post-1', type: 'post'})},
  ],
})
const instanceId = started.instance._id // startInstance returns an OperationResult

// From here the Function drives it: it drafts, runs the checks, and either auto-publishes
// a clean piece or routes a flagged one to a person, who runs:
//   await engine.fireAction({instanceId, activity: 'verify', action: 'approve'})
```

After deployment, the generated drain Function calls `drainEffects`, and the engine runs each queued effect. After each finished effect, the engine advances the pipeline until it reaches a person or the final stage. Pieces that pass every check go straight to publishing.

This diagram follows a piece that a check flags and a person approves. A caller starts the instance. A Function calls the engine to run the automated effects. An editor approves through the engine. The engine makes every transition, and the Content Lake stores each state.

![A caller starts the article workflow. The engine persists Drafting, a Function drains generation and check effects, and an editor approves flagged work through the engine. The engine then transitions through Publishing to Published while the Content Lake persists each state.](https://cdn.sanity.io/images/3do82whm/next/963b2a2b04bb05ffaa91db32d183a1fd623a50fa-2800x2380.png)

## Adapting it

- **Use the Content Agent API** when drafting needs research, web search, or tools. It can replace the `ai-draft` handler; see [Content Agent API](https://www.sanity.io/docs/apis-and-sdks/content-agent-api).
- Add or remove checks by changing the effects, their completion condition, the verdict fields, and the fields read by the routing transition.
- **Confidence scores instead of pass/fail**: declare a number field, have the check write its score there, and gate `needs-human` on a threshold rather than a boolean.
- **Always show a human, but only enable approve once checks pass**: keep the verify activity on the path and gate it with a `requirements` entry instead of routing around it.

## Next steps

- [Cookbook](https://www.sanity.io/docs/workflows/cookbook) for the other examples and the runtime/enforcement guidance.
- [Effects and runtimes](https://www.sanity.io/docs/workflows/effects-and-runtimes) for `effects`, triggers, `bindings`, and field kinds.
- This recipe builds on the Sanity docs for [Agent Actions: Generate](https://www.sanity.io/docs/agent-actions/generate-cheatsheet), [Prompt](https://www.sanity.io/docs/agent-actions/prompt-quickstart), [Functions](https://www.sanity.io/docs/functions/functions-introduction), and the [Content Agent API](https://www.sanity.io/docs/apis-and-sdks/content-agent-api).
- [Test your workflows](https://www.sanity.io/docs/workflows/testing) to cover the pipeline’s gates and effect outcomes with the in-memory bench before deploying.

> [!NOTE]
> Visiting agent?
> Workflows has MCP tools that let an agent inspect, operate, author, validate, and deploy workflows. An agent host embeds these tools. Ask the person you work for whether your host [includes the Workflows tools](https://www.sanity.io/docs/workflows/mcp).



