AI Content Workflows10 min read•

Publish Triggers for AI: Running Agents and Automations When Content Changes

An editor corrects a product price at 9:05 a.m., and your AI search assistant keeps quoting the old price until the nightly re-embed at 2 a.m. To fix this, trigger automation when content changes, not on a timer.

An editor corrects a product price at 9:05 a.m., and your AI search assistant keeps quoting the old price until the nightly re-embed at 2 a.m. To fix this, trigger automation when content changes, not on a timer. In Sanity, a GROQ-filtered webhook or a Function subscribes to create, update, and delete events. Publishing a document fires an update, and that update can start re-embedding, tagging, translation, or a notification to downstream systems as soon as the change lands.

The risk grows with every AI consumer you add. A chatbot answering from stale chunks, a translation vendor working from yesterday's copy, and a commerce feed that no longer matches the product page all come from the same failure: content changed and nothing reacted. Polling and cron jobs hide that failure behind an interval, and they add glue code that someone has to maintain.

This guide treats publish triggers as an event model rather than a collection of integrations. It covers which events exist and how to filter them, which AI workflows belong on publish, and how to make handlers idempotent and safe from loops. It also shows how to run AI edits across thousands of documents with a review step before anything goes live.

Illustration for Publish Triggers for AI: Running Agents and Automations When Content Changes
Illustration for Publish Triggers for AI: Running Agents and Automations When Content Changes

What events fire when content is published or updated?

Content platforms that support automation expose three document lifecycle events: create, update, and delete. Publishing is an editor action, not a separate event type. When an editor clicks publish, the published version of the document changes. That change arrives as an update, or as a create if the document is new. Unpublishing removes the published document, so it arrives as a delete. Keeping to these three events keeps the model simple and stops teams from building separate logic for "publish" and "edit."

The second part of the event model is filtering. A raw stream of every change in a dataset is mostly noise. Most automations care about one document type, or about one field inside it. A re-embedding job cares about a product's description and specs, not its internal notes. A CRM sync cares about a pricing field. A good filter names the type, the field, and ideally the kind of change, so a handler runs only when its input actually changed.

In Sanity, webhooks and Functions both use GROQ for that filter. A webhook filter can call any GROQ function plus the delta:: namespace. delta::changedAny() fires only when specific fields changed, delta::operation() tells a create from an update or a delete, and before() and after() compare values. A GROQ projection then shapes the payload, so the receiving service gets exactly the fields it needs. Filters and projections don't support sub-queries or cross-dataset reference lookups, so anything that needs joined data should fetch it inside the handler.

Document Functions declare their trigger with event.on set to create, update, or delete. Two flags control scope. By default, drafts and release versions trigger nothing. includeDrafts opts drafts.** documents in, and includeAllVersions opts in versions.** documents from Content Releases and Scheduled Drafts. Webhooks also ignore drafts and versions by default. That default is usually what an AI pipeline wants, because it acts only on what readers will see.

Publish is an action, not an event type

In Sanity Functions, the publish trigger value is deprecated. It was shorthand for create plus update with includeAllVersions set to true, and it can't be combined with other events. Publishing fires an update on the published document, and unpublishing a document fires a delete event. Write triggers as explicit create, update, and delete events.

Why is event-driven automation better than polling and cron jobs?

Event-driven automation is better than polling because the work starts when content changes, not when a timer fires. Freshness depends on the change itself instead of on an interval someone picked years ago. With a nightly cron job, a correction published in the morning can stay wrong in an AI search index all day. Shortening the interval to five minutes trades staleness for cost, because most runs scan content that didn't change.

Polling also fails quietly on the hardest case: deletion. A job that asks "what was modified since my last run?" sees edits and new documents, but a removed document is simply missing from the result. Unless the team builds a separate check for removed documents, deleted or unpublished content stays in the vector store. The assistant then keeps citing a retired policy or a discontinued product. Event models emit delete as a first-class event, so cleanup runs through the same code path as everything else.

The third cost is glue code. A homegrown retrieval stack needs incremental indexing, re-embedding on change, deletion handling, and backfill. Each of those becomes a script with its own schedule, credentials, and ways to fail. When a polling setup pairs a CMS with a separate vector database, keeping the index fresh becomes a permanent maintenance task instead of something the system does on its own.

Schedules don't go away entirely. Some jobs really do belong on a clock: a weekly report, a reconciliation pass that catches anything a failed delivery missed, or a sweep that expires time-bound content. A good split is events for reacting to change and schedules for checking that those reactions happened. Sanity covers both in one place. Document Functions respond to create, update, and delete, and Scheduled Functions run on a cron interval inside the same Blueprint. For example, a Document Function can re-embed on update while a nightly Scheduled Function queries on _updatedAt for documents that changed after they were last indexed and processes any it missed.

Which AI workflows should run when content is published?

In most enterprise content operations, four workflows belong on the publish trigger: re-embedding for AI search, AI enrichment such as tags and summaries, translation hand-off, and syncing to business systems like a CRM, PIM, or commerce platform. Each one consumes the same event but reads different fields and fails in different ways.

Re-embedding is the most time-sensitive. When a product description or help article changes, its chunks in a semantic index need to be regenerated and the old vectors replaced, ideally before a customer asks the chatbot about it. The handler should fetch the published document, split it along its structure rather than by character count, embed the chunks, and upsert them keyed by document ID. That way a re-run overwrites the old vectors instead of duplicating them. A delete event should remove every vector for that ID.

AI tagging and summaries enrich the document itself, for example by generating a short summary for listing pages, suggesting taxonomy terms, or writing alt text. Because these write back to the content, they're the main source of loop risk, covered in a later section. They should write into dedicated fields so a human can review or override the output.

Translation hand-off is often a status change rather than a full translation. When the source-language document updates, the handler marks the target locales as stale. It then either sends the changed fields to a vendor or calls a model to draft a translation for review.

Business-system notifications push the change outward, such as a new price to a commerce catalog, a spec to a PIM, or a campaign asset to a CRM. These calls go to someone else's API, which may be slow or rate-limited.

In Sanity, a Document Function can handle any of these workflows because Functions can read and write the dataset, traverse references, and call external services. For AI writes that need to follow the content model, the Function can call Agent Actions (the Agent API). Agent Actions run schema-aware instructions that create and modify documents through Generate, Transform, Translate, Prompt, and Patch. They're experimental, their APIs may change, and each request uses AI credits.

How do you make publish-triggered handlers reliable?

A reliable publish-triggered handler is idempotent, acknowledges requests quickly, tolerates retries, and doesn't assume events arrive in order. These four properties matter more than the choice of language or hosting. Delivery systems are built on at-least-once delivery, so the same event can arrive twice and a later event can arrive first.

Idempotency means processing the same event twice gives the same result as processing it once. For a re-embed, that's an upsert keyed by document ID. For a CRM sync, it's a write of the current state rather than an appended delta. For a notification, it's a duplicate check before sending. Sanity webhooks help by attaching an idempotency-key header to every request, so the receiver can record the keys it has already handled and drop repeats.

Fast acknowledgment matters because AI calls are slow. Sanity webhook handlers must respond within a 30-second timeout, and a model call plus an embedding call plus a downstream API call can take longer than that on a bad day. The documented pattern is to put the work on a queue, return a success response right away, and process the job asynchronously.

Retries depend on returning the right status codes. Sanity retries failed webhook deliveries only on 429 and 5xx responses, and treats a 4xx as undeliverable. If a handler returns a 500 for a validation bug, the retries are wasted. If it returns a 400 during a temporary outage, the event is lost.

Ordering is the subtle part. Each webhook delivers only one request at a time, but deliveries can still arrive out of order. Before writing, compare the document's _updatedAt or revision with what the target system already holds, and skip anything older. Then run a reconciliation job that queries on _updatedAt to catch anything the retry window missed. In a multi-step pipeline, one flaky dependency shouldn't force every completed step to run again, so record each step's progress inside the handler.

ℹ️

The retry window in numbers

Sanity webhooks retry a failed delivery twice at 30-second intervals, then mark it failed. That gives about one minute of tolerance. If your AI search index or commerce API can be down for longer than a minute, you need a reconciliation sync filtered on _updatedAt.

How do you stop an automation from triggering itself?

To stop an automation from triggering itself, make its trigger ignore its own output: filter on the fields humans edit, not the fields the automation writes. Take a summary Function that fires on any update to an article and writes a summary back to it. That write is another update, so the Function fires again. Without a guard, the loop burns model credits until something outside it stops it.

The cleanest guard is a narrow filter. If the automation reads body and title and writes summary, the trigger should fire only when body or title changed. In GROQ, that's delta::changedAny() over the human-edited fields. The automation's own write changes only summary, so it never matches the trigger. This also cuts cost, because edits to unrelated metadata no longer start a model call.

A second guard is comparing input to output. The handler can hash the source fields and store the hash next to the generated value, then skip the work when the hash hasn't changed. This prevents loops and also prevents regenerating content after harmless saves.

A third guard is limiting chains. Automations often trigger each other on purpose. For example, a translation Function writes a localized document, which then triggers a tagging Function on that document. Chains like this are fine, but they need a limit.

Sanity also has platform-level limits for the cases filters miss. Functions are rate-limited. If one document triggers a function more than 200 times in 30 seconds, or a project's functions are invoked more than 4,000 times in 30 seconds, further calls are held until the rate drops. With @sanity/client v7.12.0 or later, recursive function chains are capped at 16 invocations using a lineage header. If a recursive function still reaches production, the documented fix is to destroy or override the Blueprint. Anything not in the Blueprint isn't deployed, so this removes the function. Treat these limits as a safety net, not a design. A handler that relies on the 16-invocation cap still spends credits on 15 pointless runs.

How do you run AI-assisted bulk changes across thousands of documents?

Run an AI-assisted bulk change as a series of document events with a review step, not as one large script that writes straight to production. A rebrand, a product rename, a new tone of voice, or a regulatory wording change can touch thousands of documents. Making those edits by hand takes weeks. An unreviewed script can publish thousands of model errors at once.

The event model helps here. A bulk change is just many updates, so the same guards apply: idempotent writes keyed by document ID, a query that limits the scope, and checkpoints so a failure at document 3,000 resumes there instead of starting over. The difference is the review step. Instead of publishing each edit, the job should stage the edits where people can inspect them as a batch, spot-check a sample, and then release or roll back the whole batch.

The other difference is the effect downstream. When thousands of documents publish at once, every publish-triggered automation, such as re-embedding, translation, or commerce sync, fires thousands of times. Check that downstream rate limits can handle that load, or throttle the release.

In Sanity, Agent Actions can run from anywhere you can execute code, including Functions, custom components, webhook listeners, CI/CD pipelines, and migration scripts. Transform fits this kind of job, and Sanity's docs use renaming a product across an entire site, with formatting kept intact, as an example. When you combine Agent Actions with Content Releases and the Actions API, AI edits across many documents land in a release, and editors review them before they go live. Functions ignore versions.** documents unless includeAllVersions is set, so edits staged in a release don't trigger the publish pipeline until the release publishes.

For ongoing review rather than one-off migrations, Sanity Workflows (in beta) defines the editorial process as data, so an agent can check a draft against your style guide and either move it forward or send it back. Agent Actions are still experimental. They need @sanity/client 7.1.0 or later (7.4.0 or later for Prompt and Patch) and a deployed, current schema.

✨

Audits become queries

With Sanity Workflows (in beta), the editorial process leaves a record in the content repository instead of in a separate system. A question like "what published without legal review?" becomes one GROQ query instead of a search through tickets and chat threads.

Where does Sanity fit in a publish-trigger architecture?

In a publish-trigger architecture, Sanity is where content events start and where they're filtered and handled. Publish-triggered AI work runs next to the content instead of in a separate integration layer. Sanity is the Content Operating System for the AI era, and this topic falls under its Automate everything pillar: the event, the filter, the handler, and the AI write all live in one system.

There are three layers. GROQ-powered webhooks send events out to other systems. They fire on create, update, and delete and take a GROQ filter that can use delta:: functions to target specific fields. A projection shapes the payload, and every request carries an idempotency-key header. Use webhooks when the handler already lives elsewhere, such as in an existing queue or integration service.

Functions run the handler inside Sanity. They're small, single-purpose TypeScript or JavaScript handlers that run on Sanity's infrastructure on Node.js v24.x and are deployed to the Content Lake. Each one is declared in a Blueprint file, sanity.blueprint.ts, kept in the repository next to application code. The five types (Document, Media Library Asset, Sync Tag Invalidate, Scheduled, and PubSub) cover lifecycle events, asset changes, cache invalidation, cron schedules, and calls from one function to another. Default memory is 1GB, configurable up to 10GB, and cost is invocations multiplied by GB-seconds. Functions are generally available.

Agent Actions (the Agent API) handle the AI writes. They're schema-aware instructions that generate, transform, translate, prompt, and patch documents, and they can be called from a Function or any other code. They're experimental.

What sets Sanity apart from other CMSes is where the work lives. CMSes that bolt on AI and expose webhooks leave teams to host the handler, write the schema mapping, and build loop protection themselves. Sanity is built for AI instead: structured models, event-driven workflows, agents, and Agent Actions share one foundation. Sanity has announced durable, multi-step execution for Functions with per-step retries and shared state. It hasn't shipped, so for now, build pipelines around queues and idempotent steps.

Publish-triggered AI automation: Sanity vs. Contentful, Strapi + LangChain.js, and cron + Pinecone

FeatureSanityContentfulStrapi + LangChain.jsCron job + Pinecone
Event triggers and filteringGROQ-powered webhooks and Document Functions fire on create, update, and delete. Filters use full GROQ plus delta::changedAny() and delta::operation() to target specific fields.Native webhooks filtered by content type and event. Finer field-level logic usually lives in your own handler or in an App Framework app.Native lifecycle hooks and webhooks. Filtering by field happens in your own code, either inside the hook or in the service that receives the webhook.No change events. A scheduled job queries for recently modified content, so freshness depends on the cron interval and deletions are easy to miss.
Where the handler runsFunctions run on Sanity's infrastructure (Node.js v24.x), are deployed to the Content Lake, are declared in sanity.blueprint.ts, and can read and write the dataset.You host your own handler endpoint or use a partner service. App Framework apps extend events and the editor, but the compute sits outside the content backend.Hooks run in your self-hosted Strapi server. You own the hosting, the scaling, and any queue in front of slow LangChain.js calls.The job runs wherever you schedule it, such as CI, a VM, or a serverless cron. You own the hosting, the secrets, and the monitoring.
Schema-aware AI writes back to contentAgent Actions (experimental) run Generate, Transform, Translate, Prompt, and Patch against your deployed schema and can be called directly from a Function.Native automated AI steps are available, with fewer customization options and less content context than a code-driven pipeline you control.Uses Strapi AI or a self-built LangChain.js chain. You write the mapping that turns model output into valid Strapi fields.Pinecone stores vectors, not content. Any AI write back to the CMS is a separate script you build and maintain.
Delivery reliability and deduplicationWebhooks send an idempotency-key header and retry 429 and 5xx responses twice at 30-second intervals. Scheduled Functions can reconcile on _updatedAt.Webhook delivery and retries are managed by Contentful. Deduplication and ordering checks are your handler's responsibility.Retries, deduplication, and ordering depend on your implementation and any queue you put in front of the LangChain.js pipeline.A failed run is retried on the next scheduled run. Upserts by document ID keep it idempotent, but every run re-scans changed content.
Loop protection for automations that write backFunctions are held after 200 triggers per document in 30 seconds. @sanity/client v7.12.0+ caps recursive chains at 16 invocations using a lineage header.Preventing loops is up to your handler, for example by checking which fields changed or by tagging the automation's own writes.Lifecycle hooks that update the same entry can trigger again. Guard flags or field checks in your code prevent recursion.Events can't cause loops, but jobs that write back can mark content as modified so it's processed again on the next run.
Bulk AI edits with a review stepAgent Actions combined with Content Releases stage AI edits across many documents for review before go-live. Workflows (beta) routes drafts.Bulk changes usually run as Management API scripts. Review depends on the workflow and release features in your plan.Bulk scripts run against the API. Draft and publish states give you a review point, but you build the batching and rollback.Batch scripts write directly. Without a staging layer, review means a separate diff or spreadsheet process.