Workflows
Workflows are scenarios where the AI model has a single, well-defined task. The AI Toolkit includes these built-in workflows:
Below is the API reference for the methods that support these built-in workflows.
createProofreaderWorkflow (server-side utility)
Creates a ready-made workflow configuration for proofreading. Returns a system prompt and schemas for validating AI output.
The workflow expects a user prompt as a JSON object with:
content: The content of the document to be proofread (see the client-side setup section on how to obtain it)task: A string describing the task to completecontext: (Optional) Additional context or background information related to the task
Returns
systemPrompt(string): Ready-to-use system prompt that instructs the AI model on how to generate proofreading operationszodOutputSchema(ZodObject): Zod schema for validating the AI outputjsonOutputSchema(object): JSON schema for validating the AI output
The systemPrompt field contains an example ready-to-use prompt with sensible defaults. We encourage you to read it and modify it to fit your needs.
Example
import { createProofreaderWorkflow } from '@tiptap-pro/ai-toolkit-tool-definitions'
import { Output, streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
// Get the content from the API endpoint request
const { content } = apiEndpointRequest
// Create and configure the workflow
const workflow = createProofreaderWorkflow()
const result = streamText({
model: openai('gpt-5-mini'),
// System prompt
system: workflow.systemPrompt,
// User message with the content and the task
prompt: JSON.stringify({
content,
task: 'Correct all grammar and spelling mistakes',
context: 'This is a formal business document',
}),
output: Output.object({ schema: workflow.zodOutputSchema }),
// If you use gpt-5-mini, set the reasoning effort to minimal to improve the
// response time.
providerOptions: {
openai: {
reasoningEffort: 'minimal',
},
},
})createInsertContentWorkflow (server-side utility)
Creates a ready-made workflow configuration for inserting or replacing content. Returns a system prompt for the AI model.
The workflow expects a user prompt that is a JSON object with the following properties:
task: the task to completereplace: the HTML content to be replaced (optional)before: the HTML content before (optional)after: the HTML content after (optional)
Returns
systemPrompt(string): Ready-to-use system prompt that instructs the AI model on how to generate HTML content
The systemPrompt field contains an example ready-to-use prompt with sensible defaults. We encourage you to read it and modify it to fit your needs.
Example
import { createInsertContentWorkflow } from '@tiptap-pro/ai-toolkit-tool-definitions'
import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
// Get the task and selection from the API endpoint request
const { task, replace } = apiEndpointRequest
// Create and configure the workflow
const workflow = createInsertContentWorkflow()
const result = streamText({
model: openai('gpt-5-mini'),
// System prompt
system: workflow.systemPrompt,
// User message with the task and content in a JSON object
prompt: JSON.stringify({
task,
replace,
}),
// If you use gpt-5-mini, set the reasoning effort to minimal to improve the
// response time.
providerOptions: {
openai: {
reasoningEffort: 'minimal',
},
},
})
return result.toTextStreamResponse()proofreaderWorkflow
Applies a list of proofreading operations to the document.
Parameters
options(ProofreaderWorkflowOptions): Configuration optionshasFinished(boolean): Whether streaming has finished. Passfalsewhile operations are still streaming andtruefor the final call.operations(PartialProofreaderOperation[]): Array of proofreading operations.workflowId(unknown): Unique ID for this workflow runreviewOptions?(ReviewOptions): Control preview/review behavior. See available options.- In this method,
diffUtilityOptions.groupInlineChangesdefaults to2instead of1, so edits are shown as inline changes by default. mode: 'trackedChanges'is supported when the Tracked Changes extension is installed.
- In this method,
range?(Range): The range to apply the proofreading operations tofrom(number): Start positionto(number): End position
Returns (ProofreaderWorkflowResult)
doc(Node): The modified document after applying operationsoperationResults(OperationResult[]): Array of operation results, in the same order as the input operations. Each result contains:target(string): The target hash associated with the operation resultsuccess(boolean): Whether the operation was successfulerror(string | null): Error message if the operation failed, otherwisenull
Example
const toolkit = getAiToolkit(editor)
// Get the document in a format that allows the AI to make fast, efficient edits
const readResult = toolkit.tiptapRead()
const operations = await callApiEndpoint({ content: readResult.content })
// Apply proofreading corrections
const result = toolkit.proofreaderWorkflow({
hasFinished: true,
operations,
workflowId: 'proofread-123',
reviewOptions: {
mode: 'preview',
},
})createTiptapEditWorkflow (server-side utility)
Creates a ready-made workflow configuration for editing documents. Returns a system prompt and schemas for validating AI output.
The workflow expects a user prompt as a JSON object with:
content: The content of the document to be edited (obtained fromtiptapRead)task: A string describing the editing task to completecontext: (Optional) Additional context or background information related to the task
Returns
systemPrompt(string): Ready-to-use system prompt that instructs the AI model on how to generate edit operationszodOutputSchema(ZodObject): Zod schema for validating the AI output. This schema validates the streamedoperationsobject returned by your model.jsonOutputSchema(object): JSON schema for validating the AI output
Example
import { createTiptapEditWorkflow } from '@tiptap-pro/ai-toolkit-tool-definitions'
import { Output, streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
// Get the content and task from the API endpoint request
const { content, task } = apiEndpointRequest
// Create and configure the workflow
const workflow = createTiptapEditWorkflow()
const result = streamText({
model: openai('gpt-5-mini'),
system: workflow.systemPrompt,
prompt: JSON.stringify({ content, task, context }),
output: Output.object({ schema: workflow.zodOutputSchema }),
})tiptapEditWorkflow
Applies a list of edit operations to the document.
Parameters
options(TiptapEditWorkflowOptions): Configuration optionshasFinished(boolean): Whether streaming has finished. Passfalsewhile operations are still streaming andtruefor the final call.operations(PartialTiptapEditOperation[]): Array of edit operations. Each operation is an object with:type:'replace'|'insertBefore'|'insertAfter'target: The 6-character hash of the node (fromtiptapRead) or'doc'for entire documentcontent: HTML string with the content to insert
workflowId(unknown): Unique ID for this workflow runtiptapReadResult(TiptapReadResult): Result returned bytiptapRead, used for stale-read detection while applying edit operations.reviewOptions?(ReviewOptions): Control preview/review behavior.mode: 'trackedChanges'is supported when the Tracked Changes extension is installed.
streamingOptions?(StreamingOptions): Controls how streamed operations are applied.disableTypingEffect?(boolean): Disables the typing effect while streamed operations are applied.
tiptapEditHooks?(TiptapEditHooks): Hooks for intercepting and modifying operations. See the Tiptap Edit hooks guide for details.beforeOperation?((context: BeforeOperationContext) => BeforeOperationResult): Called before each operation is applied. Return{ action: 'accept' }to apply the operation (optionally withfragmentoroperationTypeoverrides), or{ action: 'reject', error }to skip it.
Returns (TiptapEditWorkflowResult)
doc(Node): The modified document after applying operationsoperationResults(OperationResult[]): Array of operation results, in execution order. Each result contains:target(string): The target hash associated with the operation resultsuccess(boolean): Whether the operation completed successfullyerror(string | null): Error message if the operation failed, otherwisenull
Example
const toolkit = getAiToolkit(editor)
// Get the document content
const readResult = toolkit.tiptapRead()
const operations = await callApiEndpoint({ content: readResult.content, task: 'Make the text more formal' })
// Apply edit operations
const result = toolkit.tiptapEditWorkflow({
hasFinished: true,
operations,
workflowId: 'edit-123',
tiptapReadResult: readResult,
reviewOptions: {
mode: 'preview',
},
})createEditThreadsWorkflow (server-side utility)
Creates a ready-made workflow configuration for managing comments and threads. Returns a system prompt and schemas for validating AI output.
The workflow expects a user prompt as a JSON object with:
content: The content of the document (obtained fromtiptapRead)threads: The existing threads in the document (obtained fromgetThreads)task: A string describing the comment management task to complete
Returns
systemPrompt(string): Ready-to-use system prompt that instructs the AI model on how to manage commentszodOutputSchema(ZodObject): Zod schema for validating the AI outputjsonOutputSchema(object): JSON schema for validating the AI output
Example
import { createEditThreadsWorkflow } from '@tiptap-pro/ai-toolkit-tool-definitions'
import { Output, streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
// Get the content, threads, and task from the API endpoint request
const { content, threads, task } = apiEndpointRequest
// Create and configure the workflow
const workflow = createEditThreadsWorkflow()
const result = streamText({
model: openai('gpt-5-mini'),
system: workflow.systemPrompt,
prompt: JSON.stringify({ content, threads, task }),
output: Output.object({ schema: workflow.zodOutputSchema }),
})getThreads
Retrieves all threads in the document with their comments and location information.
Returns (GetThreadsResult)
threadCount(number): The number of threads in the documentthreads(ThreadInfo[]): Array of thread information, each containing:id(string): The unique identifier of the threadcomments({ id: string; content: string }[]): Array of comments in the threadnodeRange?(string): The range of nodes where the thread is locateddocumentContent?(string): The HTML content where the thread is applied
Example
const toolkit = getAiToolkit(editor)
// Get all threads in the document
const result = toolkit.getThreads()
console.log(`Found ${result.threadCount} threads`)
result.threads.forEach((thread) => {
console.log(`Thread ${thread.id}: ${thread.comments.length} comments`)
})editThreadsWorkflow
Applies comment and thread operations to the document.
Parameters
options(EditThreadsWorkflowOptions): Configuration optionsoperations(string[][]): Array of comment operations as tuples.commentsOptions?(CommentsOptions): Options for comment operationsthreadData?(Record<string, any>): Extra metadata for created threadscommentData?(Record<string, any>): Extra metadata for created comments
Returns (EditThreadsWorkflowResult)
operations(EditThreadsOperationResult[]): Array of operation resultssuccess(boolean): Whether all operations were successful
Example
const toolkit = getAiToolkit(editor)
// Get document and threads
const { content } = toolkit.tiptapRead()
const { threads } = toolkit.getThreads()
const operations = await callApiEndpoint({ content, threads, task: 'Add review comments' })
// Apply comment operations
const result = toolkit.editThreadsWorkflow({
operations,
})
if (result.success) {
console.log('All comment operations completed successfully')
}createTemplateWorkflow (server-side utility)
Creates a ready-made workflow configuration for filling templates. Accepts an HTML template string (generated by the createHtmlTemplate method on the client), auto-extracts all template keys, and returns a system prompt and schemas for validating AI output.
The workflow expects a user prompt as a JSON object with:
task: A string describing what content to generate for the templatecontext: (Optional) Additional context or background information related to the task
Parameters
options(CreateTemplateWorkflowOptions): Configuration optionshtmlTemplate(string): The template as an HTML string, generated by thecreateHtmlTemplatemethod on the clientrequiredSlots?(string[]): Slot names the AI must fill. Unlisted slots are optional. When omitted, all slots are required. Pass an empty array to make all slots optional.requiredConditions?(string[]): Condition names the AI must evaluate. Unlisted conditions are optional. When omitted, all conditions are required. Pass an empty array to make all conditions optional.requiredAttributes?(string[]): Attribute key names the AI must set. Unlisted attributes are optional. When omitted, all attributes are required. Pass an empty array to make all attributes optional.
Returns
systemPrompt(string): Ready-to-use system prompt that instructs the AI model on how to fill the templatezodOutputSchema(ZodObject): Zod schema for validating the AI outputjsonOutputSchema(object): JSON schema for validating the AI output
Example
import { createTemplateWorkflow } from '@tiptap-pro/ai-toolkit-tool-definitions'
import { Output, streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
const { htmlTemplate, task } = apiEndpointRequest
const workflow = createTemplateWorkflow({ htmlTemplate })
const result = streamText({
model: openai('gpt-5-mini'),
system: workflow.systemPrompt,
prompt: JSON.stringify({ task, context }),
output: Output.object({ schema: workflow.zodOutputSchema }),
})
return result.toTextStreamResponse()templateWorkflow
Fills a Tiptap JSON template with AI-generated values and inserts the result into the editor. The template uses special attributes (_templateSlot, _templateIf, _templateAttributes, _templateFieldMetadata) to mark dynamic parts.
Parameters
options(TemplateWorkflowOptions): Configuration optionstemplate(Record<string, any>): The template in Tiptap JSON format (a doc node or fragment array)values(TemplateValues): AI-generated values to fill the template. Keys correspond to template attribute values.position?(Range | number): Where to insert the filled template. Default: entire document range.hasFinished?(boolean): Whether streaming has finished. When omitted, the method runs in non-streaming mode. Default:trueworkflowId?(unknown): Unique ID for this workflow run. When provided, enables streaming mode where the method tracks the insertion range across calls and replaces content progressively.preserveSlotAttr?(boolean): Whentrue, keeps_templateSlotattributes on nodes after filling. This allows identifying AI-filled content and re-filling template fields later. Default:falsereviewOptions?(ReviewOptions): Control preview/review behavior
Example
import { experimental_useObject as useObject } from '@ai-sdk/react'
import { getAiToolkit } from '@tiptap-pro/ai-toolkit'
import { z } from 'zod'
const templateSchema = z.object({}).passthrough()
const { submit, isLoading, object } = useObject({
api: '/api/template-workflow',
schema: templateSchema,
})
// Stream partial results in a useEffect
useEffect(() => {
if (!editor || !object) return
const toolkit = getAiToolkit(editor)
toolkit.templateWorkflow({
template: templateJson,
values: object as Record<string, unknown>,
position: 'document',
hasFinished: !isLoading,
workflowId,
})
}, [object, workflowId, editor, isLoading])createHtmlTemplate
Converts a Tiptap JSON template to an HTML string with template attributes preserved. The resulting HTML can be sent to the server where createTemplateWorkflow parses the template keys.
Since this is an AI Toolkit method, the editor schema is automatically available — you only need to pass the template.
Parameters
template(Record<string, unknown>): The template as Tiptap JSON (a doc node or fragment array)
Returns
- An HTML
stringwith lowercased template attributes (_templateslot,_templateif,_templateattributes,_templatefieldmetadata)
Example
const toolkit = getAiToolkit(editor)
const htmlTemplate = toolkit.createHtmlTemplate(templateJson)TemplateField
A Tiptap extension that adds template field attributes to all node types in the editor schema. Register this extension to enable template field support in the editor DOM (rendering, parsing, and CSS styling).
The extension adds four global attributes:
_templateSlot(string | null): Marks a node as a content placeholder. When the template is filled, the node is replaced with AI-generated HTML._templateIf(string | null): Marks a node as conditionally included. When the value isfalse, the node is excluded from the output._templateAttributes(TemplateAttributeEntry[] | null): Maps template keys to specific node attributes._templateFieldMetadata(Record<string, unknown> | null): Stores optional developer-defined metadata for a field occurrence.
Commands
setTemplateSlot(name: string): Sets the_templateSlotattribute on the node at the current selection.unsetTemplateSlot(): Removes the_templateSlotattribute from the node at the current selection.setTemplateIf(name: string): Sets the_templateIfattribute on the node at the current selection.unsetTemplateIf(): Removes the_templateIfattribute from the node at the current selection.setTemplateAttributes(entries: TemplateAttributeEntry[]): Sets the_templateAttributesattribute on the node at the current selection.unsetTemplateAttributes(): Removes the_templateAttributesattribute from the node at the current selection.
Example
import { TemplateField } from '@tiptap-pro/ai-toolkit'
const editor = new Editor({
extensions: [StarterKit, TemplateField],
})
// Mark the selected node as a template slot
editor.commands.setTemplateSlot('intro')
// Remove the template slot
editor.commands.unsetTemplateSlot()getTemplateFieldMatches
Returns all matching template field occurrences for a field name from a Tiptap JSON document.
The search covers _templateSlot, _templateIf, and _templateAttributes. Each match includes the node content and the optional _templateFieldMetadata object stored on that field occurrence.
Parameters
options(GetTemplateFieldMatchesOptions): Search optionsdocument(JSONContent | JSONContent[]): A Tiptap JSON doc node or fragment arrayfieldName(string): The field name to search for
Returns
TemplateFieldMatch[]fieldName(string): The matched field namefieldType('slot' | 'condition' | 'attribute'): Which template field type matchedmetadata(Record<string, unknown> | null): The_templateFieldMetadataobject for that field occurrencecontent(JSONContent[] | null): The matched node content as Tiptap JSON
Example
import { getTemplateFieldMatches } from '@tiptap-pro/ai-toolkit'
const matches = getTemplateFieldMatches({
document: editor.getJSON(),
fieldName: 'intro',
})
matches.forEach(match => {
console.log(match.fieldType)
console.log(match.metadata)
console.log(match.content)
})