页面简介
Create TanStack AI messages and stream predefined conversations through useChat without a model, API route, network request, or API key.
正文摘录
SectionsIntroductionComponentsAI ElementsInstallationThemingCLITypesetSkillsRegistryChangelogComponentsAccordionAlertAlert DialogAspect RatioAttachmentAvatarBadgeBreadcrumbBubbleButtonButton GroupCalendarCardCarouselChartCheckboxCode BlockCollapsibleComboboxCommandContext MenuData TableDate PickerDialogDirectionDrawerDropdown MenuEmptyFieldHover CardInputInput GroupInput OTPItemKbdLabelMarkerMenubarMessageMessage ScrollerNative SelectNavigation MenuPaginationPopoverProgressQuestionnaireRadio GroupResizableScroll AreaSelectSeparatorSheetSidebarSkeletonSliderSpinnerSwitchTableTabsTextareaToastToggleToggle GroupTooltipTraceTypographyAI ElementsIntroductionChain of ThoughtChatCheckpointConfirmationContextFile TreeInline CitationMessageModel SelectorPlanPrompt InputQueueReasoningSourcesStack TraceSubagentSuggestionTaskTerminalTest ResultsToolGet StartedInstallationcomponents.jsonPackage ImportsThemingTypesetDark ModeCLIMonorepoSkillsJavaScriptFigmallms.txtLegacy Docs@shadcn/reactMessage ScrollerQuestionnaire@shadcn/helpersAI SDKTanStack AIFormsReact Hook FormTanStack FormFormischUtilitiesscroll-fadeshimmerRegistryIntroductionGetting StartedGitHub RegistriesRegistry DirectoryRegistry HealthExamplesNamespacesAuthenticationDynamic SearchMCP ServerOpen in v0FAQAPI Referenceregistry.jsonregistry-item.jsonTanStack AICopy PagePreviousNextCreate TanStack AI messages and stream predefined conversations through useChat without a model, API route, network request, or API key.@shadcn/helpers/tanstack-ai lets you write an AI conversation in code and stream it through TanStack AI's useChat, with no model, API route, network request, or API key. It creates native TanStack UIMessage[] values and replays each assistant response through a local connection adapter as real AG-UI events, so your components behave exactly as they would in production: text and reasoning stream word by word, and tool calls move from input to result. Copyimport { createChat } from "@shadcn/helpers/tanstack-ai" const chat = createChat() .user("What changed in this release?") .assistant("The release adds keyboard shortcuts and faster search.") .user("Can you show me the shortcuts?") .assistant("Press ⌘K to search and ⌘Enter to submit.") Pass the chat to useChat with its initial messages and local connection. TanStack AI receives the same AG-UI events it would receive from a server. Copyimport { useChat } from "@tanstack/ai-react" function Chat() { const { messages, append } = useChat({ initialMessages: chat.get(0), // starts with no messages. connection: chat.transport(), }) const nextMessage = chat.next(messages) return ( <button disabled={!nextMessage} onClick={() => { if (nextMessage) { void append(nextMessage) } }} > Send next message </button> ) } get(0) starts with no messages. append(nextMessage) adds the next predefined user message; the connection then streams its assistant response as AG-UI events. What It's For The helper decouples your chat UI from the model and the backend, so you can work on the frontend on its own. It runs offline, instantly, and the same way every time. Build components. Develop message bubbles, tool cards, and reasoning panels against realistic streaming output, without wiring up a model first. Preview and demo. Ship reproducible previews, screenshots, and videos that never depend on a live model. Write docs. Power documentation examples with conversations that render the same way on every load. Test. Assert against a deterministic stream in CI, with no network calls, token spend, or flaky model output. Installation pnpmnpmyarnbunpnpm add @shadcn/helpersCopy Usage Create a conversation, pass its messages and connection to useChat, then send each predefined user message with next(). Copy"use client" import { createChat } from "@shadcn/helpers/tanstack-ai" import { useChat } from "@tanstack/ai-react" const chat = createChat() .user("What changed in this release?") .assistant("The release adds keyboard shortcuts and faster search.") .user("Can you show me the shortcuts?") .assistant("Press ⌘K to search and ⌘Enter to submit.") const initialMessages = chat.get(0) const connection = chat.transport() export function Chat() { const { messages, append, status } = useChat({ initialMessages, connection, }) const nextMessage = chat.next(messages) const isBusy = status === "submitted" || status === "streaming" return ( <div> {messages.map((message) => ( <div key={message.id}>{/* Render the message */}</div> ))} <button disabled={!nextMessage || isBusy} onClick={() => { if (nextMessage && !isBusy) { void append(nextMessage) } }} > Send </button> </div> ) } New ChatHow can I help you today?Morning, shadcn!What are we working on today? Press send to start a new conversationDemo is read only. Press send to send messages.Copy"use client" import { createChat } from "@shadcn/helpers/tanstack-ai"View Code User Messages Messages added with this helper use the user and assistant roles. Use user() to add a user message. Existing TanStack messages are preserved when you start with createChat({ messages }). Copyconst chat = createChat().user("What changed in this release?") const [message] = chat.get() message.role // "user" message.parts // [{ type: "text", content: "What changed in this release?" }] Pass an id, or a createdAt timestamp via metadata, as the second argument when you need them. Copychat.user("What changed in this release?", { id: "user-release-question", metadata: { createdAt: "2026-01-01T10:00:00.000Z", }, }) User messages can also include files. See Files. Assistant Messages Use assistant() to add an assistant message. Copyconst chat = createChat().assistant( "The release adds keyboard shortcuts and faster search." ) const [message] = chat.get() message.role // "assistant" message.parts // [{ type: "text", content: "The release adds..." }] A string creates one text part. You can also pass an array of TanStack message parts. Copychat.assistant([ { type: "thinking", content: "I should summarize the release." }, { type: "text", content: "The release adds keyboard shortcuts." }, ]) Use the writer callback when the message should stream in smaller steps. Copychat.assistant(({ writer }) => { writer.reasoning("I should summarize the release.") writer.text("The release adds keyboard shortcuts and faster search.") }) The writer adds parts in the order you call them. Message Parts The TanStack writer supports the parts that can round-trip through its AG-UI connection: text, reasoning, and tool calls. It also supports timing and errors. Copychat.assistant(({ writer }) => { writer.reasoning("I should answer directly.") writer.text("Hello.") }) See Adapter Differences for parts that do not have an equivalent in this connection. Text Use text() to add text. Copychat.assistant(({ writer }) => { writer.text("The release adds keyboard shortcuts.") writer.text(" Search is faster too.") }) Text streams word by word when the chat is used with chat.transport(). Consecutive text calls materialize as separate parts in get(), but TanStack's stream processor combines them into one text part during playback. Use mode: "instant" to send the whole value at once, or delayMs to change the delay between text deltas. Copywriter.text("Done.", { mode: "instant" }) writer.text("This part streams more slowly.", { delayMs: 100 }) Reasoning Use reasoning() to add reasoning. It becomes a TanStack thinking part. Copychat.assistant(({ writer }) => { writer.reasoning("I should check the latest conditions first.") writer.text("Let me check the weather.") }) Reasoning uses the same delayMs and mode options as text. Copywriter.reasoning("Checking the forecast.", { mode: "instant" }) Tool Calls Use tool() to add a tool call. It returns a handle that follows the tool from input to output. Copychat.assistant(({ writer }) => { writer .tool("getWeather", { input: { city: "San Francisco" }, }) .sleep(900) .output({ city: "San Francisco", temperature: 18, condition: "Breezy", }) writer.text("It is 18°C and breezy in San Francisco.") }) The tool can finish with output() or error(). Copywriter.tool("getWeather", { input: { city: "San Francisco" } }).error() The completed TanStack message contains a tool-call part and a sibling tool-result part. Pass the same client-tool tuple used by your app to type the tool name, input, and output. Copyimport { clientTools } from "@tanstack/ai-client" import { getWeatherTool } from "@/lib/tools" const tools = clientTools(getWeatherTool.client()) const chat = createChat<typeof tools>() chat.assistant(({ writer }) => { writer .tool("getWeather", { input: { city: "San Francisco" }, }) .output({ city: "San Francisco", temperature: 18, condition: "Breezy", }) }) Files Add files to a user message with the files option. Copychat.user("Describe this image.", { files: [ { mediaType: "image/png", url: "https://example.com/screenshot.png", }, ], }) The helper converts each file into a TanStack media part based on its media type: Media typeTanStack partimage/*imageaudio/*audiovideo/*videoOtherdocument These parts are available from get(). Because next() returns the complete user UIMessage, append() preserves its text and media parts. Copyconst nextMessage = chat.next(messages) if (nextMessage) { void append(nextMessage) } Assistant media parts can be included in a static parts array and read with get(), but the AG-UI connection does not stream assistant files. Adapter Differences TanStack AI and the AI SDK use different message and streaming models. This adapter exposes only the operations it can represent end to end. FeatureBehaviorTextStreams as AG-UI text and becomes a text part.ReasoningStreams as AG-UI reasoning and becomes a thinking part.Tool callsStream input, output, and errors into tool-call and tool-result.Data and structured outputNo writer method; existing message parts remain available through get().Custom eventsNo writer method in the public adapter.Sources, reasoning files, step startsNo TanStack message or AG-UI equivalent in this adapter.Assis