页面简介
Create AI SDK 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.jsonAI SDKCopy PagePreviousNextCreate AI SDK messages and stream predefined conversations through useChat without a model, API route, network request, or API key.@shadcn/helpers/ai-sdk lets you write an AI conversation in code and stream it through useChat, with no model, API route, network request, or API key. Because the conversation streams through the real useChat lifecycle, your components behave exactly as they would in production. It supports every part type the AI SDK does: reasoning, tools, data, files, sources, and custom parts. Tool calls can also pause for real user input, including approvals. See Human in the Loop. Copyimport { createChat } from "@shadcn/helpers/ai-sdk" 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 transport. useChat receives the same typed UIMessage[] it would get from a streamed response. Copyimport { useChat } from "@ai-sdk/react" function Chat() { const { messages, sendMessage } = useChat({ messages: chat.get(0), // starts with no messages. transport: chat.transport(), }) const nextMessage = chat.next(messages) return ( <button disabled={!nextMessage} onClick={() => { if (nextMessage) { void sendMessage(nextMessage) } }} > Send next message </button> ) } get(0) starts with no messages. sendMessage(nextMessage) sends the next predefined user message; the transport then streams its assistant response. 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 This helper works alongside your existing AI SDK setup (ai and @ai-sdk/react). Import the helpers from @shadcn/helpers/ai-sdk. Usage Create a conversation, pass its messages and transport to useChat, then send each predefined user message with next(). Copy"use client" import { useChat } from "@ai-sdk/react" import { createChat } from "@shadcn/helpers/ai-sdk" 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 transport = chat.transport() export function Chat() { const { messages, sendMessage, status } = useChat({ messages: initialMessages, transport, }) 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 sendMessage(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 { useChat } from "@ai-sdk/react"View Code User Messages Messages added with this helper use the user and assistant roles. Use user() to add a user message. Existing AI SDK 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", text: "What changed in this release?" }] Pass an id or metadata as the second argument when you need them. Copychat.user("What changed in this release?", { id: "user-release-question", metadata: { source: "docs", }, }) 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", text: "The release adds...", state: "done" }] A string creates one text part. You can also pass an array of AI SDK message parts. Copychat.assistant([ { type: "text", text: "The release adds keyboard shortcuts." }, { type: "text", text: "Search is faster too." }, ]) Use the writer callback when the message has more than plain text. 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 An assistant message can contain many part types. Add them with the writer passed to assistant(), in the order you call them: Text and Reasoning Tool Calls Data Files and Sources Step Starts and Custom Parts Copychat.assistant(({ writer }) => { writer.reasoning("Let me check the weather.") writer .tool("getWeather", { input: { city: "San Francisco" } }) .output({ city: "San Francisco", temperature: 18, condition: "Breezy" }) writer.text("It is 18°C and breezy in San Francisco.") }) Text Use text() to add a text part. Copychat.assistant(({ writer }) => { writer.text("The release adds keyboard shortcuts.") writer.text(" Search is faster too.") }) Each call creates a separate text part. Text streams word by word when the chat is used with chat.transport(). Use mode: "instant" to send the whole part at once, or delayMs to change the delay between its text deltas. Copywriter.text("Done.", { mode: "instant" }) writer.text("This part streams more slowly.", { delayMs: 100 }) Pass an id when the text part needs a stable identifier. Copywriter.text("The final answer.", { id: "answer" }) Reasoning Use reasoning() to add a reasoning part. Copychat.assistant(({ writer }) => { writer.reasoning("I should check the latest conditions first.") writer.text("Let me check the weather.") }) Reasoning uses the same id, 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", { title: "Checking weather", 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(), error(), or denied(). Copywriter.tool("getWeather", { input: { city: "San Francisco" } }).error() writer.tool("getWeather", { input: { city: "San Francisco" } }).denied() Pass { preliminary: true } to output() to stream progress before the final output, as a tool with a streaming execute does. The part is output-available with preliminary: true until the final output() replaces it. Use it for a sub-agent that streams its own steps. Copywriter .tool("researchAgent", { input: { task: "Find the image cache key." } }) .output({ steps: ["Searched for cacheKey"] }, { preliminary: true }) .sleep(900) .output({ steps: ["Searched for cacheKey", "Read optimize-images.ts"] }) Pass dynamic: true to create an AI SDK dynamic-tool part instead of a typed tool-<name> part. Copywriter.tool("getWeather", { dynamic: true, input: { city: "San Francisco" }, output: { city: "San Francisco", temperature: 18, condition: "Breezy" }, }) Type the tool name, input, and output by passing your message type to createChat. It takes the same type parameter as useChat. Copyimport type { UIMessage } from "ai" type Tools = { getWeather: { input: { city: string } output: { city: string; temperature: number; condition: string } } } type ChatMessage = UIMessage<unknown, Record<string, never>, Tools> const chat = createChat<ChatMessage>() Define the message type once and use it for both createChat and useChat. Copyconst { messages } = useChat<ChatMessage>({ messages: chat.get(0), transport: chat.transport(), }) A tool call can also wait for the user instead of finishing in the script. See Human in the Loop. Human in the Loop A tool call can pause and hand control to the real user. The helper supports both AI SDK human-in-the-loop flows: client-executed tools, wh