Ask AI
Add the Ask AI panel to rewrite, summarize and generate text from any streaming backend.
Ask AI lets users improve, shorten, translate or generate text. While a response streams, the editor is locked and the result shows as a preview. Nothing is written into the document until the user accepts it.
ai({ autocomplete: true }) adds ghost text after a pause in typing. It is off unless you set it. Tab inserts the suggestion and Escape dismisses it. Typing cancels the request. A read-only or locked editor does not ask for one.
The panel's Continue writing keeps going from the cursor. Summarize document (in the generate list, not the slash menu) writes a summary into a new block. Fix spelling & grammar previews the rewrite as a word diff. When the comments add-on is installed, an open thread has Suggest a reply, which fills the reply box and does not post until the user sends it.
The panel is a client only. It sends a POST to an endpoint you control, which can use any model. The example backend works with Gemini, Claude or OpenAI.
Install
npx shadcn@latest add https://blockcn.com/r/ai-menu.jsonHave an endpoint ready
Use one of these:
- Run the example backend. It listens on
http://localhost:8001/api/ai. - Write your own route that follows the contract below.
Wire it into the editor
You add three things: the extension, the slash item, and the <AskAI /> panel. Passing onAskAI to the toolbar also adds an Ask AI button when text is selected.
"use client";
import { Editor } from "@/components/editor/Editor";
import { useEditor } from "@/components/editor/useEditor";
import { createEditorExtensions } from "@/editor-core/schema/extensions";
import { AskAI as AskAIExtension } from "@/editor-core/ai/AskAIExtension";
import { AI_SLASH_CATEGORY } from "@/components/editor/ai/aiSlashItems";
import { AskAI } from "@/components/editor/ai/AskAI";
const extensions = [
...createEditorExtensions({
slashCategories: [AI_SLASH_CATEGORY],
}),
AskAIExtension,
];
export function BlockEditor() {
const editor = useEditor({ extensions });
if (!editor) return null;
return (
<Editor editor={editor}>
<Editor.Frame>
<Editor.Content />
<Editor.Chrome>
<Editor.SideMenu />
<Editor.FormattingToolbar
onAskAI={() => {
const { from, to } = editor.state.selection;
editor.commands.openAskAI({ mode: "selection", from, to });
}}
/>
<AskAI endpoint={process.env.NEXT_PUBLIC_AI_URL} />
</Editor.Chrome>
</Editor.Frame>
<Editor.Outline />
</Editor>
);
}If you've already added media or table extensions, keep them in the same list. Only the highlighted lines are new.
Read the endpoint from configuration rather than hardcoding it. In Vite that's import.meta.env.VITE_AI_URL; in Next.js, process.env.NEXT_PUBLIC_AI_URL. Leave it unset to post to /api/ai on your own origin.
Try it
- Select some text and click Ask AI in the toolbar.
- Or type / on an empty line and pick Ask AI to generate new content.
Endpoint default
Without an endpoint prop, AskAI posts to /api/ai on the same origin. In Next.js you can add a route at src/app/api/ai/route.ts (or proxy that path to your backend) and leave the prop out.
Transports
endpoint covers the common case. For anything else, pass a transport: a function that takes the request and an abort signal and yields text chunks. When both are set, transport is used and endpoint is ignored. ai({ actions }) replaces the built-in action list, including the slash items for generate actions. ai({ systemPrompt }) sends that string on every request. Three transports ship with the add-on:
| Transport | Response it reads |
|---|---|
plainTextTransport(endpoint, options?) | A streamed plain-text body. The default. |
sseTransport(endpoint, options?) | Server-sent events. Each data: is text or JSON with text, delta, content or OpenAI-style choices[0].delta.content. data: [DONE] ends the stream and event: error shows an error. Pass parse(data, event) for other shapes. |
aiSdkTransport(endpoint, options?) | A Vercel AI SDK route: toUIMessageStreamResponse(), toDataStreamResponse() or toTextStreamResponse(). Adds prompt to the body, as useCompletion does. |
Every transport takes headers (an object, or a function that runs per request so tokens can refresh), credentials and fetch:
import { sseTransport } from "@/components/editor/ai/transport";
const transport = sseTransport("/api/ai", {
headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
});
<AskAI transport={transport} />;To only add headers to the default transport, pass headers to AskAI directly: <AskAI headers={{ Authorization: "Bearer …" }} />.
A custom transport is an async generator:
import type { AskAITransport } from "@/components/editor/ai/transport";
const transport: AskAITransport = async function* (request, { signal }) {
const stream = await myClient.complete(request, { signal });
for await (const chunk of stream) yield chunk.text;
};Throw to show an error in the panel. A thrown AskAIError keeps the HTTP status. Throwing after yielding text marks the response as cut off rather than failed: the panel keeps the partial text and asks "Response was cut off — accept anyway?" before Accept. Throw AskAITruncatedError(message, reason) with reason "max_tokens", "refusal" or "error" to say why. useAskAI reports this as status: "truncated", with the reason in truncation.
Document context
Each request carries a context object with the document title, the block(s) the cursor or selection is in, and up to 3 blocks before and 2 after. It's capped at 4,000 characters, keeping the text nearest the cursor. Tune it or turn it off:
<AskAI context={{ blocksBefore: 5, blocksAfter: 1, maxChars: 8000 }} />
<AskAI context={false} />Context goes to the same backend as the selected text. If your documents are sensitive, apply the same data rules to both.
Backend contract
AskAI sends POST with Content-Type: application/json:
{
"action": "improve",
"text": "the selected text, when there is some",
"instruction": "optional free-text prompt",
"param": "Professional",
"systemPrompt": "optional text from ai({ systemPrompt })"
}Prop
Type
With the default transport, the response must be streamed plain text: write text chunks to the body as the model generates them. Use sseTransport or aiSdkTransport for other formats. A non-2xx status shows as an error in the panel, using the body's { "error": "…" } message when there is one.
A plain-text stream that just ends looks finished, so a provider error halfway through would be accepted as a complete answer. To report it, send the header X-Blockcn-Stream: v1 and end a failed stream with the trailer \n\u0000BLOCKCN_ERROR: followed by {"error": "…", "reason": "max_tokens" | "refusal" | "error"}. plainTextTransport strips the trailer and shows the response as cut off. Over SSE, send event: error with the same JSON instead of [DONE]. The example server does both. A connection that drops mid-stream also shows as cut off.
Treat document text as data
text and context come from the document, which may contain text written to steer the model ("ignore your instructions and…"). Put them in the user message inside clearly marked delimiters, and tell the model in the system prompt that delimited text is data, not instructions. The example server does this with per-request tags. Never interpolate them into the system prompt, and validate param before you do.
Minimal Next.js route
A sketch of a compatible route. Replace streamFromYourModel with your provider's streaming SDK call.
export async function POST(req: Request) {
const { action, text, instruction, param } = await req.json();
const prompt = buildPrompt({ action, text, instruction, param }); // your prompt logic
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
for await (const chunk of streamFromYourModel(prompt)) {
controller.enqueue(encoder.encode(chunk));
}
controller.close();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}Keep API keys on the server. Never call the model provider directly from the browser.
With the Vercel AI SDK
import { streamText } from "ai";
export async function POST(req: Request) {
const { action, text, instruction, param, context } = await req.json();
const result = streamText({
model: yourModel,
system: buildSystemPrompt(action, param), // your prompt logic
prompt: buildUserContent({ text, instruction, context }),
});
return result.toUIMessageStreamResponse();
}<AskAI transport={aiSdkTransport("/api/ai")} />