Assistant
A chat route over the AI chat block with createAssistant, and useAssistant on the client, with resumable answers, stop, model checks, moderation and quotas.
createAssistant is the server half of a chat: it stores the user's
message in the AI chat block, checks the model,
the moderation hook and the quota, claims the chat's run, streams the
answer in the AI SDK's UI message stream protocol and stores the answer
with its usage when it ends. The answer also goes to a
stream store, so a reload or a second tab picks it
up where it is. useAssistant is the client half.
In a Next.js app, the registry item writes the server half for you:
lib/assistant.ts with the assistant and the tools the model may call
(assistantTools, built per request as the caller), and the three routes
below.
npx shadcn@latest add @better-supabase/ai-chat-nextServer
import { streamText } from "ai";
import { createAssistant } from "better-supabase/ai-sdk/chat";
import { usageQuota } from "better-supabase/ai-sdk";
import { postgresStreamStore, sqlTransport } from "better-supabase/streams";
export const assistant = createAssistant({
streams: postgresStreamStore({
transport: sqlTransport(postgres.asService()),
}),
defaultModel: "openai/gpt-5-mini",
quota: usageQuota(usage, "ai.input_tokens"),
run: ({ model, messages, abortSignal, providerOptions }) =>
streamText({
model,
instructions: "You are the Acme assistant.",
messages,
abortSignal,
providerOptions,
}),
enqueueCostBackfill: (payload) => jobs.enqueue("ai.cost_backfill", payload),
});run gets the model the request may use, the history as model messages,
the abort signal stop triggers and the gateway options
for the user, tenant and chat. Return streamText(...) or
agent.stream(...). AI SDK 7 calls the system prompt instructions.
The assistant reads three members of what run returns: stream, the
stream parts it turns into UI message chunks with the standalone
toUIMessageStream({ stream, originalMessages, onEnd }); usage, the
tokens of every step; and finalStep, whose providerMetadata carries the
gateway's generation id and cost. streamText({ experimental_lowMemory: true })
returns no finalStep, so the answer is stored without the generation id
and cost; the tokens are still counted. A result with only the 0.31 members
(toUIMessageStream(), totalUsage, providerMetadata) still works and is
read the old way until 0.33. A result without a stream releases the run and
answers 500 AI_CHAT_RUN_FAILED.
The stream is read once: the UI chunks go to the stream store, which tees
them to the client and to every resume call, and onEnd stores the final
message. That is why the answer survives a closed tab: the snapshot is built
on the server, not from what the browser received.
Three routes serve it. Each builds the per-request context: the chat block with the user's transport and a service transport, the user and the tenant.
import { after } from "next/server";
export async function POST(request: Request) {
const context = await assistantContext(); // { chats, userId, organizationId }
return assistant.respond(request, { ...context, waitUntil: after });
}export async function GET(
request: Request,
{ params }: RouteContext<"/api/chat/[id]/stream">,
) {
const { id } = await params;
return assistant.resume(id, await assistantContext(), {
signal: request.signal,
});
}export async function POST(
_: Request,
{ params }: RouteContext<"/api/chat/[id]/stop">,
) {
const { id } = await params;
return assistant.stop(id, await assistantContext());
}organizationId is null for a chat outside a tenant (the block's
tenant: false option). Such a chat skips quota and the gateway's org:
tag. With messages: { key: "uuid" } on the block, every message id must be
a uuid; the default generateId is crypto.randomUUID(), and the client's
useChat needs generateId: () => crypto.randomUUID() too.
waitUntil keeps the function running until the answer is stored after the
response is sent: after in Next.js, ctx.waitUntil on Workers.
The stop route aborts the generation through the run's abort signal and
stores the answer so far as aborted. A stop() in the browser only
closes its connection; without the route the model would keep running and
the answer would be stored as complete.
What a request does
- Reads
{ id, message, trigger, messageId, model }. The chat is created on first use with the id the client made. - Picks the model: the requested one when the tenant's plans allow it
(
403 AI_MODEL_NOT_ALLOWEDotherwise), then the chat's model, thendefaultModel, then the first allowed model. - Runs
moderateon the user's message, when set.blockanswers403 AI_MODERATION_BLOCKED; every verdict other thanallowis recorded. - Runs
quota, when set. An error answers 429 withRetry-After. - Stores the message (
appendUser), reads the active branch and repairs tool calls that never got a result. - Claims the run. While another answer runs it answers
409 AI_CHAT_BUSY. - Streams the answer. When it ends, the answer is stored (
complete,abortedafter a stop, orerrorwhen the stream failed), the run is released with its token usage and the gateway's generation id and cost, andonFinishruns. A failed stream releases the run asfailedand keeps the error text in the run'serror, while the client sees the fixedonErrormessage.
Errors are RFC 9457 problem details responses with a code (see Results).
| Option | Does |
|---|---|
streams | The stream store: postgresStreamStore or redisStreamStore |
run | Starts the generation |
defaultModel | The model when the request and the chat name none that is allowed |
quota | The quota check, such as usageQuota(usage, meter) |
moderate | Checks the user's message: allow, flag, redact or block |
enqueueCostBackfill | Called when the gateway hasn't reported the cost yet |
onFinish | Called after the answer is stored, with its status and usage |
streamTtl | How long the stream is kept, seconds or an interval; one day by default |
feature | The gateway's feature: tag, chat by default |
onError | The message the client sees for a stream error, aiErrorMessage by default |
stream | What the client receives beside the text, such as assistantMetadata |
validate | Schemas the user's message must match before it is stored |
generateId | Message and stream ids, crypto.randomUUID() by default |
Tool approvals
A tool with needsApproval stops the answer at an approval-requested part. The client answers with addToolApprovalResponse, and useAssistant then sends the stored assistant message with the decision on it. The assistant loads the stored message, copies only approved and reason onto it, and continues the same message, so the approval and the tool output end up in one answer.
Return tools from run so toUIMessageStream can build the tool parts, and set toolApprovalSecret to sign approvals:
const assistant = createAssistant({
streams,
defaultModel: "openai/gpt-5",
toolApprovalSecret: process.env.APPROVAL_SECRET,
run: (args) =>
agent.stream({
messages: args.messages,
abortSignal: args.abortSignal,
experimental_toolApprovalSecret: args.toolApprovalSecret,
}),
});A decision whose signature differs from the stored request gets a 403, and one that matches no pending request gets a 409. The client never supplies a tool's input or output on this path.
Stream options
stream sets the toUIMessageStream options that decide what the client
receives beside the text: messageMetadata, sendReasoning, sendSources,
sendStart and sendFinish. A function gets the run's arguments, so the
metadata can name the model the request got. assistantMetadata sends the
model and start time with the first chunk, and the finish reason and token
usage with the last:
import {
assistantMetadata,
createAssistant,
} from "better-supabase/ai-sdk/chat";
export const assistant = createAssistant({
// ...
stream: (args) => ({ ...assistantMetadata(args), sendReasoning: false }),
});On the client, message.metadata then has model, createdAt,
finishReason and usage. Type it with
useAssistant<UIMessage<AssistantMessageMetadata>>.
Validation
validate checks the user's message with the AI SDK's
safeValidateUIMessages before anything is stored. A message whose
metadata, data parts or tool parts don't match answers
422 AI_MESSAGE_INVALID:
export const assistant = createAssistant({
// ...
validate: { metadataSchema, dataSchemas: { weather: weatherSchema }, tools },
});The AI SDK validates only schemas it can turn into JSON Schema: zod, the
AI SDK's jsonSchema(schema, { validate }), or a Standard JSON Schema such
as ArkType. A plain Standard Schema without a JSON Schema passes unchecked.
Errors
aiErrorToDbError (from better-supabase/ai-sdk) turns an AI SDK or AI
Gateway error into a DbError, so a route answers with the same problem
details as the rest of the app. It matches errors by name, and the message
is fixed per kind: the provider's message can quote the prompt or a key, so
it never reaches the client. A gateway error also carries its generationId and
ruleId in details, so you can find the request in the gateway dashboard.
| Error | Kind | Code |
|---|---|---|
APICallError 429, gateway rate_limit_exceeded | rate_limited (with Retry-After) | AI_PROVIDER_RATE_LIMITED |
APICallError 408 or 504, gateway timeout_error | timeout | AI_PROVIDER_TIMEOUT |
APICallError 400, 413 or 422 | invalid_request | AI_PROVIDER_BAD_REQUEST |
APICallError 5xx, gateway internal_server_error | network | AI_PROVIDER_UNAVAILABLE |
| Gateway error with status 402 (budget or credits used up) | quota_exceeded, status 402 | AI_GATEWAY_PAYMENT_REQUIRED |
NoSuchModelError, gateway model_not_found | not_found | AI_MODEL_NOT_FOUND |
Gateway access_policy_denied (GatewayAccessPolicyDeniedError) | forbidden | AI_GATEWAY_ACCESS_POLICY_DENIED |
TypeValidationError | validation | AI_TYPE_VALIDATION |
RetryError | the last error's | the last error's |
| An abort | aborted | AI_ABORTED |
The assistant uses it twice. When run throws a known provider error, the
route answers with it (a 429 from the provider is a 429 for the client);
other errors still answer 500 AI_CHAT_RUN_FAILED. And aiErrorMessage,
the fixed message of the mapped error, is the default onError for errors
in the stream.
Client
"use client";
import { useAssistant } from "better-supabase/ai-sdk/react";
import type { UIMessage } from "ai";
export function Chat({ id, initial }: { id: string; initial: UIMessage[] }) {
const { messages, sendMessage, stop, status, regenerate } = useAssistant({
id,
messages: initial,
model: "openai/gpt-5-mini",
});
// ...
}useAssistant is useChat with a transport for these routes. It sends
only the new message, since the server keeps the history, reconnects to
/api/chat/{id}/stream after a reload (resume, on by default) and makes
stop() also stop the answer on the server, so it is stored as stopped.
api, body, headers, onError, onFinish, throttle, onToolCall,
onData, messageMetadataSchema and dataPartSchemas work as in
useChat. Pass your message type to type the metadata, data parts and
tools: useAssistant<MyUIMessage>({ ... }).
assistantTransport(config) is the transport useAssistant makes. Wrap it
in your own transport function to change what the default does, such as
adding a header per request.
Load the history in a Server Component and pass it as messages:
import { toUIMessages } from "better-supabase/ai-sdk";
const path = await aiChat.messages.path(id, { native: true }).orThrow();
return <Chat id={id} initial={toUIMessages(path)} />;toUIMessages trusts the stored history. To check it against the tools and
schemas the app uses now, call validUIMessages, which runs the AI SDK's
safeValidateUIMessages and returns a validation error
(AI_MESSAGES_INVALID) for a history saved before a tool's input schema
changed:
import { validUIMessages } from "better-supabase/ai-sdk";
const checked = await validUIMessages(path, { tools });
const initial = checked.ok ? checked.data : [];The UI message stream protocol version is pinned as
SPEC_PINS.aiSdkUiMessageStream; see Standards.
Example
The Next.js example has an assistant at /assistant
(apps/examples/nextjs/src/features/assistant). Without AI_GATEWAY_API_KEY
it answers with a scripted MockLanguageModelV4, so the stored messages,
the stream store and resuming after a reload work on the local stack.
Compact generated UI specs
assistant({ parts: { compact } }) rewrites the response message before it is saved. Pair it with
collapseSpecParts from better-supabase/json-render so a streamed UI
spec is stored as one part.
Last updated on
AI SDK
Convert between AI SDK UI messages and the canonical message format, attribute spend in the AI Gateway, and keep the model catalog and costs current.
Completions and objects
Routes for useCompletion and useObject with createCompletionRoute and createObjectRoute, with the quota check, gateway tags and usage metering of the assistant.