Chat
A whole chat in one component. The thread, each answer with its code, tool calls and sources, the row of actions under it and the composer at the bottom, all wired.
Installation
Copy and paste the following code into your project.
1'use client';23import * as React from 'react';4import { Actions } from '../ai/actions';5import { type AttachmentData, Attachments } from '../ai/attachments';6import { CodeBlock } from '../ai/code-block';7import { Conversation } from '../ai/conversation';8import { PromptInput, type PromptInputMessage } from '../ai/prompt-input';9import { Reasoning } from '../ai/reasoning';10import { Response } from '../ai/response';11import { Sources } from '../ai/sources';12import { Suggestion } from '../ai/suggestion';13import { Tool, type ToolStatus } from '../ai/tool';14import { Bubble } from '../components/bubble';15import { Message } from '../components/message';16import { cn } from '../lib/cn';1718type ChatStatus = 'ready' | 'submitted' | 'streaming' | 'error';19type ChatRole = 'user' | 'assistant';20type ChatFeedback = 'up' | 'down';2122type ChatTextPart = { type: 'text'; text: string };23type ChatCodePart = { type: 'code'; code: string; language?: string };24type ChatToolPart = {25 type: 'tool';26 name: string;27 status: ToolStatus;28 input?: unknown;29 output?: unknown;30};31type ChatReasoningPart = { type: 'reasoning'; text: string };32type ChatSourcesPart = { type: 'sources'; items: { href: string; title: string }[] };33type ChatFilePart = {34 type: 'file';35 name: string;36 size?: number;37 url?: string;38 mediaType?: string;39};4041type ChatPart =42 | ChatTextPart43 | ChatCodePart44 | ChatToolPart45 | ChatReasoningPart46 | ChatSourcesPart47 | ChatFilePart;4849interface ChatMessage {50 id: string;51 role: ChatRole;52 parts: ChatPart[];53}5455interface ChatSendMessage {56 text: string;57 files?: File[];58}5960interface ChatLabels {61 placeholder: string;62 emptyTitle: string;63 emptyDescription: string;64 user: string;65 assistant: string;66 copy: string;67 copied: string;68 retry: string;69 thumbsUp: string;70 thumbsDown: string;71 send: string;72 stop: string;73 input: string;74 addFiles: string;75 scrollToBottom: string;76 sources: (count: number) => string;77}7879const DEFAULT_LABELS: ChatLabels = {80 placeholder: 'Ask anythingโฆ',81 emptyTitle: 'Start a conversation',82 emptyDescription: 'Ask a question or pick one of the suggestions.',83 user: 'You',84 assistant: 'Assistant',85 copy: 'Copy',86 copied: 'Copied',87 retry: 'Retry',88 thumbsUp: 'Good answer',89 thumbsDown: 'Bad answer',90 send: 'Send message',91 stop: 'Stop generating',92 input: 'Message',93 addFiles: 'Add files',94 scrollToBottom: 'Scroll to bottom',95 sources: (count) => `Used ${count} ${count === 1 ? 'source' : 'sources'}`,96};9798interface ChatContextValue {99 messages: ChatMessage[];100 status: ChatStatus;101 labels: ChatLabels;102 suggestions: string[];103 onSend: (message: ChatSendMessage) => void;104 onStop?: () => void;105 onRetry?: (messageId: string) => void;106 onFeedback?: (messageId: string, feedback: ChatFeedback) => void;107 onSuggestion?: (text: string) => void;108 renderMarkdown: (text: string) => React.ReactNode;109}110111const ChatContext = React.createContext<ChatContextValue | null>(null);112113type ChatItemContextValue = Pick<114 ChatContextValue,115 'status' | 'labels' | 'onRetry' | 'onFeedback' | 'renderMarkdown'116>;117118const ChatItemContext = React.createContext<ChatItemContextValue | null>(null);119120const useChatItem = (): ChatItemContextValue => {121 const context = React.use(ChatItemContext);122 if (!context) {123 throw new Error('Chat components must be used within Chat');124 }125 return context;126};127128const useChat = (): ChatContextValue => {129 const context = React.use(ChatContext);130 if (!context) {131 throw new Error('Chat components must be used within Chat');132 }133 return context;134};135136function renderParagraphs(text: string): React.ReactNode {137 return text138 .split(/\n{2,}/)139 .filter((paragraph) => paragraph.trim().length > 0)140 .map((paragraph, index) => <p key={index}>{paragraph}</p>);141}142143function messageText(message: ChatMessage): string {144 return message.parts145 .filter((part): part is ChatTextPart => part.type === 'text')146 .map((part) => part.text)147 .join('\n\n');148}149150function toAttachment(part: ChatFilePart, index: number): AttachmentData {151 return {152 id: `${part.name}-${index}`,153 filename: part.name,154 mediaType: part.mediaType,155 url: part.url,156 size: part.size,157 };158}159160interface ChatProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> {161 messages: ChatMessage[];162 status?: ChatStatus;163 onSend: (message: ChatSendMessage) => void;164 onStop?: () => void;165 onRetry?: (messageId: string) => void;166 onFeedback?: (messageId: string, feedback: ChatFeedback) => void;167 suggestions?: string[];168 onSuggestion?: (text: string) => void;169 placeholder?: string;170 emptyTitle?: string;171 emptyDescription?: string;172 labels?: Partial<ChatLabels>;173 renderMarkdown?: (text: string) => React.ReactNode;174 children?: React.ReactNode;175}176177type ChatThreadProps = React.HTMLAttributes<HTMLDivElement>;178179interface ChatMessageProps extends React.HTMLAttributes<HTMLDivElement> {180 message: ChatMessage;181 isLast?: boolean;182}183184type ChatPendingProps = React.HTMLAttributes<HTMLDivElement>;185type ChatSuggestionsProps = React.HTMLAttributes<HTMLDivElement>;186187interface ChatComposerProps extends Omit<188 React.ComponentProps<typeof PromptInput>,189 'onSubmit' | 'children'190> {191 children?: React.ReactNode;192}193194const EMPTY_SUGGESTIONS: string[] = [];195196const ChatRoot = ({197 className,198 messages,199 status = 'ready',200 onSend,201 onStop,202 onRetry,203 onFeedback,204 suggestions = EMPTY_SUGGESTIONS,205 onSuggestion,206 placeholder,207 emptyTitle,208 emptyDescription,209 labels: partialLabels,210 renderMarkdown = renderParagraphs,211 children,212 ref,213 ...props214}: ChatProps & { ref?: React.Ref<HTMLDivElement> }) => {215 const labels = React.useMemo<ChatLabels>(216 () => ({217 ...DEFAULT_LABELS,218 ...partialLabels,219 ...(placeholder !== undefined ? { placeholder } : {}),220 ...(emptyTitle !== undefined ? { emptyTitle } : {}),221 ...(emptyDescription !== undefined ? { emptyDescription } : {}),222 }),223 [partialLabels, placeholder, emptyTitle, emptyDescription],224 );225226 const callbacks = React.useRef({ onRetry, onFeedback });227228 React.useEffect(() => {229 callbacks.current = { onRetry, onFeedback };230 });231232 const retry = React.useCallback((messageId: string) => {233 callbacks.current.onRetry?.(messageId);234 }, []);235236 const feedback = React.useCallback((messageId: string, value: ChatFeedback) => {237 callbacks.current.onFeedback?.(messageId, value);238 }, []);239240 const hasRetry = onRetry !== undefined;241 const hasFeedback = onFeedback !== undefined;242243 const itemValue = React.useMemo<ChatItemContextValue>(244 () => ({245 status,246 labels,247 onRetry: hasRetry ? retry : undefined,248 onFeedback: hasFeedback ? feedback : undefined,249 renderMarkdown,250 }),251 [status, labels, hasRetry, retry, hasFeedback, feedback, renderMarkdown],252 );253254 const value = React.useMemo<ChatContextValue>(255 () => ({256 messages,257 status,258 labels,259 suggestions,260 onSend,261 onStop,262 onRetry,263 onFeedback,264 onSuggestion,265 renderMarkdown,266 }),267 [268 messages,269 status,270 labels,271 suggestions,272 onSend,273 onStop,274 onRetry,275 onFeedback,276 onSuggestion,277 renderMarkdown,278 ],279 );280281 return (282 <ChatContext value={value}>283 <ChatItemContext value={itemValue}>284 <div285 ref={ref}286 data-status={status}287 className={cn('flex h-full min-h-0 w-full flex-col', className)}288 {...props}289 >290 {children ?? (291 <>292 <ChatThread />293 <ChatComposer />294 </>295 )}296 </div>297 </ChatItemContext>298 </ChatContext>299 );300};301302ChatRoot.displayName = 'Chat';303304const ChatThread = ({305 className,306 children,307 ref,308 ...props309}: ChatThreadProps & { ref?: React.Ref<HTMLDivElement> }) => {310 const { messages, labels, suggestions } = useChat();311312 return (313 <Conversation ref={ref} className={cn('flex-1', className)} {...props}>314 {messages.length === 0 ? (315 <Conversation.Empty>316 <span className="text-foreground font-medium">{labels.emptyTitle}</span>317 <span>{labels.emptyDescription}</span>318 {suggestions.length > 0 && <ChatSuggestions className="mt-4 justify-center" />}319 </Conversation.Empty>320 ) : (321 <Conversation.Content>322 {children ??323 messages.map((message, index) => (324 <ChatMessageItem325 key={message.id}326 message={message}327 isLast={index === messages.length - 1}328 />329 ))}330 <ChatPending />331 </Conversation.Content>332 )}333 <Conversation.ScrollButton label={labels.scrollToBottom} />334 </Conversation>335 );336};337338ChatThread.displayName = 'ChatThread';339340const ChatText = React.memo(function ChatText({341 text,342 renderMarkdown,343}: {344 text: string;345 renderMarkdown: (text: string) => React.ReactNode;346}) {347 return React.useMemo(() => renderMarkdown(text), [text, renderMarkdown]);348});349350const ChatUserMessage = ({ message }: { message: ChatMessage }) => {351 const { labels } = useChatItem();352 const text = messageText(message);353 const files = message.parts.filter((part): part is ChatFilePart => part.type === 'file');354355 return (356 <Message.Content>357 <Message.Header>{labels.user}</Message.Header>358 {files.length > 0 && (359 <Attachments variant="inline">360 {files.map((file, index) => {361 const data = toAttachment(file, index);362 return (363 <Attachments.Item key={data.id} data={data}>364 <Attachments.Preview />365 <Attachments.Info />366 </Attachments.Item>367 );368 })}369 </Attachments>370 )}371 {text && (372 <Bubble>373 <Bubble.Content>{text}</Bubble.Content>374 </Bubble>375 )}376 </Message.Content>377 );378};379380const ChatAssistantMessage = ({ message, isLast }: { message: ChatMessage; isLast: boolean }) => {381 const { status, labels, onRetry, onFeedback, renderMarkdown } = useChatItem();382 const streaming = isLast && status === 'streaming';383 const text = messageText(message);384385 return (386 <Message.Content className="max-w-full">387 <Message.Header>{labels.assistant}</Message.Header>388 <Response isStreaming={streaming}>389 {message.parts.map((part, index) => {390 switch (part.type) {391 case 'reasoning':392 return (393 <Reasoning key={index} isStreaming={streaming} defaultOpen={false}>394 <Reasoning.Trigger />395 <Reasoning.Content>{part.text}</Reasoning.Content>396 </Reasoning>397 );398 case 'text':399 return <ChatText key={index} text={part.text} renderMarkdown={renderMarkdown} />;400 case 'code':401 return (402 <CodeBlock403 key={index}404 code={part.code}405 language={part.language}406 className="my-3 rounded-md"407 >408 <CodeBlock.CopyButton />409 <CodeBlock.Content />410 </CodeBlock>411 );412 case 'tool':413 return (414 <Tool key={index} status={part.status} className="my-3">415 <Tool.Header name={part.name} />416 <Tool.Content>417 {part.input !== undefined && <Tool.Input value={part.input} />}418 {part.output !== undefined && (419 <Tool.Output value={part.output} error={part.status === 'error'} />420 )}421 </Tool.Content>422 </Tool>423 );424 case 'sources':425 return (426 <Sources key={index} className="my-3">427 <Sources.Trigger label={labels.sources} />428 <Sources.Content>429 {part.items.map((item) => (430 <Sources.Item key={item.href} href={item.href} title={item.title} />431 ))}432 </Sources.Content>433 </Sources>434 );435 default:436 return null;437 }438 })}439 </Response>440 {!streaming && (441 <Message.Footer className="px-0">442 <Actions>443 {text && <Actions.Copy text={text} label={labels.copy} copiedLabel={labels.copied} />}444 {onRetry && (445 <Actions.Button label={labels.retry} onClick={() => onRetry(message.id)}>446 <Actions.Icons.retry />447 </Actions.Button>448 )}449 {onFeedback && (450 <>451 <Actions.Button452 label={labels.thumbsUp}453 onClick={() => onFeedback(message.id, 'up')}454 >455 <Actions.Icons.thumbsUp />456 </Actions.Button>457 <Actions.Button458 label={labels.thumbsDown}459 onClick={() => onFeedback(message.id, 'down')}460 >461 <Actions.Icons.thumbsDown />462 </Actions.Button>463 </>464 )}465 </Actions>466 </Message.Footer>467 )}468 </Message.Content>469 );470};471472const ChatMessageItem = React.memo(function ChatMessageItem({473 className,474 message,475 isLast = false,476 ref,477 ...props478}: ChatMessageProps & { ref?: React.Ref<HTMLDivElement> }) {479 const isUser = message.role === 'user';480481 return (482 <Message483 ref={ref}484 align={isUser ? 'end' : 'start'}485 data-role={message.role}486 className={className}487 {...props}488 >489 {isUser ? (490 <ChatUserMessage message={message} />491 ) : (492 <ChatAssistantMessage message={message} isLast={isLast} />493 )}494 </Message>495 );496});497498ChatMessageItem.displayName = 'ChatMessage';499500const ChatPending = ({501 className,502 ref,503 ...props504}: ChatPendingProps & { ref?: React.Ref<HTMLDivElement> }) => {505 const { messages, status, labels } = useChat();506 const last = messages[messages.length - 1];507508 if (status !== 'submitted' || !last || last.role !== 'user') return null;509510 return (511 <Message ref={ref} className={className} {...props}>512 <Message.Content className="max-w-full">513 <Message.Header>{labels.assistant}</Message.Header>514 <Response.Skeleton />515 </Message.Content>516 </Message>517 );518};519520ChatPending.displayName = 'ChatPending';521522const ChatSuggestions = ({523 className,524 ref,525 ...props526}: ChatSuggestionsProps & { ref?: React.Ref<HTMLDivElement> }) => {527 const { suggestions, onSuggestion, onSend } = useChat();528529 if (suggestions.length === 0) return null;530531 return (532 <Suggestion.Group ref={ref} className={cn('flex-wrap', className)} {...props}>533 {suggestions.map((suggestion) => (534 <Suggestion535 key={suggestion}536 suggestion={suggestion}537 size="sm"538 onClick={(text) => (onSuggestion ? onSuggestion(text) : onSend({ text }))}539 />540 ))}541 </Suggestion.Group>542 );543};544545ChatSuggestions.displayName = 'ChatSuggestions';546547const ChatComposer = ({548 className,549 children,550 ref,551 ...props552}: ChatComposerProps & { ref?: React.Ref<HTMLFormElement> }) => {553 const { status, labels, onSend, onStop } = useChat();554 const busy = status === 'submitted' || status === 'streaming';555556 const handleSubmit = (message: PromptInputMessage) => {557 if (busy) return false;558 onSend({ text: message.text, files: message.files.map((file) => file.file) });559 return true;560 };561562 return (563 <div className="border-border shrink-0 border-t p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">564 <PromptInput565 ref={ref}566 multiple567 onSubmit={handleSubmit}568 className={cn('rounded-md', className)}569 {...props}570 >571 {children ?? (572 <>573 <PromptInput.Header>574 <PromptInput.Attachments />575 </PromptInput.Header>576 <PromptInput.Body>577 <PromptInput.Textarea placeholder={labels.placeholder} label={labels.input} />578 </PromptInput.Body>579 <PromptInput.Footer>580 <PromptInput.Tools>581 <PromptInput.AddAttachments label={labels.addFiles} />582 </PromptInput.Tools>583 <PromptInput.Submit584 status={status}585 label={labels.send}586 stopLabel={labels.stop}587 onStop={onStop}588 />589 </PromptInput.Footer>590 </>591 )}592 </PromptInput>593 </div>594 );595};596597ChatComposer.displayName = 'ChatComposer';598599interface UIMessageLike {600 id: string;601 role: string;602 parts: Array<{603 type: string;604 text?: string;605 state?: string;606 input?: unknown;607 output?: unknown;608 errorText?: string;609 url?: string;610 title?: string;611 filename?: string;612 mediaType?: string;613 }>;614}615616function toolStatus(state?: string, errorText?: string): ToolStatus {617 if (errorText || state === 'output-error') return 'error';618 if (state === 'output-available') return 'complete';619 if (state === 'input-available') return 'running';620 return 'pending';621}622623const MESSAGE_CACHE_LIMIT = 500;624const messageCache = new Map<string, ChatMessage>();625626function samePart(a: ChatPart, b: ChatPart): boolean {627 if (a.type === 'sources' || b.type === 'sources') {628 if (a.type !== 'sources' || b.type !== 'sources') return false;629 return (630 a.items.length === b.items.length &&631 a.items.every(632 (item, index) => item.href === b.items[index]?.href && item.title === b.items[index]?.title,633 )634 );635 }636 const left = a as Record<string, unknown>;637 const right = b as Record<string, unknown>;638 const keys = Object.keys(left);639 return (640 keys.length === Object.keys(right).length &&641 keys.every((key) => Object.is(left[key], right[key]))642 );643}644645function reuseMessage(next: ChatMessage): ChatMessage {646 const cached = messageCache.get(next.id);647 if (648 cached &&649 cached.role === next.role &&650 cached.parts.length === next.parts.length &&651 cached.parts.every((part, index) => {652 const other = next.parts[index];653 return other !== undefined && samePart(part, other);654 })655 ) {656 return cached;657 }658 if (messageCache.size >= MESSAGE_CACHE_LIMIT) messageCache.clear();659 messageCache.set(next.id, next);660 return next;661}662663function toChatMessages(uiMessages: UIMessageLike[]): ChatMessage[] {664 return uiMessages665 .filter((message) => message.role === 'user' || message.role === 'assistant')666 .map((message) => {667 const parts: ChatPart[] = [];668 let sources: ChatSourcesPart | null = null;669670 for (const part of message.parts) {671 if (part.type === 'text' && part.text !== undefined) {672 parts.push({ type: 'text', text: part.text });673 } else if (part.type === 'reasoning' && part.text !== undefined) {674 parts.push({ type: 'reasoning', text: part.text });675 } else if (part.type === 'file') {676 parts.push({677 type: 'file',678 name: part.filename ?? part.url?.split('/').pop() ?? 'file',679 url: part.url,680 mediaType: part.mediaType,681 });682 } else if (part.type === 'source-url' && part.url) {683 if (!sources) {684 sources = { type: 'sources', items: [] };685 parts.push(sources);686 }687 sources.items.push({ href: part.url, title: part.title ?? part.url });688 } else if (part.type.startsWith('tool-')) {689 parts.push({690 type: 'tool',691 name: part.type.slice('tool-'.length),692 status: toolStatus(part.state, part.errorText),693 input: part.input,694 output: part.errorText ?? part.output,695 });696 }697 }698699 return reuseMessage({ id: message.id, role: message.role as ChatRole, parts });700 });701}702703const Chat = Object.assign(ChatRoot, {704 Thread: ChatThread,705 Message: ChatMessageItem,706 Pending: ChatPending,707 Suggestions: ChatSuggestions,708 Composer: ChatComposer,709});710711export { Chat, toChatMessages, useChat };712export type {713 ChatComposerProps,714 ChatFeedback,715 ChatLabels,716 ChatMessage,717 ChatMessageProps,718 ChatPart,719 ChatPendingProps,720 ChatProps,721 ChatRole,722 ChatSendMessage,723 ChatStatus,724 ChatSuggestionsProps,725 ChatThreadProps,726};
Update the import paths to match your project structure.
Anatomy
1import { Chat } from '@/hybrids/chat';
1<Chat2 messages={messages}3 status={status}4 onSend={({ text, files }) => send(text, files)}5 onStop={stop}6 onRetry={(id) => regenerate(id)}7 onFeedback={(id, vote) => rate(id, vote)}8 suggestions={['What is NachUI?', 'Show me the composer']}9/>
Give it the messages and a status, and it draws the rest: the thread pinned to the newest message, a skeleton while the reply is on its way, a caret while it streams, and the composer that sends. Put it inside any parent with a fixed height and it fills it.
Composition
Open
chat.tsx and you find the elements in the order they appear on screen. The chat adds no logic of its own beyond handing each part of a message to the element that knows how to draw it.Chatโโโ Chat.Thread Conversationโ โโโ Conversation.Empty + Chat.Suggestions Suggestionโ โโโ Chat.Message Messageโ โ โโโ user Bubble, Attachmentsโ โ โโโ assistant Responseโ โ โโโ reasoning Reasoningโ โ โโโ text renderMarkdownโ โ โโโ code CodeBlockโ โ โโโ tool Toolโ โ โโโ sources Sourcesโ โ โโโ footer Actionsโ โโโ Chat.Pending Response.Skeletonโ โโโ Conversation.ScrollButtonโโโ Chat.Composer PromptInput
Pass children to
Chat to lay the parts out yourself; every part reads the messages and handlers from context.1<Chat messages={messages} onSend={send}>2 <header className="border-b p-3">Support</header>3 <Chat.Thread />4 <Chat.Composer accept="image/*" />5</Chat>
Message shape
A message is a role and a list of parts. Parts render in order, so a reply can think, answer, show code, call a tool and cite its sources, in that sequence.
1type ChatMessage = {2 id: string;3 role: 'user' | 'assistant';4 parts: ChatPart[];5};67type ChatPart =8 | { type: 'text'; text: string }9 | { type: 'reasoning'; text: string }10 | { type: 'code'; code: string; language?: string }11 | { type: 'tool'; name: string; status: ToolStatus; input?: unknown; output?: unknown }12 | { type: 'sources'; items: { href: string; title: string }[] }13 | { type: 'file'; name: string; size?: number; url?: string; mediaType?: string };
Text parts go through
renderMarkdown. The default splits paragraphs on blank lines; hand it react-markdown or your own renderer to get the rest.1<Chat renderMarkdown={(text) => <Markdown>{text}</Markdown>} โฆ />
Adapter
The chat does not know which SDK runs your model.
toChatMessages maps the UIMessage array the Vercel AI SDK keeps into the shape above, without importing the SDK: text, reasoning and file parts pass through, tool-* parts become tool parts with their state folded into a status, and source-url parts are gathered into one sources part.1'use client';23import { useChat } from '@ai-sdk/react';4import { Chat, toChatMessages } from '@/hybrids/chat';56export function Support() {7 const { messages, sendMessage, status, stop, regenerate } = useChat();89 return (10 <Chat11 messages={toChatMessages(messages)}12 status={status}13 onSend={({ text, files }) => sendMessage({ text, files })}14 onStop={stop}15 onRetry={() => regenerate()}16 />17 );18}
Anything else that produces messages works the same way: build the array, pass it in.
Streaming
status drives the two waiting states. submitted shows a skeleton under the last user message until the first token lands; streaming puts a caret after the last reply and turns the send button into a stop button.Start a conversationAsk a question or pick one of the suggestions.
1'use client';23import { useEffect, useRef, useState } from 'react';4import { Chat, type ChatMessage, type ChatStatus } from '@/hybrids/chat';56const REPLY =7 'Every element in this thread is one you can install on its own. The chat only decides the order they sit in, and hands each one the part of the message it knows how to draw.';89export function Streaming() {10 const [messages, setMessages] = useState<ChatMessage[]>([]);11 const [status, setStatus] = useState<ChatStatus>('ready');12 const timer = useRef<ReturnType<typeof setInterval> | null>(null);1314 const stop = () => {15 if (timer.current) clearInterval(timer.current);16 timer.current = null;17 setStatus('ready');18 };1920 useEffect(() => stop, []);2122 const send = ({ text }: { text: string }) => {23 const id = String(Date.now());24 setMessages((previous) => [25 ...previous,26 { id: `u-${id}`, role: 'user', parts: [{ type: 'text', text }] },27 ]);28 setStatus('submitted');2930 const words = REPLY.split(' ');31 let count = 0;3233 setTimeout(() => {34 setStatus('streaming');35 setMessages((previous) => [36 ...previous,37 { id: `a-${id}`, role: 'assistant', parts: [{ type: 'text', text: '' }] },38 ]);39 timer.current = setInterval(() => {40 count += 1;41 const text = words.slice(0, count).join(' ');42 setMessages((previous) =>43 previous.map((message) =>44 message.id === `a-${id}` ? { ...message, parts: [{ type: 'text', text }] } : message,45 ),46 );47 if (count >= words.length) stop();48 }, 60);49 }, 700);50 };5152 return (53 <div className="bg-card h-[26rem] w-full max-w-2xl overflow-hidden rounded-lg shadow-sm">54 <Chat55 messages={messages}56 status={status}57 onSend={send}58 onStop={stop}59 suggestions={['What makes this a hybrid?', 'Send anything to see it stream']}60 />61 </div>62 );63}
API Reference
Chat
| Prop | Type | Default | Description |
|---|---|---|---|
messages | ChatMessage[] | - | The thread, oldest first |
status | 'ready' | 'submitted' | 'streaming' | 'error' | 'ready' | Drives the skeleton, the caret and the stop button |
onSend | (message: { text: string; files?: File[] }) => void | - | Called when the composer submits |
onStop | () => void | - | Called by the stop button while a reply is in flight |
onRetry | (messageId: string) => void | - | Adds a retry action under each reply |
onFeedback | (messageId: string, vote: 'up' | 'down') => void | - | Adds thumbs up and down under each reply |
suggestions | string[] | [] | Chips shown in the empty state |
onSuggestion | (text: string) => void | - | Called when a chip is picked; falls back to onSend |
placeholder | string | - | Composer placeholder, shorthand for labels.placeholder |
emptyTitle | string | - | Empty state title, shorthand for labels.emptyTitle |
emptyDescription | string | - | Empty state text, shorthand for labels.emptyDescription |
labels | Partial<ChatLabels> | - | Every visible string, with English defaults |
renderMarkdown | (text: string) => ReactNode | - | Renders text parts; default splits paragraphs |
children | ReactNode | - | Replaces the default layout of thread and composer |
className | string | - | Additional CSS classes |
Chat.Thread
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | - | Replaces the rendered messages inside the thread |
className | string | - | Additional CSS classes |
Chat.Message
| Prop | Type | Default | Description |
|---|---|---|---|
message | ChatMessage | - | The message to draw |
isLast | boolean | false | Marks the reply that streams and opens its reasoning |
className | string | - | Additional CSS classes |
Chat.Pending
Renders
Response.Skeleton while status is submitted and the last message is from the user; nothing otherwise.| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Chat.Suggestions
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Chat.Composer
Accepts every
PromptInput prop except onSubmit, so accept, maxFiles and maxFileSize pass straight through.| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | - | Replaces the default textarea, tools and submit |
className | string | - | Additional CSS classes |
toChatMessages
| Signature | Description |
|---|---|
toChatMessages(messages: UIMessageLike[]): ChatMessage[] | Maps Vercel AI SDK messages to the chat's shape, no SDK import |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.