Generate quick start
Get started with Generate by writing your first instructions to create and modify documents.
Experimental feature
This article describes an experimental Sanity feature. The APIs described are subject to change and the documentation may not be completely accurate.
Generate lets you programmatically run schema-aware AI instructions on Sanity documents. You can run instructions from anywhere you can execute code, such as cloud functions, webhook listeners, CI/CD pipelines, migration scripts, and more.
In this guide, you'll use Generate to create a document and write content based on your instructions. You'll use @sanity/client to create the instructions (you can also make requests using the HTTP API directly).
Prerequisites:
@sanity/clientv7.1.0 or later and an environment to run client requests.- In Node.js v23.6 or later, you can run the TypeScript examples in this guide without additional servers or build processes. Alternatively, you can use earlier versions with an experimental flag.
sanityCLI v3.88.0 or later.- A Sanity project for testing. The examples in this guide use details from the sample "Movies" studio schema that you can select when initializing a new project.
- A read/write API token to authenticate requests.
- A valid
projectIdanddatasetname.
Step 1: Obtain a schema ID
Generate requires an uploaded schema. If you've deployed recently, you can check for a list of uploaded schemas by running the schemas list command. If you don't see a schema or want to deploy the latest version, redeploy your studio to Sanity or deploy the schema.
npx sanity@latest schemas list
npx sanity@latest deploynpx sanity@latest schemas deploy
Copy the schema ID, which you'll need for making Agent Actions requests.
Learn more about schema deployment.
Step 2: Configure the client
Import and configure @sanity/client with the projectId, dataset, API token, and an apiVersion of vX.
import { createClient } from "@sanity/client";
export const client = createClient({
projectId: 'YOUR_PROJECT_ID',
dataset: 'production',
apiVersion: 'vX',
token: process.env.SANITY_API_TOKEN
})If you're already using the client elsewhere in an application, you can reuse its base configuration. If you need to adjust the token or the API version, use the withConfig method to create a new client based on your existing one. For example:
// ...
const generateClient = client.withConfig({
token: process.env.SANITY_API_TOKEN,
})Step 3: Create an instruction
Instructions describe the content to target and the actions to take upon that content. They can create new documents or update existing ones. In the simplest form, generate takes the following settings:
targetDocumentordocumentId: ThetargetDocumentsetting defines anoperation. SettingdocumentIdis shorthand for usingtargetDocumentwith theeditoperation.instruction: The instruction you want to send to Generate.schemaId: The ID of your schema.
In this example, you'll create an instruction that adds a new movie to your dataset.
Update the code to include the following instruction:
await client.agent.action.generate({
// Replace with your schema ID
schemaId: "YOUR_SCHEMA_ID",
// Tell the client to create a new 'movie' document type.
targetDocument: { operation: "create", _type: "movie" },
// Provide an instruction, or prompt.
instruction: "Write the details for a movie titled $title.",
// Optionally, provide any params for the instruction.
// You can access them with the $key syntax.
instructionParams: {
title: { type: "constant", value: "Sanity: The Content Operating System" },
},
});This code creates a new draft document of the movie type, then tells Generate to write details about the movie. In this case, rather than directly telling the AI in the instructions that the title should be "Sanity: The Content Operating System", instructionParams is used to pass it in as the $title parameter.
Gotcha
Depending on your schema, you may find that the instruction doesn't generate images or connect references. To enable these features, you'll need additional schema changes. See the linked guides to configure each feature.
Run the file with node instruction.ts, replacing the filename with the path to your own file. Generate adds a new movie titled "Sanity: The Content Operating System" to your dataset.
By default, the create operation creates a draft. Agent Actions never write to a published document unless you set forcePublishedWrite: true on the request. To create a published document, provide an _id to targetDocument in addition to the _type and operation, and set forcePublishedWrite: true. Providing a version ID as the _id creates a content release version instead.
Protip
You might wonder why this example uses instructionParams to pass variables instead of string interpolation or another way of building the instruction string. By using instructionParams and then passing them to the instruction with the $key syntax, Generate has more control over how it shapes and sends your requests to the LLMs.
Modify an existing document
To update an existing document, set the documentId or use the edit operation with targetDocument: { operation: "edit", _id: "DOCUMENT_ID" }.
This example uses the existing document details to rewrite the title. Obtain the document ID from your studio by selecting Inspect from the More options menu in the document title bar, querying the document in Vision Tool, or querying it with client.fetch().
const docId = "EXISTING_DOCUMENT_ID";
await client.agent.action.generate({
schemaId: "YOUR_SCHEMA_ID",
// documentId is equivalent to targetDocument: {operation: 'edit', _id: docId }
documentId: docId,
instruction: `
Update the title based on the details about the movie.
Use the information in $details to come up with the new title.
`,
instructionParams: {
details: {
type: "field",
path: "overview",
},
},
target: {
path: "title",
}
});In addition to swapping the targetDocument property for documentId, this example also has a new instructionParams.
As with the previous title example, you can name these keys whatever you like. The details key in this instance is a field type, and just like title in the earlier example, you can reference it in the instructions with a $ prefix ($details).
Field-type instruction parameters expect a path leading to fields in the document. In this case, it uses the overview field to read a summary of the movie that the instruction can use as context.
Another approach is to use a GROQ-type query and capture the whole or parts of other documents as context.
await client.agent.action.generate({
schemaId: "YOUR_SCHEMA_ID",
documentId: "EXISTING_DOCUMENT_ID",
instruction: `
Update the title so that it aligns closer to the other movie titles.
Use the information in $background to come up with the new title.
`,
instructionParams: {
background: {
type: "groq",
query: `*[_type == $type] | order(_createdAt desc)[0...20].title`,
params: {type: 'movie'},
},
},
target: {
path: "title",
}
});GROQ-type instruction parameters take a GROQ query and pass the result to the parameter. In this case, it passes the titles of other movie documents in your dataset.
Protip
If you want to pass an individual document, you can use the document type param. For example: thisDocument: { type: 'document', documentId: 'DOCUMENT_ID'}. If you omit the document ID, the parameter is set to the current document.
This example also introduces the target parameter, and its child path. Target lets you explicitly tell the instruction which fields to write to. Check out more examples of target in the Generate common patterns page.
When you run either of these examples, Generate responds with an updated document, including a new title based on other titles in your dataset.
Next steps
These examples run once, but you can loop over multiple documents, build multi-step workflows, and much more. These resources provide additional examples and details.
Create images with Generate
Configure your schema to enable image generation.
Enable references in Generate
Configure your schema to enable the API to connect references.
Generate common patterns
View common patterns and best practices.
Agent Actions
Send Agent Actions requests over HTTP instead of the client.