Skip to content

shadcn.io is an independent project built on shadcn/ui

Guides

AI SDK

Build a streaming chat on the Vercel AI SDK 7: a route with streamText, useChat in the browser, and each message part drawn with our components.

On this page8 sections

The AI SDK (opens in a new tab) runs the model, streams its reply and keeps the conversation: streamText on the server, useChat from @ai-sdk/react in the browser. Our components draw it. A message arrives as a list of parts (text, reasoning, tool calls, sources), and each kind of part has a component.

There's no AI SDK component to install. This guide builds the Chat pattern on a real model with AI SDK 7: a tool, a route handler, a client component that renders every part, and the same UI running with no model at all.

Preview width

Press send to play a scripted thread of three turns. The agent's reasoning streams into a Trace, a command reads Running until its output arrives and then Ran, and the reply comes as Markdown with fenced code in a Code Block. The demo's parts are shaped like the AI SDK's reasoning, tool-* and text parts, played on timers instead of a model.

How the parts map

useChat gives you messages, each with a role and parts, and a status. Render the person's text in a Bubble, and the agent's parts in order:

Part or statusWhat it holdsComponent
textThe reply, with state streaming then doneMarkdownReply in a Message, from the Markdown guide
reasoningThe model's thinking, when it sends itA Reasoning line: a Trace that opens while it streams
tool-<name>A call: input, then output or errorText, with a stateA Tool line, its output in a Code Block
tool-<name> in approval-requestedA call waiting for the personAn Item with Approve and Deny
source-urlA page the reply cites: url and an optional titleSources: one line that opens on the links
fileA file in a message: mediaType, url, filenameAttachment
status submittedSent, before the first part arrivesA Marker with the Shimmer class

Install

Add the AI SDK

bun add ai @ai-sdk/react zod

The code here is for ai 7 and @ai-sdk/react 4, which need Node.js 22 or newer. Zod describes the tool's input.

Add the components

shadcn CLILocked
Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Chat adds Message Scroller, Message, Bubble and Input Group. Tool adds Trace and Code Block, which the reasoning and source lines are drawn with too. Marker is the line shown while the model starts, and Item holds an approval.

Add the Markdown renderer

bun add @tanstack/markdown

Then create components/markdown-reply.tsx as the Markdown guide shows. Text parts render through it, with fenced code in a Code Block.

Connect a model

A model string such as "anthropic/claude-sonnet-4.6" goes through the Vercel AI Gateway (opens in a new tab), the AI SDK's default, which reads its key from the environment:

.env.local
AI_GATEWAY_API_KEY=your-api-key

To call a provider directly instead, install its package and pass its model: anthropic("claude-sonnet-4-5") from @ai-sdk/anthropic reads ANTHROPIC_API_KEY.

Define the tool

The agent gets one tool, runCommand. Defining it in its own file lets the client import the message type without importing the tool's code.

lib/ai/tools.ts
import { type InferUITools, tool, type UIDataTypes, type UIMessage } from "ai";
import { z } from "zod";

import { runInSandbox } from "@/lib/sandbox";

export const tools = {
  runCommand: tool({
    description: "Run a shell command in the project and return its output.",
    inputSchema: z.object({ command: z.string() }),
    execute: async ({ command }) => ({ stdout: await runInSandbox(command) }),
  }),
};

/** The messages useChat holds, with tool parts typed from these tools. */
export type ChatMessage = UIMessage<
  unknown,
  UIDataTypes,
  InferUITools<typeof tools>
>;

runInSandbox is yours to write: run the command in an isolated environment, never in the server's own process. With ChatMessage, a tool-runCommand part has a typed input.command and output.stdout.

Write the route

useChat posts the conversation to /api/chat and reads a stream of UI message parts back. In the Next.js App Router, that's a route handler:

app/api/chat/route.ts
import { convertToModelMessages, isStepCount, streamText } from "ai";

import { type ChatMessage, tools } from "@/lib/ai/tools";

export async function POST(request: Request) {
  const { messages }: { messages: ChatMessage[] } = await request.json();

  const result = streamText({
    model: "anthropic/claude-sonnet-4.6",
    instructions: "You are a coding agent. Reply in Markdown.",
    messages: await convertToModelMessages(messages),
    tools,
    toolApproval: { runCommand: "user-approval" },
    stopWhen: isStepCount(5),
  });

  return result.toUIMessageStreamResponse({ sendSources: true });
}
  • convertToModelMessages returns a Promise in AI SDK 7: await it.
  • instructions is the system prompt. system still works in 7, marked deprecated.
  • toolApproval makes runCommand wait for the person. Instead of running it, streamText streams an approval request, and runs the command on the next request if the person approved. In AI SDK 7 this is set on streamText; needsApproval on the tool itself is deprecated.
  • stopWhen: isStepCount(5) lets the model answer after a tool result. The default, isStepCount(1), ends the turn as soon as a tool has run.
  • toUIMessageStreamResponse sends reasoning parts by default (sendReasoning), but sources only with sendSources: true.

The handler takes a Request and returns a Response, so any server that works that way can host it.

Build the chat

One client component holds the conversation: the thread, a line while the model starts, the error, and the field.

components/chat/chat.tsx
"use client";

import { useChat } from "@ai-sdk/react";
import {
  type ChatTransport,
  lastAssistantMessageIsCompleteWithApprovalResponses,
} from "ai";
import { ArrowUpIcon, RotateCcwIcon, SquareIcon } from "lucide-react";
import { type FormEvent, useRef, useState } from "react";

import { AssistantTurn } from "@/components/chat/assistant-turn";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupTextarea,
} from "@/components/ui/input-group";
import { Marker, MarkerContent, MarkerIcon } from "@/components/ui/marker";
import { Message, MessageContent } from "@/components/ui/message";
import {
  MessageScroller,
  MessageScrollerButton,
  MessageScrollerContent,
  MessageScrollerItem,
  MessageScrollerProvider,
  MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import type { ChatMessage } from "@/lib/ai/tools";

const textOf = (message: ChatMessage) =>
  message.parts.map((part) => (part.type === "text" ? part.text : "")).join("");

export function Chat(props: {
  messages?: ChatMessage[];
  transport?: ChatTransport<ChatMessage>;
}) {
  const {
    addToolApprovalResponse,
    error,
    messages,
    regenerate,
    sendMessage,
    status,
    stop,
  } = useChat<ChatMessage>({
    messages: props.messages,
    // Once every approval has an answer, send it back to the route.
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
    transport: props.transport,
  });
  const [text, setText] = useState("");
  const formRef = useRef<HTMLFormElement>(null);
  const busy = status === "submitted" || status === "streaming";
  const canSend = text.trim().length > 0 && !busy;

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (canSend) {
      void sendMessage({ text: text.trim() });
      setText("");
    }
  };

  return (
    <MessageScrollerProvider autoScroll>
      <div className="flex h-full min-h-0 flex-col gap-4">
        <div className="min-h-0 flex-1">
          <MessageScroller>
            <MessageScrollerViewport>
              <MessageScrollerContent aria-busy={busy} className="gap-6">
                {messages.map((message) => (
                  <MessageScrollerItem
                    key={message.id}
                    messageId={message.id}
                    scrollAnchor={message.role === "user"}
                  >
                    {message.role === "user" ? (
                      <Message align="end">
                        <MessageContent>
                          <Bubble align="end" variant="muted">
                            <BubbleContent>{textOf(message)}</BubbleContent>
                          </Bubble>
                        </MessageContent>
                      </Message>
                    ) : (
                      <AssistantTurn
                        message={message}
                        onApproval={addToolApprovalResponse}
                        streaming={
                          status === "streaming" && message === messages.at(-1)
                        }
                      />
                    )}
                  </MessageScrollerItem>
                ))}
                {status === "submitted" ? (
                  <MessageScrollerItem>
                    <Marker role="status">
                      <MarkerContent className="shimmer">Thinking...</MarkerContent>
                    </Marker>
                  </MessageScrollerItem>
                ) : null}
              </MessageScrollerContent>
            </MessageScrollerViewport>
            <MessageScrollerButton />
          </MessageScroller>
        </div>
        {error ? (
          <Marker
            className="text-destructive"
            render={<button onClick={() => void regenerate()} type="button" />}
          >
            <MarkerIcon>
              <RotateCcwIcon aria-hidden="true" className="size-4" />
            </MarkerIcon>
            <MarkerContent>Retry the failed reply</MarkerContent>
          </Marker>
        ) : null}
        <form onSubmit={handleSubmit} ref={formRef}>
          <InputGroup>
            <InputGroupTextarea
              aria-label="Message"
              className="p-3"
              onChange={(event) => setText(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter" && !event.shiftKey) {
                  event.preventDefault();
                  formRef.current?.requestSubmit();
                }
              }}
              placeholder="Ask the agent..."
              value={text}
            />
            <InputGroupAddon align="block-end">
              <InputGroupButton
                aria-label={busy ? "Stop" : "Send"}
                className="ms-auto"
                disabled={!(busy || canSend)}
                onClick={busy ? () => void stop() : undefined}
                pill
                size="icon-sm"
                type={busy ? "button" : "submit"}
                variant="default"
              >
                {busy ? (
                  <SquareIcon aria-hidden="true" className="size-3 fill-current" />
                ) : (
                  <ArrowUpIcon aria-hidden="true" />
                )}
              </InputGroupButton>
            </InputGroupAddon>
          </InputGroup>
        </form>
      </div>
    </MessageScrollerProvider>
  );
}

The page gives it a height to fill:

app/chat/page.tsx
import { Chat } from "@/components/chat/chat";

export default function ChatPage() {
  return (
    <main className="mx-auto flex h-dvh w-full max-w-2xl flex-col p-4">
      <Chat />
    </main>
  );
}

The thread

useChat without a transport posts to /api/chat; pass new DefaultChatTransport({ api: "/api/agent" }) from ai for another path, headers or a body. Each message is a MessageScrollerItem with its id. scrollAnchor on the person's message settles each new question near the top, and the reply streams into the room below it; autoScroll follows the reply while the reader stays at the bottom and lets go when they scroll up. The content is aria-busy while a reply is on its way, so a screen reader announces the finished turn rather than each word. Message Scroller covers the rest of its props.

Waiting, stopping and errors

status is submitted from the moment a message is sent until the first part arrives, streaming while parts arrive, ready when the turn is done, and error when the request failed. While it's submitted, the thread ends on a Marker reading Thinking, its words sweeping with the shimmer class and announced through role="status".

Preview width

Thinking... on a plain status line, and Reading 4 files on a separator, each label sweeping with the shimmer class while the separator's rule stays still. The class comes from the Shimmer utility, which Trace installs.

While the chat is busy, the send button turns into Stop, and stop() ends the reply and keeps what arrived. When a request fails, error holds it and the Marker above the field becomes a button: regenerate() runs the last turn again, from the person's message if no reply came.

The field

The field is the Prompt Input pattern: an Input Group with a textarea and a send button that becomes Stop. Enter sends through requestSubmit, so it checks canSend exactly as the button does, and Shift+Enter starts a new line.

Preview width

Type a message and send it with Enter or the arrow: for two seconds the arrow becomes a square Stop button, as it does while a reply streams. The plus button attaches files as chips above the text, and two menus pick the model and the effort.

To send files, pass the input's FileList with the text: sendMessage({ text, files }). They arrive as file parts on the person's message, ready for Attachment.

Render the agent's turn

AssistantTurn walks the message's parts in order, so text written between two tool calls stays between them, and lists the reply's sources once at the end.

components/chat/assistant-turn.tsx
import { ReasoningLine } from "@/components/chat/reasoning-line";
import { SourceList } from "@/components/chat/source-list";
import { ToolLine } from "@/components/chat/tool-line";
import { MarkdownReply } from "@/components/markdown-reply";
import { Message, MessageContent } from "@/components/ui/message";
import { Trace } from "@/components/ui/trace";
import type { ChatMessage } from "@/lib/ai/tools";

export function AssistantTurn({
  message,
  onApproval,
  streaming,
}: {
  message: ChatMessage;
  onApproval: (response: { approved: boolean; id: string }) => void;
  streaming: boolean;
}) {
  // A reply can cite the same page twice: list each URL once.
  const sources = message.parts
    .filter((part) => part.type === "source-url")
    .filter(
      (part, index, all) =>
        all.findIndex((other) => other.url === part.url) === index
    );

  return (
    <Message>
      <MessageContent className="gap-3">
        {message.parts.map((part, index) => {
          const key = `${message.id}-${index}`;

          switch (part.type) {
            case "text":
              return (
                <MarkdownReply
                  key={key}
                  streaming={streaming && part.state === "streaming"}
                  text={part.text}
                />
              );
            case "reasoning":
              return (
                <Trace key={key}>
                  <ReasoningLine
                    running={streaming && part.state === "streaming"}
                    text={part.text}
                  />
                </Trace>
              );
            case "tool-runCommand":
              return (
                <ToolLine
                  key={key}
                  onApproval={onApproval}
                  part={part}
                  streaming={streaming}
                />
              );
            default:
              return null;
          }
        })}
        {sources.length > 0 ? <SourceList sources={sources} /> : null}
      </MessageContent>
    </Message>
  );
}

The reply stays out of a bubble: it's the page's text, with room for lists and code. Each state check also asks whether the chat is still streaming, so a reply the reader stopped never shows as live.

Reasoning

A reasoning part is a line that reads Thinking while it streams, open on the thinking, then Thought, folded shut. Until the first words arrive, it's a plain line with nothing to open. Once the reader opens or closes it, their choice wins.

components/chat/reasoning-line.tsx
"use client";

import { CircleCheckIcon, LoaderCircleIcon } from "lucide-react";
import { useState } from "react";

import {
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace";

export function ReasoningLine({ running, text }: { running: boolean; text: string }) {
  // Undefined until the reader opens or closes it: till then, it follows `running`.
  const [open, setOpen] = useState<boolean>();

  const line = (
    <TraceLine status={running ? "running" : undefined}>
      <TraceIcon>
        {running ? (
          <LoaderCircleIcon
            aria-hidden="true"
            className="animate-spin motion-reduce:animate-none"
          />
        ) : (
          <CircleCheckIcon aria-hidden="true" />
        )}
      </TraceIcon>
      <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>
    </TraceLine>
  );

  if (text.length === 0) {
    return line;
  }

  return (
    <TraceCollapsible onOpenChange={setOpen} open={open ?? running}>
      <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger>
      <TraceCollapsibleContent className="whitespace-pre-wrap">
        {text}
      </TraceCollapsibleContent>
    </TraceCollapsible>
  );
}
Preview width

The turn shows in full at first, its reasoning open. Replay streams it: the line reads Thinking while the reasoning arrives, then Thought for 5s, and folds shut as the answer starts. The AI SDK doesn't time reasoning; to show a duration, measure it on the server and send it as message metadata.

Tool calls

A tool part's state decides its line. While the call runs it's a plain line reading Running, with a shimmer. Once its output arrives it reads Ran and opens on the output in a small Code Block. A failed call keeps its error status and shows the error.

stateLine
input-streaming, input-availableRunning …, or Failed to run … if the chat stopped first
approval-requestedAn Item asking to run it, with Deny and Approve
approval-respondedRunning … if approved, Denied … if not
output-availableRan …, opening on output
output-errorFailed to run …, opening on errorText
output-deniedDenied …
components/chat/tool-line.tsx
import { TerminalIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import {
  Item,
  ItemActions,
  ItemContent,
  ItemMedia,
  ItemTitle,
} from "@/components/ui/item";
import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace";
import type { ChatMessage } from "@/lib/ai/tools";

type ToolPart = Extract<
  ChatMessage["parts"][number],
  { type: "tool-runCommand" }
>;

export function ToolLine({
  onApproval,
  part,
  streaming,
}: {
  onApproval: (response: { approved: boolean; id: string }) => void;
  part: ToolPart;
  streaming: boolean;
}) {
  const command = part.input?.command ?? "";

  // A question for the reader, not a step the agent took: outside the Trace.
  if (part.state === "approval-requested") {
    const { id } = part.approval;

    return (
      <Item size="sm" variant="outline">
        <ItemMedia variant="icon">
          <TerminalIcon aria-hidden="true" />
        </ItemMedia>
        <ItemContent>
          <ItemTitle>Run {command}?</ItemTitle>
        </ItemContent>
        <ItemActions>
          <Button
            onClick={() => onApproval({ approved: false, id })}
            size="sm"
            variant="outline"
          >
            Deny
          </Button>
          <Button onClick={() => onApproval({ approved: true, id })} size="sm">
            Approve
          </Button>
        </ItemActions>
      </Item>
    );
  }

  if (
    part.state === "output-denied" ||
    (part.state === "approval-responded" && !part.approval.approved)
  ) {
    return (
      <Trace>
        <TraceLine>
          <TraceIcon>
            <TerminalIcon aria-hidden="true" />
          </TraceIcon>
          <TraceTitle>Denied {command}</TraceTitle>
        </TraceLine>
      </Trace>
    );
  }

  if (part.state === "output-available" || part.state === "output-error") {
    const failed = part.state === "output-error";

    return (
      <Trace>
        <TraceCollapsible>
          <TraceCollapsibleTrigger>
            <TraceLine status={failed ? "error" : undefined}>
              <TraceIcon>
                <TerminalIcon aria-hidden="true" />
              </TraceIcon>
              <TraceTitle>
                {failed ? "Failed to run" : "Ran"} {command}
              </TraceTitle>
            </TraceLine>
          </TraceCollapsibleTrigger>
          <TraceCollapsibleContent>
            <CodeBlock size="sm">
              <CodeBlockContent className="max-h-64" wrap>
                {failed ? part.errorText : part.output.stdout}
              </CodeBlockContent>
            </CodeBlock>
          </TraceCollapsibleContent>
        </TraceCollapsible>
      </Trace>
    );
  }

  // Still running, or approved and waiting for the route to run it.
  const running = streaming || part.state === "approval-responded";

  return (
    <Trace>
      <TraceLine status={running ? "running" : "error"}>
        <TraceIcon>
          <TerminalIcon aria-hidden="true" />
        </TraceIcon>
        <TraceTitle>
          {running ? "Running" : "Failed to run"} {command}
        </TraceTitle>
      </TraceLine>
    </Trace>
  );
}
Preview width

Four calls in one Trace: git status --short ran, and opens on its output; pnpm dev failed, in the error color, and opens on the timeout; rm -rf dist was denied; pnpm test is still running, its title shimmering.

A tool with no execute, which runs in the browser, stays input-available after the turn ends, until you add its output with addToolOutput. Treat that state as waiting for your code, not failed.

Approvals

With toolApproval on the route, a call stops at approval-requested and the turn ends there. The Item asks the reader; addToolApprovalResponse({ id, approved }) records the answer on the part, and sendAutomaticallyWhen sends it back to the route once every pending approval in the message has one. The route then runs the command, or tells the model it was denied, and the same message carries on.

Preview width

Press Send message: the agent thinks, then asks before it runs rm -rf dist. Approve and the line reads Running, then Ran; Deny and it reads Denied. The answer follows either way. For a question with more to say than one line, use Confirmation.

Sources

source-url parts arrive when the model or a provider's search tool cites pages, and only with sendSources: true on the route. List them under the reply, each page once, in a line that counts them.

components/chat/source-list.tsx
import { ArrowUpRightIcon, GlobeIcon } from "lucide-react";

import {
  Trace,
  TraceCollapsible,
  TraceCollapsibleContent,
  TraceCollapsibleTrigger,
  TraceIcon,
  TraceLine,
  TraceTitle,
} from "@/components/ui/trace";

export function SourceList({
  sources,
}: {
  sources: { title?: string; url: string }[];
}) {
  return (
    <Trace>
      <TraceCollapsible>
        <TraceCollapsibleTrigger>
          <TraceLine>
            <TraceIcon>
              <GlobeIcon aria-hidden="true" />
            </TraceIcon>
            <TraceTitle>
              Used {sources.length} {sources.length === 1 ? "source" : "sources"}
            </TraceTitle>
          </TraceLine>
        </TraceCollapsibleTrigger>
        <TraceCollapsibleContent>
          <Trace>
            {sources.map((source) => (
              <a href={source.url} key={source.url} rel="noreferrer" target="_blank">
                <TraceLine>
                  <TraceTitle>
                    {source.title ?? new URL(source.url).hostname}
                    <span className="sr-only"> (opens in a new tab)</span>
                  </TraceTitle>
                  <TraceIcon>
                    <ArrowUpRightIcon aria-hidden="true" className="rtl:-scale-x-100" />
                  </TraceIcon>
                </TraceLine>
              </a>
            ))}
          </Trace>
        </TraceCollapsibleContent>
      </TraceCollapsible>
    </Trace>
  );
}
Preview width

A question about starting an Astro project with pnpm. The answer streams, and with its last word a line reads Used 3 sources, open on a link to each page: the agent cited the Astro docs twice, and they're listed once. A source-url part's title is optional, so a link falls back to the URL's hostname. To mark the sentence a source backs, add an Inline Citation.

Run it without a model

@shadcn/helpers, from shadcn, scripts a conversation in code and streams it through the real useChat, with no route, network or API key. Use it to build the components before a model is wired up, for a preview that renders the same way every time, and in tests.

bun add @shadcn/helpers

createChat() takes your message type, so the script's tool calls are checked against runCommand. Its transport() returns a ChatTransport, the interface DefaultChatTransport implements for the route, so the Chat component runs unchanged:

app/chat/preview/page.tsx
"use client";

import { createChat } from "@shadcn/helpers/ai-sdk";

import { Chat } from "@/components/chat/chat";
import type { ChatMessage } from "@/lib/ai/tools";

const script = createChat<ChatMessage>()
  .user("Which Node version is installed?")
  .assistant(({ writer }) => {
    writer.reasoning("node --version prints it.");
    writer
      .tool("runCommand", { input: { command: "node --version" } })
      .sleep(800)
      .output({ stdout: "v24.18.0" });
    writer.text("Node **24.18.0** is installed.");
  })
  .user("Clean up the build folder.")
  .assistant(({ writer }) => {
    writer.text("That deletes `dist`, which can't be undone.");
    writer.tool("runCommand", {
      input: { command: "rm -rf dist" },
      needsApproval: true,
      output: { stdout: "" },
    });
  })
  .assistant(({ toolCall, writer }) => {
    writer.text(
      toolCall?.approved ? "Removed `dist`." : "Okay, I left `dist` in place."
    );
  });

const messages = script.get();
const transport = script.transport({
  fallback: "This preview only knows its scripted turns.",
});

export default function ChatPreview() {
  return (
    <main className="mx-auto flex h-dvh w-full max-w-2xl flex-col p-4">
      <Chat messages={messages} transport={transport} />
    </main>
  );
}
  • get() returns the script as messages, up to the turn that waits for approval, so the preview opens on the Approve and Deny buttons. Answer, and sendAutomaticallyWhen sends the answer to the transport, which streams the last turn: toolCall.approved picks its wording.
  • get(0) starts empty. script.next(messages) returns the next scripted user message, to fill the field or send with sendMessage.
  • fallback answers anything sent after the script runs out. Without one, the transport throws.
  • In tests, script.transport({ delayMs: 0 }) and writer.text(text, { mode: "instant" }) stream without waiting, the same way on every run.

The helpers pin ai to 7.x. For the same idea on TanStack AI, see TanStack AI.

FAQ

Is there an AI SDK component to install?

No. The chat is built from components you add one by one: Message Scroller, Message, Bubble, Input Group, Trace, Code Block, Marker and Item. Chat, Reasoning, Tool, Sources and Prompt Input are patterns: their commands add those parts, and the code is yours to copy.

Which AI SDK version is this guide for?

ai 7 and @ai-sdk/react 4. In 7, convertToModelMessages returns a Promise, the system prompt is instructions (with system deprecated), tool approval is set with toolApproval on streamText (with needsApproval on a tool deprecated), and step limits use isStepCount, with stepCountIs kept as an alias.

Why does the agent stop right after calling a tool?

streamText stops when a step ends with tool results, after one step by default (isStepCount(1)), so the model never gets to answer. Set stopWhen: isStepCount(5), or another limit, and the model gets more steps to read the result and reply.

How do I ask the person before a tool runs?

Set toolApproval: { runCommand: "user-approval" } on streamText. The tool part reaches the client in approval-requested, with an approval.id; show an Item with Deny and Approve that call addToolApprovalResponse({ id, approved }). Pass sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses to useChat, so the answer goes back to the route on its own.

Why don't reasoning or sources show up?

toUIMessageStreamResponse forwards reasoning by default but sources only with sendSources: true. Beyond that, the model has to produce them: reasoning comes from models and settings that return it, and sources from providers or search tools that cite pages. The UI renders whatever parts arrive.

What do useChat's statuses mean for the UI?

submitted: the message is sent and nothing has arrived, so show the Thinking marker. streaming: parts are arriving, so lines run and the reply grows. ready: the turn is over and the person can send again. error: the request failed, and error holds why. While submitted or streaming, the send button is Stop and the thread is aria-busy.

How do I keep a long streaming reply fast?

Throttle updates with useChat({ throttle: 50 }), keep one MarkdownReply per part so finished blocks keep their DOM, and let Code Block re-highlight only the lines that changed, which it does already. Message Scroller rows skip painting while they're far off screen, so long threads stay fast.

Can I call a provider directly instead of the AI Gateway?

Yes. A model string like "anthropic/claude-sonnet-4.6" goes through the Vercel AI Gateway with AI_GATEWAY_API_KEY. Install a provider package and pass its model instead, such as anthropic("claude-sonnet-4-5") from @ai-sdk/anthropic, which reads ANTHROPIC_API_KEY. The UI doesn't change: parts look the same whichever provider streams them.

Does my route have to be at /api/chat?

No, that's only the default. Pass transport: new DefaultChatTransport({ api: "/api/agent" }) to useChat for another path; the same options take headers, body and credentials. The Chat component on this page takes the transport as a prop, so you can change it per page.

How do I send files with a message?

Pass the file input's FileList with the text: sendMessage({ text, files }). Each file becomes a file part on the person's message, with mediaType, url and filename, and the model receives it. Show them as Attachment chips: above the text in the field, as Prompt Input does, and on the sent message.

How do I build or test the chat without calling a model?

Script the conversation with createChat() from @shadcn/helpers/ai-sdk and pass chat.get() and chat.transport() to useChat. It streams text, reasoning, tool calls, approvals, sources and files through the real useChat lifecycle, offline and the same on every run.

I use AI SDK Elements. Can I switch to these components?

Yes. Chat, Reasoning, Tool, Sources and Prompt Input each have a Migrating from AI SDK Elements section, with a prompt for your coding agent that rebuilds the Elements file on our components and keeps its exports, so the code that imports it keeps working.