shadcn.io is an independent project built on shadcn/ui
On this page9 sections
TanStack AI (opens in a new tab) runs the model and streams its reply: chat() with a provider adapter on the server, useChat from @tanstack/ai-react in the browser. Our components draw the conversation. Each message arrives as a list of parts (text, thinking, tool calls and their results), and each kind of part has a component.
There's no TanStack AI component to install. This guide builds the Chat pattern on TanStack AI 0.40: a tool, a route handler, a client component that renders every part, and the same UI running with no model at all. The components are the ones the AI SDK guide uses; only the way you read the parts changes.
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. On TanStack AI those are a thinking part, a tool-call with its tool-result, and a text part.
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 status | What it holds | Component |
|---|---|---|
text | The reply so far, in content | MarkdownReply in a Message, from the Markdown guide |
thinking | The model's reasoning, in content | A Reasoning line: a Trace that opens while it streams |
tool-call | A call: name, arguments as JSON, a state, then output | A Tool line, its output in a Code Block |
tool-result | The call's result: toolCallId, content, a state and an error | The same Tool line, read with its call |
tool-call in approval-requested | A call waiting for the person, with approval.id | An Item with Approve and Deny |
image, audio, video, document | Media in a message | Attachment |
status submitted | Sent, before the first part arrives | A Marker with the Shimmer class |
TanStack AI's message parts have no source part, so Sources has nothing to read from the stream on its own. If a tool returns links, list them from its output.
Install
Add TanStack AI
bun add @tanstack/ai @tanstack/ai-client @tanstack/ai-react @tanstack/ai-openai zodThe code here is for @tanstack/ai 0.40, @tanstack/ai-client 0.20 and @tanstack/ai-react 0.16. @tanstack/ai-openai is the OpenAI adapter; Anthropic, Gemini, OpenRouter, Ollama and others have their own packages. Zod 4 describes the tool's input and output.
Add the components
Chat adds Message Scroller, Message, Bubble and Input Group. Tool adds Trace and Code Block, which the reasoning line is drawn with too. Marker is the line shown while the model starts, and Item holds an approval.
Add the Markdown renderer
bun add @tanstack/markdownThen create components/markdown-reply.tsx as the Markdown guide shows. Text parts render through it, with fenced code in a Code Block.
Write the route
useChat posts the conversation to your route and reads Server-Sent Events back. The route defines the tool, runs chat() and streams the result:
import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
import { z } from "zod";
import { runInSandbox } from "@/lib/sandbox";
const runCommand = toolDefinition({
name: "runCommand",
description: "Run a shell command in the project and return its output.",
needsApproval: true,
inputSchema: z.object({ command: z.string() }),
outputSchema: z.object({ stdout: z.string() }),
}).server(async ({ command }) => ({ stdout: await runInSandbox(command) }));
export async function POST(request: Request) {
const { messages } = await request.json();
const stream = chat({
adapter: openaiText("gpt-4o"),
messages,
systemPrompts: ["You are a coding agent. Reply in Markdown."],
tools: [runCommand],
});
return toServerSentEventsResponse(stream);
}toolDefinition()describes the tool once..server()gives it an implementation that runs on the server;.client()would run it in the browser instead, with the same types.needsApproval: truemakes the call wait for the person before it runs.runInSandboxis yours to write: run the command in an isolated environment, never in the server's own process.- The adapter needs your provider's key. The OpenAI adapter's docs (opens in a new tab) say where it reads it.
The client sends an AG-UI RunAgentInput body: messages, threadId, runId, tools and forwardedProps. chat() takes those messages as they come. To validate the body first, chatParamsFromRequest(request) from @tanstack/ai parses it and returns the same fields. It throws a 400 Response for a body that doesn't fit, so in a Next.js route handler, catch it and return it:
export async function POST(request: Request) {
try {
const { messages, runId, threadId } = await chatParamsFromRequest(request);
const stream = chat({
adapter: openaiText("gpt-4o"),
messages,
runId,
systemPrompts: ["You are a coding agent. Reply in Markdown."],
threadId,
tools: [runCommand],
});
return toServerSentEventsResponse(stream);
} catch (error) {
// A body that isn't a RunAgentInput: return the 400 as it is.
if (error instanceof Response) {
return error;
}
throw error;
}
}Build the chat
One client component holds the conversation: the thread, a line while the model starts, the error, and the field.
"use client";
import {
type ConnectionAdapter,
fetchServerSentEvents,
type UIMessage,
useChat,
} from "@tanstack/ai-react";
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";
// Created once: a new connection would create a new chat client.
const routeConnection = fetchServerSentEvents("/api/chat");
const textOf = (message: UIMessage) =>
message.parts.map((part) => (part.type === "text" ? part.content : "")).join("");
export function Chat(props: {
connection?: ConnectionAdapter;
initialMessages?: UIMessage[];
}) {
const {
addToolApprovalResponse,
error,
messages,
reload,
sendMessage,
status,
stop,
} = useChat({
connection: props.connection ?? routeConnection,
initialMessages: props.initialMessages,
});
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.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 reload()} 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 ? () => 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:
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 connection is created once.
useChatmakes a new chat client when its connection changes, sofetchServerSentEvents("/api/chat")lives outside the component. Its second argument takesheaders,credentialsand abody. - The thread anchors each question.
scrollAnchoron the person's message settles it near the top while the reply streams into the room below, andautoScrollfollows the reply until the reader scrolls up. The content isaria-busywhile a reply is on its way. See Message Scroller. statusissubmitteduntil the first part arrives, thenstreaming, thenready, orerrorwhen the request failed. While it'ssubmitted, the thread ends on a Thinking Marker withrole="status".- Stop and retry. While the chat is busy, the send button is Stop and calls
stop(). When a request fails,errorholds it, and the Marker above the field callsreload()to run the last turn again. sendMessagetakes a string, or{ content }with text and media parts for images and documents.
An agent's message with Copy, Like and Dislike buttons in its footer, and a message of yours that failed to send, with a Retry button next to the error. Put the same MessageFooter under a finished reply for actions like Copy, and Retry with reload() on the last one.
Render the agent's turn
AssistantTurn walks the message's parts in order. Only the last part of a streaming message can still be growing, so that's the one marked live.
import type { ToolResultPart } from "@tanstack/ai-client";
import type { UIMessage } from "@tanstack/ai-react";
import { ReasoningLine } from "@/components/chat/reasoning-line";
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";
export function AssistantTurn({
message,
onApproval,
streaming,
}: {
message: UIMessage;
onApproval: (response: { approved: boolean; id: string }) => void;
streaming: boolean;
}) {
return (
<Message>
<MessageContent className="gap-3">
{message.parts.map((part, index) => {
const key = `${message.id}-${index}`;
const live = streaming && index === message.parts.length - 1;
switch (part.type) {
case "text":
return <MarkdownReply key={key} streaming={live} text={part.content} />;
case "thinking":
return (
<Trace key={key}>
<ReasoningLine running={live} text={part.content} />
</Trace>
);
case "tool-call":
return (
<ToolLine
call={part}
key={key}
onApproval={onApproval}
result={message.parts.find(
(other): other is ToolResultPart =>
other.type === "tool-result" && other.toolCallId === part.id
)}
streaming={streaming}
/>
);
default:
return null;
}
})}
</MessageContent>
</Message>
);
}
A tool-result part renders nothing on its own: the Tool line reads it with its call. The reply stays out of a bubble, as the page's text with room for lists and code.
Reasoning
A thinking part is a line that reads Thinking while it streams, open on the reasoning, then Thought, folded shut. It's the same component as in the AI SDK guide: it takes the text and a running flag, not a part.
"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>
);
}
A thinking part has no streaming state of its own. While the message streams and the thinking is its last part, the model is still thinking; once text starts after it, the line folds shut.
Tool calls
A tool call's line comes from two parts: the tool-call, with its state, and the tool-result that arrives when the tool has run. The arguments are the JSON the model wrote, partial while they stream, so parse them carefully.
tool-call state | tool-result | Line |
|---|---|---|
awaiting-input, input-streaming, input-complete | None yet | Running …, or Failed to run … if the chat stopped first |
approval-requested | None | An Item asking to run it, with Deny and Approve |
approval-responded | None yet | Running … if approved, Denied … if not |
complete | state complete | Ran …, opening on the call's output |
error | state error | Failed to run …, opening on the result's error |
import type { ToolCallPart, ToolResultPart } from "@tanstack/ai-client";
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";
/** The command from the call's arguments: JSON, partial while it streams. */
function commandOf(call: ToolCallPart) {
try {
return String(JSON.parse(call.arguments).command ?? call.name);
} catch {
return call.name;
}
}
export function ToolLine({
call,
onApproval,
result,
streaming,
}: {
call: ToolCallPart;
onApproval: (response: { approved: boolean; id: string }) => void;
result?: ToolResultPart;
streaming: boolean;
}) {
const command = commandOf(call);
const approvalId = call.approval?.id;
// A question for the reader, not a step the agent took: outside the Trace.
if (call.state === "approval-requested" && approvalId) {
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: approvalId })}
size="sm"
variant="outline"
>
Deny
</Button>
<Button
onClick={() => onApproval({ approved: true, id: approvalId })}
size="sm"
>
Approve
</Button>
</ItemActions>
</Item>
);
}
if (call.approval?.approved === false) {
return (
<Trace>
<TraceLine>
<TraceIcon>
<TerminalIcon aria-hidden="true" />
</TraceIcon>
<TraceTitle>Denied {command}</TraceTitle>
</TraceLine>
</Trace>
);
}
if (result && result.state !== "streaming") {
const failed = result.state === "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 ? result.error : call.output?.stdout}
</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
);
}
// Still running, or approved and waiting for the route to run it.
const running = streaming || call.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>
);
}
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.
The call's output is the tool's result parsed from JSON, so it has the shape of the tool's outputSchema. The tool-result part keeps the raw content as the tool returned it. Without typed tools on the client, output is untyped; pass your client tools to useChat to type it by tool name.
Approvals
With needsApproval: true, the call stops at approval-requested and carries an approval.id. The Item asks the reader, and addToolApprovalResponse({ id, approved }) records the answer. The client then sends the follow-up request on its own once every pending call in the message is answered, with no option to set, and the route runs the command or skips it.
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. TanStack's tool approval docs (opens in a new tab) cover the server side in full.
Start the conversation
An empty thread is easier to start with a few prompts the reader can send in one click. Each is a Suggestion: an outline Button whose label goes to sendMessage word for word.
Six prompts in a row above the field, scrolling sideways when they don't fit. Click one and it's sent as written, with the agent's reply under it. Anything typed instead gets a note that the demo only knows its suggestions.
Run it without a model
@shadcn/helpers, from shadcn, scripts a conversation in code and replays it through TanStack AI's useChat as real AG-UI events, with no route, network or API key. Text and reasoning stream word by word, and tool calls move from input to result.
bun add @shadcn/helpersIts transport() is a connection adapter, the same kind fetchServerSentEvents returns, so the Chat component runs unchanged:
"use client";
import { createChat } from "@shadcn/helpers/tanstack-ai";
import { Chat } from "@/components/chat/chat";
const script = createChat()
.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.");
});
const initialMessages = script.get();
const connection = script.transport({
fallback: "This preview has one scripted turn. In your app, the route answers.",
});
export default function ChatPreview() {
return (
<main className="mx-auto flex h-dvh w-full max-w-2xl flex-col p-4">
<Chat connection={connection} initialMessages={initialMessages} />
</main>
);
}get()returns the script as TanStackUIMessages, so the preview opens on the finished turn: athinkingpart, atool-callwith itstool-result, and the text.get(0)starts empty.script.next(messages)returns the next scripted user message, andappend(next)fromuseChatsends it as written.fallbackstreams for anything sent after the script runs out. Without one, the connection throws.- In tests,
script.transport({ delayMs: 0 })andwriter.text(text, { mode: "instant" })stream without waiting, the same way on every run.
The writer covers text, reasoning, tool calls with an output or an error, timing and errors. It has no approval option and no sources, so script those with the AI SDK helper or test them against your route.
TanStack AI or the AI SDK
Both stream into the same components, so the choice doesn't change your UI, only the code that reads the parts. What differs, from each library's own types and docs:
| TanStack AI | AI SDK | |
|---|---|---|
| Version used here | @tanstack/ai 0.40, @tanstack/ai-react 0.16 | ai 7, @ai-sdk/react 4 |
| Models | A provider adapter: openaiText("gpt-4o") | A model string through the Vercel AI Gateway, or a provider package |
| Tools | toolDefinition(), then .server() or .client() with the same types | tool() with an execute on the server; no execute runs it on the client |
| Approvals | needsApproval on the tool; the client sends the follow-up itself | toolApproval on streamText; sendAutomaticallyWhen sends the follow-up |
| Reasoning part | thinking, without a state | reasoning, with state |
| Sources | No source part | source-url with sendSources: true |
| Wire format | AG-UI events over Server-Sent Events | The UI message stream |
| UI packages | React, Solid, Vue, Svelte and Preact | React, Vue, Svelte and Angular |
Pick the AI SDK for sources as message parts, a scripted approval in previews, or a codebase already on AI SDK Elements. Pick TanStack AI for one tool definition that runs on either side, the AG-UI protocol, or a Solid or Preact app. TanStack keeps its own comparison with the AI SDK (opens in a new tab).
FAQ
Is there a TanStack AI 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. They're the same components as on the AI SDK guide; only the code that reads each part differs.
What does useChat send to my route?
fetchServerSentEvents posts an AG-UI RunAgentInput as JSON: messages, threadId, runId, tools, forwardedProps, and data, a copy of forwardedProps for older servers. Pass messages to chat() as it is. To validate the body, chatParamsFromRequest(request) returns the same fields and throws a 400 Response when it doesn't fit.
How do tool approvals work in TanStack AI?
Set needsApproval: true in toolDefinition(). The tool-call part reaches the client in approval-requested with an approval.id; answer with addToolApprovalResponse({ id, approved }). Once every pending call in the message has an answer, the client sends the follow-up request itself, with nothing like the AI SDK's sendAutomaticallyWhen to set.
How do I show the model's reasoning?
Render each thinking part as a reasoning line with its content. The part has no streaming state, so treat it as running while the message streams and it's the message's last part. The model has to send reasoning: TanStack lists thinking among the Anthropic adapter's features.
Where does a tool call's output come from?
From two places. The tool-call part gets output, the result parsed from JSON, and a complete or error state. A sibling tool-result part, matched by toolCallId, keeps the raw content, its own state, and an error message when the tool failed. The Tool line on this page reads both.
Can I show sources with TanStack AI?
Not from a part: TanStack AI's message parts are text, thinking, tool calls and results, media, structured output and UI resources, with no source part. If a tool returns links, list them from its output with the Sources pattern, which only needs a URL and a title for each.
How do I preview the chat without a model?
Script it with createChat() from @shadcn/helpers/tanstack-ai, then pass chat.get() as initialMessages and chat.transport() as the connection. It replays text, reasoning and tool calls as AG-UI events through the real useChat, offline and the same on every run. Create the connection once, outside the component.
Can the TanStack helper script an approval?
No. Its writer scripts text, reasoning, tool calls that end with an output or an error, pauses and errors; its tool options have no approval. The AI SDK helper does script approvals, as the AI SDK guide shows, or test the approval against your route.
Should I use TanStack AI or the AI SDK?
Either works with these components. TanStack AI suits one tool definition shared by server and client, the AG-UI protocol, and Solid or Preact apps. The AI SDK suits apps that need sources as message parts, model strings through the Vercel AI Gateway, or a move from AI SDK Elements.
Which model providers does TanStack AI support?
Each provider is its own adapter package: @tanstack/ai-openai, @tanstack/ai-anthropic, @tanstack/ai-gemini, @tanstack/ai-openrouter, @tanstack/ai-ollama, @tanstack/ai-grok and @tanstack/ai-groq among them. Swap the adapter in chat({ adapter }); the parts the client receives keep the same shape.
How do I stop or retry a reply?
stop() ends the reply that's streaming, and reload() runs the last turn again. When a request fails, status is error and error holds it; the chat on this page shows a Marker above the field that calls reload().
Does the route work outside Next.js?
Yes. The handler takes a Request and returns a Response. chatParamsFromRequest throws its 400 as a Response, which TanStack Start, SolidStart, Remix and React Router 7 return on their own; in Next.js, catch it as shown above. To set up a TanStack Start app, see TanStack Start.