useChat
Overview
useChat holds a chat with a model through your own server route: the messages and their branches, the reply as it streams in, and the tool calls waiting on the user.
It's the AI kit's data layer, and it renders nothing. It returns plain data and functions, so any markup can show a chat, and the kit's chat components will take the same messages as props. Hand it an adapter for the wire format your route speaks: Anthropic's Messages API, OpenAI-compatible chat completions, the Vercel AI SDK's UI message stream, or plain text and server-sent events. The adapter takes your route's URL, never an API key: the key stays on your server.
Import
import { useChat, anthropicAdapter } from '@allxsmith/bestax-ai';
Usage
A Chat With No Server
scriptedAdapter answers from a script instead of a route, so this example runs in the page with no
server and no key. Swap it for one of the adapters below and the rest stays the same.
function ScriptedChat() { const [draft, setDraft] = useState(''); const { messages, status, send, stop } = useChat({ adapter: scriptedAdapter({ reply: ({ messages }) => { const question = messages[messages.length - 1]; const asked = question.parts .map(part => (part.type === 'text' ? part.text : '')) .join(''); return `This reply is scripted, so it streams with no server. You asked: "${asked}"`; }, }), }); const busy = status === 'submitted' || status === 'streaming'; return ( <Box> <Block role="log" aria-busy={busy}> {messages.map(message => ( <Paragraph key={message.id}> <strong>{message.role === 'user' ? 'You' : 'Assistant'}:</strong>{' '} {message.parts .map(part => (part.type === 'text' ? part.text : '')) .join('')} </Paragraph> ))} </Block> <form onSubmit={event => { event.preventDefault(); void send(draft); setDraft(''); }} > <Input label="Message" value={draft} onChange={event => setDraft(event.target.value)} /> {busy ? ( <Button type="button" onClick={stop}> Stop </Button> ) : ( <Button type="submit" color="primary"> Send </Button> )} </form> </Box> ); }
Messages and Parts
Each message has a role, a status and an ordered list of parts. A reply's parts stay in the
order they streamed, so reasoning, text, tool calls and sources interleave the way the model wrote
them.
| Part | What it holds |
|---|---|
text | Text, with citations naming the source parts it cites. |
reasoning | The model's reasoning, with startedAt and endedAt for "Thought for 12s". It can be redacted. |
tool-call | A tool call: its streamed inputText, the parsed input, its state, and its output or errorText. |
source | Something the reply drew on: a url, a title, a quoted passage. |
file | A file the user attached, or one the model made. |
step | The start of another call to the model within one reply, such as after its tools ran. |
data | Your server's own data under a name, such as tasks. |
A message's status is pending until its reply starts, streaming while it arrives, then
done, error (with an error saying why), aborted, or awaiting-action while a tool call in it
waits on the user. Each message keeps its own, so an old reply stays error while the conversation
goes on. The hook's own status is submitted, streaming, awaiting-action, error or idle.
Each part keeps a providerData field with what its adapter needs to send it back exactly as it
arrived. Anthropic asks for an assistant turn back as it streamed, thinking signatures included, so
store messages whole and don't edit their parts.
A streamed reply updates messages at most once a frame, and at once when it ends.
Adapters
Each adapter is a request builder and a parser for one wire format, over one shared reader of
server-sent events. Each takes url (your route, /api/chat by default), headers, credentials
and fetch.
| Adapter | Your route streams | It sends | Files it takes |
|---|---|---|---|
anthropicAdapter() | Anthropic's Messages API stream, passed on unchanged | { messages } in the Messages API's shape | JPEG, PNG, GIF and WebP, and PDF |
openAIAdapter() | A chat completions stream, passed on unchanged | { messages } in the chat completions shape | PNG, JPEG, WebP and GIF |
aiSdkAdapter() | The AI SDK's UI message stream, from an AI SDK route | { messages, trigger, messageId }, as the SDK's own client | Any |
textAdapter() | Plain text | { messages: [{ role, content }] } | None |
sseAdapter() | Server-sent events, each event's data being more text | { messages: [{ role, content }] } | None |
The fields of the hook's body option go beside those in every request. System messages stay in
the browser: your server sets the system prompt.
openAIAdapter takes reasoningField for a provider that streams reasoning in a field of its own,
such as DeepSeek's reasoning_content. sseAdapter takes parse, which turns each event into
text, or into updates in the hook's own terms, for a route with events of its own shape.
const deepseek = openAIAdapter({ reasoningField: 'reasoning_content' });
const events = sseAdapter({
url: '/api/stream',
parse: ({ event, data }) =>
event === 'token' ? JSON.parse(data).text : null,
});
Tools and Approvals
When a reply calls a tool, the call waits for the user's decision unless you list the tool in
tools and say it needs none. It fails closed:
- A tool that isn't in
toolsalways waits for a decision, and so does one whoseneedsApprovalthrows or returns anything butfalse. - A call can only be decided once its input has fully arrived and the reply has ended.
respondleaves any other call as it is, so keep Approve disabled until the call'sstateisawaiting-approval. - A decision applies once. A second one changes nothing.
- A decision goes to the call on the branch on screen. For a call on another branch, pass its reply's
id as the last argument to
respondoraddToolOutput: two replies can hold calls with one id, such as branches restored from storage. - An edit goes in the approval, as
approval.input, and that is what runs. The model's owninputnever changes, so the history the model sees stays as it wrote it. - Stopping, or sending something else, gives up on calls still waiting, so nothing is left to approve later.
const { messages, respond } = useChat({
adapter: anthropicAdapter(),
tools: {
// Runs in the browser with no decision. It can call your own server.
get_weather: {
needsApproval: false,
execute: async input => getWeather(input),
},
// Waits for a decision, then runs with the input the user approved.
send_email: {
execute: async (input, { signal }) => sendEmail(input, { signal }),
},
},
});
// From an Approve or Deny button on a call whose state is 'awaiting-approval':
respond(call.toolCallId, { approved: true });
respond(call.toolCallId, { approved: false, note: 'Not to that address.' });
Approved, a call with an execute runs in the browser. Without one, it waits for addToolOutput,
which you call with what it returned, or with errorText when it failed. The one exception is a
decision your AI SDK route asked for itself, with an approval request in its stream: approved with
no edit and no execute, that call goes back to the route, which runs it, and if the route's next
response holds no result for it, the call fails rather than wait. A decision the browser asked for,
for a tool you didn't list or one whose needsApproval says so, never goes to the route as an
approval. Denied, the model is told so, with the note. Once no call in the reply waits, the hook sends the reply back with its results, and
the model's next step streams into the same message after a step part.
When tools that need no decision keep running, the reply goes back by itself at most maxSteps times
in a row (5 unless you say). Then it ends, done, with those tools' results recorded, and the next
message the user sends carries them. Each message the user sends, and each decision or output they
give, starts the count again.
The browser can send any history, so your server checks a call again before acting on it: that it issued the call, and that the input is one it allows.
Branches
regenerate writes a new reply beside the old one, and edit adds an edited question beside the
original, each with a reply of its own. Neither replaces anything: messages that share a parentId
are branches, and messages is the branch on screen. getBranches and switchBranch move between
them, for a "2 / 3" picker.
const { index, count } = getBranches(message.id);
<Buttons>
<Button
aria-label="Previous version"
isDisabled={index === 0}
onClick={() => switchBranch(message.id, index - 1)}
>
‹
</Button>
<Span>
{index + 1} / {count}
</Span>
<Button
aria-label="Next version"
isDisabled={index === count - 1}
onClick={() => switchBranch(message.id, index + 1)}
>
›
</Button>
</Buttons>;
A message with no parentId follows the one before it in the array, so a plain array of messages is
a plain thread, and the hook only writes parentId where the array order doesn't say it.
Attachments
send takes files. Give upload to store each one (on your own storage, say) and resolve its URL,
and the message gets a file part pointing there. Without upload, a file becomes a data: URL,
which suits a demo but puts the whole file in every request; a file over 5 MB fails.
A file the adapter can't carry is refused before anything is sent or stopped, with error naming
it. Each adapter lists the media types it takes in its accept, in the form an <input>'s accept
attribute takes, so a file picker can offer only those: accept={adapter.accept?.join(',')}. An
edit checks the files it carries over the same way.
The provider fetches a stored file itself, so upload resolves an absolute https: URL the
provider can reach, or a data: URL. A relative path or a blob: URL fails the request, with the
file-url code, rather than leave the file out.
const chat = useChat({
adapter: anthropicAdapter(),
upload: async (file, { signal }) => {
// An absolute https: URL, such as a signed URL on your storage.
const { url } = await storeFile(file, { signal });
return { url, mediaType: file.type, name: file.name, size: file.size };
},
});
chat.send({ text: 'What is in this picture?', files: [file] });
Holding the History
Without messages, the hook holds the history, starting from defaultMessages, and setMessages
replaces it. Pass messages and onMessagesChange to hold it yourself, to save it as it changes,
say. Either way the list is every message, every branch included, and it's what to store.
function Conversation({ saved, save }) {
const [messages, setMessages] = useState(saved);
const chat = useChat({
adapter: anthropicAdapter(),
messages,
onMessagesChange: next => {
setMessages(next);
save(next);
},
});
// …
}
Once you've taken a reply into the messages you pass, leaving it out stops its request, as does
leaving out a call whose tool is running in the browser. A reply you haven't taken yet keeps
streaming toward you. setMessages stops what it drops the same way.
Your callbacks (onMessagesChange, onFinish, onError, needsApproval, body, a tool's
execute, and an adapter of your own's buildRequest and parser) can call stop, send or
setMessages themselves. Whatever the hook was about to do next, such as sending a reply back with
its tool results or starting a tool, it does only if the reply is still there, in the state it left
it, once the callback returns. It goes on from the reply as your callback left it, so a change that
settles nothing, such as to its metadata, holds. A request is built once your callbacks before it
have run, so it carries their changes, and a buildRequest that changes the history builds once
more on the history it left. A turn ends when a callback drops the question it had, or moves the
reply away from it: it sends nothing, and its reply becomes aborted, as if stopped. A reply with
no question before it, such as a greeting you open the chat with, goes on once its calls are
answered.
While a reply streams, onMessagesChange fires about once a frame, so save on onFinish instead if
writing that often is too much. For a list of conversations, see useConvos.
Testing Without a Key
createScriptedResponse makes a Response whose body streams a script: plain text from strings, or
server-sent events from objects. It can cut the body at any byte, pace it with a delay, and end with
an AbortError when its signal aborts, as a real fetch does. Give it to any adapter as fetch, so a
test or a story runs that adapter's real parser with no server.
const adapter = anthropicAdapter({
fetch: async (url, init) =>
createScriptedResponse(
[
{
event: 'message_start',
data: { type: 'message_start', message: {} },
},
// …the rest of the events your test needs
],
{ chunkSize: 3, signal: init.signal }
),
});
scriptedAdapter does the same for a whole chat, speaking the AI SDK's stream, so a demo can script
reasoning, tool calls and approvals as well as text. Its reply gets each request's messages and
trigger, and returns a string, or the stream's chunks.
Server Routes
Each route holds the key, sets the model, the system prompt and the tools, and takes nothing from the browser but the messages. The routes below are Next.js route handlers; any server that can stream a response works the same way. Add your own authentication and rate limits, as for any route of yours.
A route that forwards whatever the browser sends would let anyone use your key with any model, prompt or tool, so each route below checks what arrives against the shapes its adapter sends, and refuses a system message or a history past its limit.
Anthropic
With Anthropic's TypeScript SDK, the route passes the API's own stream on, so the thinking blocks and their signatures reach the browser as they were sent. Keep the model, the system prompt and the thinking settings the same for the whole conversation.
// app/api/chat/route.ts
import Anthropic from '@anthropic-ai/sdk';
// Reads ANTHROPIC_API_KEY from the server's environment.
const client = new Anthropic();
type Block = Record<string, unknown>;
const isRecord = (value: unknown): value is Block =>
typeof value === 'object' && value !== null && !Array.isArray(value);
// A file's source: inline base64, or a URL.
const isSource = (source: unknown) =>
isRecord(source) &&
((source.type === 'base64' &&
typeof source.media_type === 'string' &&
typeof source.data === 'string') ||
(source.type === 'url' && typeof source.url === 'string'));
// The blocks the chat sends back, by type, each with the fields the API
// reads. A Map, so a type such as `__proto__` finds nothing. A route that
// turns on another feature adds its blocks, as the web search route below
// does.
const blocks = new Map<string, (block: Block) => boolean>([
['text', block => typeof block.text === 'string'],
// A summary that compaction left in place of older turns, or `null`
// where a summary failed, which the API passes over: sent back as it is.
[
'compaction',
block => block.content === null || typeof block.content === 'string',
],
['image', block => isSource(block.source)],
['document', block => isSource(block.source)],
[
'thinking',
block =>
typeof block.thinking === 'string' && typeof block.signature === 'string',
],
['redacted_thinking', block => typeof block.data === 'string'],
// A tool you give the model is called, and answered, with these.
[
'tool_use',
block =>
typeof block.id === 'string' &&
typeof block.name === 'string' &&
isRecord(block.input),
],
[
'tool_result',
block =>
typeof block.tool_use_id === 'string' &&
typeof block.content === 'string',
],
]);
// User and assistant turns, each with text or blocks the route takes, and
// not too many of them.
function isConversation(
value: unknown,
takes = blocks
): value is Anthropic.MessageParam[] {
return (
Array.isArray(value) &&
value.length <= 100 &&
value.every(
message =>
(message?.role === 'user' || message?.role === 'assistant') &&
(typeof message.content === 'string' ||
(Array.isArray(message.content) &&
message.content.every(
(block: unknown) =>
isRecord(block) &&
(takes.get(String(block.type))?.(block) ?? false)
)))
)
);
}
export async function POST(request: Request) {
const { messages } = await request.json();
if (!isConversation(messages)) {
return new Response('Bad request', { status: 400 });
}
try {
const upstream = await client.messages
.create(
{
model: 'claude-opus-5-5',
max_tokens: 64000,
system: 'You are a helpful assistant.',
thinking: { type: 'adaptive', display: 'summarized' },
messages,
stream: true,
},
// Stops the model when the reader leaves.
{ signal: request.signal }
)
.asResponse();
return new Response(upstream.body, {
headers: { 'Content-Type': 'text/event-stream' },
});
} catch {
return new Response('The model is unavailable.', { status: 502 });
}
}
With Server Tools
A server tool, such as web search, runs inside Anthropic's API, and a long turn of one can pause
(stop_reason: "pause_turn"). The route that gave Claude the tool resumes it: it sends the paused
content back and streams the rest of the turn on, leaving out the paused message's stop and the next
one's start, so the browser reads one reply. A reply that pauses with no route to resume it ends
with the finish reason paused, and a server tool call it left with no result isn't sent back
with the next question, since the API refuses one there.
// app/api/chat/route.ts, with web search
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const encoder = new TextEncoder();
// The blocks from the route above, and web search's call and results.
const withSearch = new Map([
...blocks,
[
'server_tool_use',
(block: Block) =>
typeof block.id === 'string' &&
typeof block.name === 'string' &&
isRecord(block.input),
],
[
'web_search_tool_result',
(block: Block) => typeof block.tool_use_id === 'string',
],
]);
export async function POST(request: Request) {
const { messages } = await request.json();
if (!isConversation(messages, withSearch)) {
return new Response('Bad request', { status: 400 });
}
const body = new ReadableStream<Uint8Array>({
async start(controller) {
const send = <Event extends { type: string }>(event: Event) =>
controller.enqueue(
encoder.encode(
`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`
)
);
let history: Anthropic.MessageParam[] = messages;
try {
// Resume a paused turn a few times at most.
for (let resumed = 0; resumed < 5; resumed++) {
const stream = client.messages.stream(
{
model: 'claude-opus-5-5',
max_tokens: 64000,
system: 'You are a helpful assistant.',
thinking: { type: 'adaptive', display: 'summarized' },
tools: [{ type: 'web_search_20260209', name: 'web_search' }],
messages: history,
},
{ signal: request.signal }
);
let paused = false;
for await (const event of stream) {
if (
event.type === 'message_delta' &&
event.delta.stop_reason === 'pause_turn'
) {
paused = true;
}
if (resumed > 0 && event.type === 'message_start') continue;
if (paused && event.type === 'message_stop') continue;
send(event);
}
if (!paused) break;
const message = await stream.finalMessage();
history = [
...history,
{ role: 'assistant', content: message.content },
];
}
} catch {
send({
type: 'error',
error: { type: 'api_error', message: 'The model is unavailable.' },
});
}
controller.close();
},
});
return new Response(body, {
headers: { 'Content-Type': 'text/event-stream' },
});
}
isConversation and blocks are from the route above. The route parses and writes each event again,
rather than passing the bytes on, but the events, signatures included, are the API's own.
OpenAI-Compatible
Any server that speaks chat completions, OpenAI's or another provider's, takes the same route, with its base URL, key and model in the server's environment.
// app/api/chat/route.ts
type Entry = Record<string, unknown>;
const isRecord = (value: unknown): value is Entry =>
typeof value === 'object' && value !== null && !Array.isArray(value);
// Only these fields, so nothing else reaches the provider with your key.
const only = (entry: Entry, ...keys: string[]) =>
Object.keys(entry).every(key => keys.includes(key));
// A user message's parts: text, and images by URL.
const isPart = (part: unknown) =>
isRecord(part) &&
((part.type === 'text' &&
only(part, 'type', 'text') &&
typeof part.text === 'string') ||
(part.type === 'image_url' &&
only(part, 'type', 'image_url') &&
isRecord(part.image_url) &&
only(part.image_url, 'url') &&
typeof part.image_url.url === 'string'));
// A call a reply made, with its arguments as they streamed.
const isCall = (call: unknown) =>
isRecord(call) &&
only(call, 'id', 'type', 'function') &&
typeof call.id === 'string' &&
call.type === 'function' &&
isRecord(call.function) &&
only(call.function, 'name', 'arguments') &&
typeof call.function.name === 'string' &&
typeof call.function.arguments === 'string';
// A user or assistant turn, or the tool message that answers a call.
const isMessage = (message: unknown) => {
if (!isRecord(message)) return false;
switch (message.role) {
case 'user':
return (
only(message, 'role', 'content') &&
(typeof message.content === 'string' ||
(Array.isArray(message.content) && message.content.every(isPart)))
);
case 'assistant':
// With `reasoningField` set, list that field here too.
return (
only(message, 'role', 'content', 'refusal', 'tool_calls') &&
(message.content === null || typeof message.content === 'string') &&
(message.refusal === undefined ||
typeof message.refusal === 'string') &&
(message.tool_calls === undefined ||
(Array.isArray(message.tool_calls) &&
message.tool_calls.every(isCall)))
);
case 'tool':
return (
only(message, 'role', 'tool_call_id', 'content') &&
typeof message.tool_call_id === 'string' &&
typeof message.content === 'string'
);
default:
return false;
}
};
// Those, and not too many of them.
const isConversation = (value: unknown): boolean =>
Array.isArray(value) && value.length <= 100 && value.every(isMessage);
export async function POST(request: Request) {
const { messages } = await request.json();
if (!isConversation(messages)) {
return new Response('Bad request', { status: 400 });
}
const upstream = await fetch(`${process.env.LLM_BASE_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.LLM_API_KEY}`,
},
body: JSON.stringify({
model: process.env.LLM_MODEL,
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
...messages,
],
stream: true,
stream_options: { include_usage: true },
}),
signal: request.signal,
});
if (!upstream.ok) {
return new Response('The model is unavailable.', { status: 502 });
}
return new Response(upstream.body, {
headers: { 'Content-Type': 'text/event-stream' },
});
}
AI SDK
An AI SDK route works unchanged with aiSdkAdapter, so use the one from the
AI SDK's chatbot guide. In short:
// app/api/chat/route.ts
import { anthropic } from '@ai-sdk/anthropic';
import {
convertToModelMessages,
createUIMessageStreamResponse,
streamText,
toUIMessageStream,
validateUIMessages,
} from 'ai';
export async function POST(request: Request) {
const body = await request.json();
// The SDK checks each message's shape, but not how many there are.
if (!Array.isArray(body?.messages) || body.messages.length > 100) {
return new Response('Bad request', { status: 400 });
}
const messages = await validateUIMessages({ messages: body.messages });
const result = streamText({
model: anthropic('claude-opus-5-5'),
instructions: 'You are a helpful assistant.',
messages: await convertToModelMessages(messages),
});
return createUIMessageStreamResponse({
stream: toUIMessageStream({ stream: result.stream }),
});
}
aiSdkAdapter sends what the SDK's own client sends: messages, trigger (submit-message or
regenerate-message) and, when regenerating, messageId. Put a chat id in the hook's body if
your route reads one.
Plain Text
textAdapter reads any route that writes text, and sseAdapter any that writes events.
// app/api/chat/route.ts
// Each message's role and text, as these adapters send them.
const isConversation = (
value: unknown
): value is { role: 'user' | 'assistant'; content: string }[] =>
Array.isArray(value) &&
value.length <= 100 &&
value.every(
message =>
(message?.role === 'user' || message?.role === 'assistant') &&
typeof message.content === 'string'
);
export async function POST(request: Request) {
const { messages } = await request.json();
if (!isConversation(messages)) {
return new Response('Bad request', { status: 400 });
}
const stream = await yourModel.streamText(messages, {
signal: request.signal,
});
return new Response(stream, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
Security
- Keys stay on the server. No adapter takes an API key, only your route's URL. Never point an adapter at a provider's own URL: the key would have to be in the browser.
- Your server decides. It sets the model, the system prompt, the tools and any limits, the same for every request, and reads nothing else from the body but the messages.
- The history is the browser's. A browser can send any messages, tool results and approvals. Before your server runs a tool, it checks that it issued that call and that the input is one it allows, as it would check any form.
- Approvals fail closed. A tool you haven't listed waits for a decision, a call can't be decided before its input is complete, a decision applies once, and an edit runs only as the approval's input.
- Model output is untrusted. Text, tool inputs and outputs, sources and data can all hold
whatever a prompt injection put there. Render them as text, check a URL before it becomes a link,
and render
dataparts only through components you choose. - Requests retry only before the reply starts. A network failure, a 408, a 429 or a 5xx is tried
again (up to
maxRetries, honoringRetry-After); once a reply has started, trying again is the user's choice, withregenerate. A reply going on, sent back with its new tool results or decisions (trigger: 'continue'), is never tried again, since your server may have acted on them before it failed. A new message's request is, though its history holds results from earlier turns. - Tools can't loop on their own. A reply goes back to the model by itself at most
maxStepstimes in a row, after which the user has to act.
API
function useChat<TMetadata = unknown>(
options: UseChatOptions<TMetadata>
): UseChatResult<TMetadata>;
Options
| Option | Type | Default | Description |
|---|---|---|---|
adapter | ChatAdapter | — | Reads your route's wire format. It's read on each request, so it can change. |
messages | ChatMessage[] | — | Every message, every branch, when you hold the history. |
defaultMessages | ChatMessage[] | [] | The messages to start with, when the hook holds the history. |
onMessagesChange | (messages: ChatMessage[]) => void | — | Called with every message, every branch, each time they change: at most once a frame while a reply streams, and at once when it ends. |
tools | Record<string, ChatToolConfig> | — | The tools the browser knows: needsApproval (true by default, or a function of the input) and execute, which runs the tool in the browser. A tool not listed waits for a decision. |
upload | (file: File, { signal }) => Promise<ChatUploadedFile> | — | Stores an attached file and resolves its url, mediaType and, optionally, name and size. Without it a file becomes a data: URL, and one over 5 MB fails. |
body | Record<string, unknown> | () => Record<string, unknown> | — | Extra fields for each request's body, or a function that returns them when the request is made. |
onFinish | (message: ChatMessage) => void | — | Called when a reply's stream has finished, also when it waits on a tool call. Not called when it fails or is stopped, including when onMessagesChange, seeing the finished reply, stops the chat or starts another turn. |
onError | (error: ChatError) => void | — | Called when a request fails, or a send is refused, with the error and its code. |
generateId | () => string | — | Makes the id of each new message and part. The default doesn't need a secure context. |
maxRetries | number | 2 | How many times a request is tried again after a network failure, a 408, a 429 or a 5xx, before any of its reply has arrived. A reply going on with its new tool results or decisions is never tried again. |
idleTimeout | number | 0 | Milliseconds the server may take to answer, and then a reply may go without a byte, before it fails, or 0 for no limit. |
maxSteps | number | 5 | How many times in a row a reply goes back to the model by itself, after tools that needed no decision ran in the browser. Then the reply ends, done, with their results recorded. |
The callbacks are read when they fire, so an inline function is fine.
Returns
| Value | Type | Description |
|---|---|---|
messages | ChatMessage[] | The branch on screen, oldest first. |
status | 'idle' | 'submitted' | 'streaming' | 'awaiting-action' | 'error' | Where the conversation is. |
error | ChatError | undefined | Why the last request failed, or the last send was refused, until the next one or clearError. See Errors. |
send | (input: string | ChatInput) => Promise<void> | Adds the user's message and a reply to the end of the branch on screen, and streams the reply. ChatInput is { text, files?, metadata? }. A file the adapter can't carry is refused first. |
stop | () => void | Stops the reply. It keeps what arrived and becomes aborted, and calls still waiting are given up. |
regenerate | (messageId?: string) => Promise<void> | Writes a new reply beside the given one, or the last one on screen, and switches to it. Given a user message, it writes a new reply to it. |
edit | (userMessageId: string, input: string | { text, files? }) => Promise<void> | Adds an edited copy of a question beside it, switches to it, and streams a reply. Files carry over unless the edit brings its own. |
getBranches | (messageId: string) => { index: number; count: number } | Where a message sits among the messages that share its parent. |
switchBranch | (messageId: string, index: number) => void | Shows the branch at index among the message's siblings. |
respond | (toolCallId: string, decision: { approved, input?, note? }, messageId?: string) => void | Decides a call waiting for a decision, once. input is the user's edit, which runs in place of the model's; note goes to the model with a denial. |
addToolOutput | (toolCallId: string, result: { output } | { errorText }, messageId?: string) => void | Records what a call returned, for a call that needs no decision or was approved. Both go to the call on the branch on screen, or in the reply messageId names. |
setMessages | (next: ChatMessage[] | (previous) => ChatMessage[]) => void | Replaces every message. A reply it drops stops streaming, and a tool running for a call it drops stops. A reply still streaming keeps the metadata and parentId you set on it. A function shouldn't call setMessages itself: one that does on every run throws. |
clearError | () => void | Clears error, and a status of error with it. |
On the server the hook fetches nothing, and once the component calling it unmounts, the request in flight, any tool running in the browser and any upload stop, and nothing changes after.
The Adapter Contract
An adapter is an object the hook calls; write one for a wire format of your own.
interface ChatAdapter {
/** `sse` hands the parser server-sent events; `text` each decoded chunk. */
format: 'sse' | 'text';
buildRequest(context: {
messages: ChatMessage[]; // the branch, ending where the reply goes
trigger: 'send' | 'regenerate' | 'continue';
body?: Record<string, unknown>;
messageId?: string; // the reply `regenerate` replaces
}): { url: string; init: RequestInit };
/** A fresh parser for each response, which may keep state. */
createParser(): ChatStreamParser;
fetch?: (url: string, init: RequestInit) => Promise<Response>;
/** `true` when your server runs an approved tool itself. */
sendsApprovals?: boolean;
/** The media types of the files it carries; left out, any; empty, none. */
accept?: readonly string[];
}
interface ChatStreamParser {
(event: { event: string; data: string; id: string }): ChatUpdate[];
/** Called once the body ends. */
end?: () => ChatUpdate[];
}
The hook does the fetching, the decoding and the framing, so a parser only turns one event into
ChatUpdates: part-start, delta and part-end for text and reasoning, tool-start,
tool-delta, tool-input, tool-approval, tool-output, tool-error and tool-denied for tool
calls, source, file, data, step-start, step-reset, metadata for the reply's
metadata, finish, error, abort, and end
once the stream has finished as it should. Reading stops at end, so a route may keep the connection
open after it. A stream that ends with no end marks the reply error. A request builder that
can't send something throws a ChatError (below) rather than leave it out.
Errors
error, onError and a failed message's error carry a stable code, so your app can word or
translate them; the message is English, as a default. retryable says whether regenerate may
help.
| Code | What happened |
|---|---|
an HTTP status, such as 429 | Your route answered with an error. |
network | The route couldn't be reached, or the connection closed before the reply finished. |
timeout | The route took longer than idleTimeout to answer, or the reply stopped arriving. |
incomplete | The stream ended before it said it was done. |
stream | The route sent an error in the stream with no code; one with a code (overloaded_error) keeps it. |
invalid-event | The stream sent an event that isn't JSON. |
file-refused | The adapter can't carry a file of that type. |
file-too-large | A file is over 5 MB, with no upload. |
file-unreadable | A file couldn't be read. |
file-url | A file's URL is one the provider can't fetch. |
upload-failed | upload threw or rejected. |
unexpected | Code threw outside fetching and reading: building the request (the body option, say), handling the reply's stream (a parser of your own), or your callbacks (generateId, or an onMessagesChange that throws as a turn starts). A retry won't help. |
ChatError is exported, so a custom adapter can throw one with a code of its own.
Accessibility
- Put the messages in an element with
role="log", and setaria-busywhilestatusissubmittedorstreaming, so a screen reader doesn't read a reply word by word. - Announce that a reply has started and that it's done in a status region, rather than each update.
- Give a tool call's Approve and Deny real buttons, with Approve disabled until the call's
stateisawaiting-approval, and show the input that will run, the user's edit when there is one. - Name the branch picker's buttons ("Previous version", "Next version"), and say which branch is showing in text.
- When a reply fails, show
message.error.messagein the thread, and offerregenerate.
Related Components
useConvos: The list of conversations, for a sidebar.- AI kit: What the kit holds, and what's planned.