Streaming
Stream AI edits from the server so they appear in the document in real time, as the model generates them. The edit runs on your server and is applied to the Tiptap Cloud document over a live connection, so every collaborator sees it happen.
Requires Collaboration
Streaming applies the edit to a live Tiptap Cloud document and syncs it to the editor through Collaboration, so both are required. Unlike the non-streaming tools, there is no inline-document mode. If you are not on Tiptap Cloud Collaboration yet, you will need it to stream edits from the server.
See the source code on GitHub.
Tech stack
- A client-side React application
- A server application
- An AI agent framework like the Vercel AI SDK
- OpenAI models
- The Server AI Toolkit
The Server AI Toolkit works with any AI agent framework and AI model. Use it with any frontend framework and backend programming language. This guide uses a simple Node.js server endpoint that takes a Request object and returns a Response.
Before you continue, set up the Server AI Toolkit by following the installation guide.
How it works
- Your server fetches the
tiptapEdittool definition and reads the document, just as it does with a non-streaming agent. - As the model generates the tool call, your server forwards the raw input deltas to
/v4/ai/toolkit/stream-toolover a WebSocket connection, asstart,delta, andendmessages. - From there, the Server AI Toolkit applies the edit for you: as the forwarded deltas arrive, it incrementally updates the Tiptap Cloud document over a live connection. You never apply anything yourself; the document updates happen automatically on the server side as the deltas stream in.
- The client renders the changes through Collaboration. The editor never calls a streaming method itself, so the edits arrive as document updates.
Stream an edit
Works with most AI backends
This example uses the AI SDK by Vercel, but you can drive
stream-tool from most AI back-end setups. You just forward your model's tool-call input as
delta messages.
On the server, open a WebSocket connection to stream-tool and drive it with your model's tool-call stream. The connection lets you forward each tool-call delta as the model produces it instead of sending the whole input at once.
Each message is a JSON object sent as one text frame. You send three message types: start to open the stream, delta for each chunk of the AI-generated tool input, and end once the input is complete. The server sends its events back the same way and closes the connection once the edit is applied.
Install dependencies
Install these dependencies in your server app:
npm install ai ws zodimport {
createUIMessageStreamResponse,
gateway,
generateId,
isStepCount,
streamText,
tool,
toUIMessageStream,
type UIMessage,
} from 'ai'
import WebSocket from 'ws'
import { z } from 'zod'
import { getAuthHeaders } from './server-ai-toolkit/get-auth-headers'
// The Server AI Toolkit API base URL
const apiBaseUrl = process.env.TIPTAP_CLOUD_AI_API_URL || 'https://api.tiptap.dev'
export async function handleStreamEditRequest(request: Request): Promise<Response> {
const { messages, editorContext, documentId } = await request.json()
// Single-shot edit: the task is the latest user message.
const lastUser = (messages as UIMessage[]).filter((m) => m.role === 'user').at(-1)
const task =
lastUser?.parts
.filter((p) => p.type === 'text')
.map((p) => (p as { text: string }).text)
.join(' ') ?? ''
// 1. Fetch the tiptapEdit tool definition and read the document.
// These steps match the non-streaming flow. See the REST API reference.
const { tools, systemPrompt } = await fetch(`${apiBaseUrl}/v4/ai/toolkit/fetch-tools`, {
method: 'POST',
headers: await getAuthHeaders(),
body: JSON.stringify({ editorContext, tools: { tiptapEdit: true } }),
}).then((res) => res.json())
const tiptapEdit = tools.find((t) => t.name === 'tiptapEdit')
const read = await fetch(`${apiBaseUrl}/v4/ai/toolkit/execute-tool`, {
method: 'POST',
headers: await getAuthHeaders(documentId),
body: JSON.stringify({
tool: { name: 'readDocument', input: {} },
document: { type: 'cloud', id: documentId },
editorContext,
}),
}).then((res) => res.json())
// 2. Open a WebSocket to stream-tool. Each message is one text frame.
const socket = new WebSocket(`${apiBaseUrl.replace(/^http/, 'ws')}/v4/ai/toolkit/stream-tool`, {
headers: await getAuthHeaders(documentId),
// Fail instead of waiting forever if the connection is never answered.
handshakeTimeout: 10_000,
})
// Resolves to false when the connection fails, so sending never blocks the model's stream.
const opened = new Promise<boolean>((resolve) => {
socket.once('open', () => resolve(true))
socket.once('close', () => resolve(false))
})
// Messages wait for the connection, then go out in the order they were sent.
const send = async (message: object) => {
if ((await opened) && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message))
}
}
// The server sends one event per frame and closes the connection when it's done.
const events: { type: string; message?: string }[] = []
socket.on('message', (data) => events.push(JSON.parse(data.toString())))
const closed = new Promise((resolve) => socket.once('close', resolve))
// A failed connection also closes the socket, so `execute` below reports it.
socket.on('error', () => {})
// 3. Drive the model. Forward its tool input as start / delta / end messages.
const result = streamText({
model: gateway('openai/gpt-6-luna'),
instructions: `${systemPrompt}\n\nMake the edit with tiptapEdit, then reply with one short sentence confirming what you changed.`,
prompt: JSON.stringify({ content: read.tool.output, task }),
// Close the connection if the model fails, so the stream doesn't stay open on the server.
onError: () => socket.close(),
onAbort: () => socket.close(),
tools: {
tiptapEdit: tool({
description: tiptapEdit.description,
inputSchema: z.fromJSONSchema(tiptapEdit.inputSchema),
strict: false,
onInputStart: () =>
send({
version: 1,
type: 'start',
editorContext,
document: { type: 'cloud', id: documentId },
tool: { name: 'tiptapEdit' },
user: 'ai-assistant',
}),
onInputDelta: ({ inputTextDelta }) =>
send({ version: 1, type: 'delta', argsTextDelta: inputTextDelta }),
onInputAvailable: () => send({ version: 1, type: 'end' }),
// Wait for the AI server to finish applying the edit, then report the
// result so the chat turn completes and the model can tell the user.
execute: async () => {
await closed
const error = events.find((event) => event.type === 'error')
if (error) return { ok: false, error: error.message }
return { ok: events.some((event) => event.type === 'completed') }
},
}),
},
// Step 0: force the edit. Step 1: forbid tools so the model writes the
// confirmation sentence for the chat.
stopWhen: isStepCount(2),
prepareStep: ({ stepNumber }) => ({
toolChoice: stepNumber === 0 ? 'required' : 'none',
}),
})
// The edits reach the editor via Y.Doc sync; this stream drives the chat.
return createUIMessageStreamResponse({
stream: toUIMessageStream({
stream: result.stream,
originalMessages: messages,
generateMessageId: generateId,
}),
})
}See the REST API reference for the full request and response message shapes, and the demo source for a production-ready route with error handling.
Streaming over HTTP
stream-tool also accepts the same messages as an NDJSON
POST request with a streamed body. The edit still reaches the document as the deltas arrive, but
the response events are only sent once the request body ends, and some proxies cut long requests.
Prefer the WebSocket connection. See the REST API
reference.
Client-side setup
Install dependencies
Install these dependencies in your client app:
npm install @ai-sdk/react @tiptap/extension-collaboration @tiptap/react @tiptap/starter-kit @tiptap-pro/provider @tiptap/ai-toolkit @tiptap/y-tiptap ai yjsOn the client, add the Collaboration and ServerAiToolkit extensions, connect the document with a TiptapCollabProvider, and drive the chat with the AI SDK useChat hook (the same as the other server demos). The streamed edits arrive in the editor through Collaboration; useChat shows the model's replies.
import { useChat } from '@ai-sdk/react'
import { Collaboration } from '@tiptap/extension-collaboration'
import { EditorContent, useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import { ServerAiToolkit, getEditorContext } from '@tiptap/ai-toolkit'
import { DefaultChatTransport } from 'ai'
import { useRef } from 'react'
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({ undoRedo: false }),
Collaboration.configure({ document: doc }),
ServerAiToolkit,
],
})
// editorContext in a ref to avoid an AI SDK stale-closure (vercel/ai#7819).
const editorContextRef = useRef(editor ? getEditorContext(editor) : null)
editorContextRef.current = editor ? getEditorContext(editor) : null
const { messages, sendMessage, status } = useChat({
transport: new DefaultChatTransport({
api: '/api/stream-edit',
body: () => ({
editorContext: editorContextRef.current,
documentId: 'your-document-id',
}),
}),
})Fade in text as it streams
Streamed text lands in the document token by token. The optional AiInsertReveal extension fades it in as it arrives, so the edit reads as a smooth reveal instead of text popping in. It is a view-only decoration: it adds no marks and never touches the document, so it stays inert to accept/reject and to persistence, and neither your own typing nor another collaborator's is faded.
It builds on the client-side setup above: it reveals text that arrives through Collaboration, so it needs that setup. Import it from the streaming-reveal subpath and add it after ServerAiToolkit. It reads collaboration positions from @tiptap/y-tiptap, so install that too if it is not already a dependency.
Pass your collaboration provider to it. The provider's awareness is how the AI is told apart from other collaborators, and without it nothing is revealed.
import { ServerAiToolkit, getEditorContext } from '@tiptap/ai-toolkit'
import { AiInsertReveal } from '@tiptap/ai-toolkit/streaming-reveal'
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({ undoRedo: false }),
Collaboration.configure({ document: doc }),
ServerAiToolkit,
AiInsertReveal.configure({ provider }),
],
})CSS styles
The extension adds the ai-insert-reveal class to each freshly-streamed run and seeds its animation-delay so the fade resumes at the right point across the per-token re-render. It ships no CSS. Add an animation for that class to define the effect. The class lands on an inline element, so animate properties that apply to one, such as opacity, color or filter.
.tiptap .ai-insert-reveal {
animation: ai-insert-reveal 380ms ease-out both;
}
@keyframes ai-insert-reveal {
from {
opacity: 0.35;
}
to {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.tiptap .ai-insert-reveal {
animation: none;
}
}Configuration
| Option | Default | Description |
|---|---|---|
provider | null | Your collaboration provider. Required: its awareness identifies the AI, and nothing is revealed without it. |
className | 'ai-insert-reveal' | Class applied to each streamed run. Change it to run a different effect or to avoid a collision. |
durationMs | 550 | How long each run keeps its decoration. Keep it at or above your CSS animation duration so the fade can finish. |
AiInsertReveal.configure({ provider, durationMs: 700 })Stream as tracked changes
To let users review streamed edits instead of applying them directly, add reviewOptions to the start message. The edit then appears as a tracked-change suggestion that's typed into the document in real time and that users can accept or reject.
send({
version: 1,
type: 'start',
editorContext,
document: { type: 'cloud', id: documentId },
tool: { name: 'tiptapEdit' },
user: 'ai-assistant',
reviewOptions: { mode: 'trackedChanges' },
})Add the Tracked Changes extension on the client to render and accept or reject the suggestions. See the Use with Tracked Changes guide and the Tracked Changes streaming demo.
End result
The result is a simple but polished AI chatbot application:
See the source code on GitHub.
Next steps
- REST API reference: the full
stream-toolrequest and response protocol. - Review options: all
reviewOptionssettings. - Use with Tracked Changes: review server-side edits before they're accepted.
- Streaming with the client-side AI Toolkit: stream into the Tiptap Editor client-side, with the client variant of the AI Toolkit.