Web · Components
Chat
Chat: a single component for both AI chat (like ChatGPT) and messaging (like WhatsApp).
Live example
Preview
Code
Events
- Events appear here when you interact with the preview.
Import
Chat: a single component for both AI chat (like ChatGPT) and messaging (like WhatsApp). Messages are given as data; the list, bubbles, actions and composer are drawn automatically.
Messaging (`mode="messaging"`)
- Bubbles; consecutive messages from the same person are grouped; colored names and avatars in group chats. The day divider sticks to the top while scrolling.
- Time, "edited", star/pin and delivery ticks (sending, single, double, blue read, failed → tap to retry).
- Reactions: 6 quick emoji + the full picker; chips show counts and who reacted. Reply: tapping the quote goes to the message and highlights it.
- WhatsApp format:
*bold*,_italic_,~strike~, URLs as links; emoji-only messages are large; long messages get "Read more". - Attachments: an image/video grid (fullscreen
Lightbox), voice messages (waveform, seeking, 1.5×/2×), file cards, link previews. - Mobile: swipe a bubble right → reply; long press → reaction and action sheet from the bottom (with haptics). On desktop a toolbar appears on hover.
AI (`mode="assistant"`)
- Responses are drawn without flicker with
Markdownwhile streaming (tables, code blocks); a reasoning section, tool steps, source chips, error + retry, copy / regenerate / 👍👎. Withstatus, a stop button and "thinking" dots.useChatwires it all.
Shared
- Sticks to the bottom: streaming and new messages stay visible; while scrolled up the position is kept and an "N new messages" button appears. Scrolling doesn't jump while older messages load (
onLoadMore). An unread divider. - Performance: every row is
memo; streaming only redraws the last message. Off-screen rows aren't rendered thanks tocontent-visibility; smooth even with thousands of messages. Heavy parts (fullscreen, emoji) load when needed. - Accessibility: incoming messages are announced to screen readers; ↑/↓ move between messages and the focused message's tools are reached with Tab.
Examples
The chat composer: for both messaging (WhatsApp) and AI prompts (ChatGPT). Chat draws it itself; it can also be used on its own (e.g. an "ask" box at the bottom of a page).
- Growing field: grows as you type and scrolls past the limit (overlay scrollbar).
- Enter: sends on desktop, Shift+Enter adds a new line; on phones Enter is a new line. IME (Chinese/Japanese) input isn't split.
- Attachments: paperclip button, paste (screenshots) and drag and drop; images show a small preview, others a type icon. Type, size and count limits are checked.
- Voice messages: microphone permission is requested; recording shows a timer and live bars. The sent file is in
draft.files, the duration and waveform indraft.voice. - Reply/edit: a quote bar on top; closes with Esc.
- AI: while
statusis streaming the send button becomes "Stop".
Examples
Lightweight emoji picker: categories, recently used and keyboard navigation (arrow keys, Home/End, Enter). Used in ChatComposer and the reaction bar; can also be used on its own.
- No extra dependency or emoji font; the system's emoji are used.
- Categories render as they enter the screen (
content-visibility).
Examples
Chat header: avatar, name, status or "typing…", actions on the right. Given to Chat's header prop. A server component.
Examples
Three bouncing dots: "typing…" and the AI's "thinking" state. Chat shows it itself; it can also be used on its own in a header or contact list. A server component; the animation is CSS only and stops with the "reduced motion" preference.
Examples
toggleReaction
functionToggles a reaction and returns the new list (does not mutate the array). With single (default, like WhatsApp) the person's previous reaction is removed.
Examples
defaultChatMessages
constantTurkish chat texts.
parseStreamData
functionTurns an SSE data: line into a part. Recognizes your own part objects (type field), OpenAI (choices[0].delta.content), Anthropic (delta.text, delta.thinking) and { text | content | delta }; when it is not JSON it is the text itself. [DONE] and unknown ones are null.
readChatStream
functionTurns a stream into parts: Response (fetch), ReadableStream, AsyncIterable or a single text. In SSE responses data: lines are decoded with parse (default parseStreamData).
Examples
applyStreamPart
functionApplies a part to a message and returns the new message.
useChat
functionManages the state of an AI chat: keeps messages, reads the response as a stream, stops, regenerates and edits. Provider independent; send calls your own API route.
- Smooth: parts are drawn once per frame (even when hundreds of parts arrive per second); only the last message updates.
- Reasoning time is measured automatically ("Thought for 12 s").
- When stopped, the received text stays; on error the response shows "Retry".
Examples
ChatMode
typeKind of chat.
"messaging": like WhatsApp: bubbles on both sides, time and ticks inside the bubble, reactions, swipe to reply, voice messages."assistant": like ChatGPT: a centered column, user messages as bubbles on the right, AI responses as bubble-less Markdown; reasoning, tools, sources, copy/regenerate/rating.
ChatSuggestion
typeSuggestion chip: text, or a separate label + prompt.
ChatProps
interfaceProps of the Chat component.
Extends: Omit<ComponentProps<"div">, "children" | "onCopy">
| Name | Type | Default | Description |
|---|---|---|---|
messages | readonly ChatMessage[] | Messages, oldest to newest. See ChatMessage. | |
mode? | ChatMode | "messaging" | Kind of chat. See ChatMode. |
currentUserId? | string | Id of the person using the app; your own messages appear on the right. | |
users? | readonly ChatUser[] | People in the chat (name, photo, color). See ChatUser. | |
group? | boolean | true` when `users` has more than two people | Group chat: the other side's name (colored) and avatar are visible. |
status? | ChatStatus | "ready" | AI status. See ChatStatus. |
onSend? | (draft: ChatDraft) => unknown | When a message is sent. Without it no composer is drawn (read only). | |
onStop? | () => void | When "Stop" is pressed (AI). | |
onReact? | (message: ChatMessage, emoji: string) => void | When a reaction is chosen or its chip is tapped. toggleReaction does the work. | |
onEdit? | (message: ChatMessage, text: string) => unknown | With the new text when your own message is edited. | |
onDelete? | (message: ChatMessage) => unknown | When deleted (confirmation is asked first; see confirmDelete). | |
onForward? | (message: ChatMessage) => void | When "Forward" is chosen. | |
onStar? | (message: ChatMessage) => void | When "Star" is chosen. | |
onPin? | (message: ChatMessage) => void | When "Pin" is chosen. | |
onRetry? | (message: ChatMessage) => void | "Retry" on a message that failed to send or a failed response. | |
onRegenerate? | (message: ChatMessage) => void | "Regenerate" on an AI response. | |
onFeedback? | (message: ChatMessage, value: "up" | "down" | null) => void | When a response gets 👍/👎 (null: withdrawn). | |
onCopy? | (message: ChatMessage) => void | When text is copied to the clipboard (copying happens automatically). | |
actions? | readonly ChatActionName[] | Actions to show. When omitted, all those whose handlers are given; copy and reply are always available. See ChatActionName. | |
customActions? | readonly ChatCustomAction[] | Custom actions added to the message menu. | |
canEdit? | (message: ChatMessage) => boolean | own, non-deleted messages | Can the message be edited? |
canDelete? | (message: ChatMessage) => boolean | own messages | Can the message be deleted? |
confirmDelete? | boolean | true | Ask for confirmation before deleting? |
quickReactions? | readonly string[] | ["👍", "❤️", "😂", "😮", "😢", "🙏"] | Quick reactions. |
typing? | readonly string[] | Ids of people typing; a "typing…" bubble at the bottom. | |
hasMore? | boolean | Are there older messages? onLoadMore is called when scrolling up. | |
onLoadMore? | () => unknown | Loads older messages; loading shows at the top until the promise settles. The position doesn't shift. | |
unreadFrom? | string | Id of the first unread message: a divider goes before it and it is scrolled to on open. | |
suggestions? | readonly ChatSuggestion[] | Suggestion chips above the composer; an empty array hides them. | |
empty? | ReactNode | Content shown when there are no messages. | |
header? | ReactNode | Header above the list (e.g. ChatHeader). | |
composer? | Partial<Omit<ChatComposerProps, "onSend">> | false | Composer settings (attachments, voice, placeholder, tools, note…). false hides the composer. See ChatComposerProps. | |
groupWindow? | number | 300000` (5 min) | Messages from the same person within this many ms are grouped. |
collapseAfter? | number | 700 | Plain text longer than this many characters collapses with "Read more"; 0 turns it off. |
swipeToReply? | boolean | true | Reply by swiping a bubble right on touch screens. |
timeZone? | string | the browser's | Time zone of times and day dividers. |
texts? | Partial<ChatMessages> | Texts of the chat (this name is used because the message data is messages). App-wide via ui.chat in the dictionary. See ChatMessages. |
ChatAttachOptions
interfaceFile attachment rules.
| Name | Type | Default | Description |
|---|---|---|---|
accept? | string | readonly string[] | Accepted types: "image/*", ".pdf", ["image/*", ".zip"]. | |
maxSize? | FileSize | Maximum size per file: bytes or "10 MB". | |
maxFiles? | number | 10 | Maximum number of files in a message. |
ChatComposerHandle
interfaceFunctions on the ref for controlling ChatComposer from outside.
| Name | Type | Description |
|---|---|---|
focus | () => void | Focuses the input. |
addFiles | (files: Iterable<File>) => void | Adds files (drag and drop, your own button); those breaking the rules are dropped. |
insertText | (text: string) => void | Inserts text at the caret. |
clear | () => void | Clears the text and attachments. |
Composer look.
"messaging": like WhatsApp: a rounded field, emoji on the left, attachment on the right, a round send/microphone button next to it."assistant": like ChatGPT: a wide card; text on top, a tool row at the bottom (attachment,toolbar, send/stop).
ChatComposerProps
interfaceProps of the ChatComposer component.
Extends: Omit<ComponentProps<"form">, "onSubmit" | "children" | "ref" | "defaultValue">
| Name | Type | Default | Description |
|---|---|---|---|
onSend | (draft: ChatDraft) => unknown | Called with the draft on send. If the promise rejects, the text comes back. | |
value? | string | Text in controlled use. | |
defaultValue? | string | Initial text in uncontrolled use. | |
onValueChange? | (value: string) => void | When the text changes. | |
variant? | ChatComposerVariant | "messaging" | Look. See ChatComposerVariant. |
placeholder? | string | Placeholder. Defaults to "Type a message" / "Ask anything…" by look. | |
disabled? | boolean | Disabled. | |
status? | ChatStatus | AI status: while "submitted" or "streaming" the send button becomes "Stop" and no new message is sent. See ChatStatus. | |
onStop? | () => void | When "Stop" is pressed. | |
attachments? | boolean | ChatAttachOptions | false | File attachments: paperclip button, paste (screenshots) and drag and drop. true or rules (ChatAttachOptions). |
voice? | boolean | false | Voice messages: while the text is empty a microphone button appears instead of send; during recording a timer and live audio bars, cancel and send. |
emoji? | boolean | true` for the `"messaging"` look | Emoji button. |
replyTo? | ChatMessage | null | Message being replied to; shown as a quote above the field. | |
replyAuthor? | ReactNode | Name of the author of the message being replied to. | |
replyColor? | string | Color of the reply quote. | |
onCancelReply? | () => void | When the reply is dismissed. | |
editing? | ChatMessage | null | Message being edited: its text comes into the field and sending edits it. | |
onCancelEdit? | () => void | When editing is cancelled. | |
submitOnEnter? | boolean | "desktop" | "desktop" | Does Enter send? "desktop": on mouse/keyboard devices Enter sends and Shift+Enter adds a new line; on touch screens Enter is a new line (send with the send button). |
maxLength? | number | Maximum characters. A counter appears when close. | |
toolbar? | ReactNode | Extra tools (e.g. a model picker, a "Search the web" button). | |
footer? | ReactNode | Small note below the field (e.g. "AI can make mistakes."). | |
onTyping? | () => void | Called at most once every 3 seconds while the user types; to forward the "typing…" signal to the server. | |
autoFocus? | boolean | Focus on open. | |
ref? | Ref<ChatComposerHandle> | Control functions. See ChatComposerHandle. | |
messages? | Partial<ChatMessages> | Texts of this field. See ChatMessages. |
EmojiPickerProps
interfaceProps of the EmojiPicker component.
Extends: Omit<ComponentProps<"div">, "onSelect">
| Name | Type | Default | Description |
|---|---|---|---|
onSelect | (emoji: string) => void | Called when an emoji is chosen. | |
recent? | boolean | true | Recently used section (stored in the browser). |
messages? | Partial<ChatMessages> | Texts of this picker. See ChatMessages. |
ChatHeaderProps
interfaceProps of the ChatHeader component.
Extends: Omit<ComponentProps<"header">, "title">
| Name | Type | Description |
|---|---|---|
title | ReactNode | Name of the person or group. |
subtitle? | ReactNode | Subtitle: "online", "last seen 14:05", "Jane, John, You". |
typing? | ReactNode | "typing…" instead of the subtitle (e.g. "Jane is typing…"); shown with dots. |
avatar? | string | Photo. |
status? | AvatarStatus | Status dot of the avatar. |
start? | ReactNode | Element left of the avatar (e.g. a back button on phones). |
actions? | ReactNode | Actions on the right (call, video call, menu). |
ChatMessages
interfaceTexts of the chat components (Chat, ChatComposer, EmojiPicker). Replace them app-wide in the dictionary's ui.chat namespace, or for one chat with the messages prop. Placeholders such as {count} and {name} are filled at runtime.
| Name | Type | Default | Description |
|---|---|---|---|
list | string | "Mesajlar" | Screen reader name of the message list. |
you | string | "Sen" | Author of your own messages (in quotes, reactions). |
unread | string | "{count} okunmamış mesaj" | Unread messages separator. |
jumpToLatest | string | "En yeni mesajlara git" | Scroll down button. |
newMessages | string | "{count} yeni mesaj" | Count of new messages that arrived while scrolled up. |
loadingOlder | string | "Eski mesajlar yükleniyor…" | While older messages load. |
edited | string | "düzenlendi" | Note next to the time of an edited message. |
deleted | string | "Bu mesaj silindi" | Deleted message. |
deletedOwn | string | "Bu mesajı sildin" | Your own deleted message. |
forwarded | string | "İletildi" | Note above a forwarded message. |
readMore | string | "Devamını oku" | Link that expands a long message. |
sending | string | "Gönderiliyor" | Delivery status. |
sent | string | "Gönderildi" | Delivery status: single tick. |
delivered | string | "Teslim edildi" | Delivery status: double tick. |
read | string | "Okundu" | Delivery status: blue double tick. |
failed | string | "Gönderilemedi. Yeniden denemek için dokun." | Message that failed to send. |
starred | string | "Yıldızlı" | Starred message marker. |
pinned | string | "Sabitlendi" | Pinned message marker. |
react | string | "Tepki ver" | Reaction button. |
reply | string | "Yanıtla" | Reply action. |
copy | string | "Kopyala" | Copy action. |
copied | string | "Kopyalandı" | After copying. |
edit | string | "Düzenle" | Edit action. |
delete | string | "Sil" | Delete action. |
forward | string | "İlet" | Forward action. |
star | string | "Yıldızla" | Star action. |
unstar | string | "Yıldızı kaldır" | Unstar action. |
pin | string | "Sabitle" | Pin action. |
unpin | string | "Sabitlemeyi kaldır" | Unpin action. |
retry | string | "Yeniden dene" | Retry action. |
regenerate | string | "Yeniden oluştur" | Regenerate response action. |
good | string | "İyi yanıt" | Like button. |
bad | string | "Kötü yanıt" | Dislike button. |
more | string | "Diğer" | More actions menu. |
moreReactions | string | "Diğer emojiler" | + button in the reaction bar. |
messageActions | string | "Mesaj eylemleri" | Screen reader name of the action panel. |
deleteTitle | string | "Mesaj silinsin mi?" | Delete confirmation title. |
deleteDescription | string | "Mesaj herkes için silinir." | Delete confirmation description. |
reactedBy | string | "{names} tepki verdi" | Tooltip of a reaction chip. |
typing | string | "{name} yazıyor…" | While one person types. |
typingTwo | string | "{a} ve {b} yazıyor…" | While two people type. |
typingMany | string | "{count} kişi yazıyor…" | While three or more people type. |
thinking | string | "Düşünüyor…" | While thinking. |
thought | string | "Düşünme" | Thinking section of unknown duration. |
thoughtFor | string | "{seconds} sn düşündü" | Thinking duration. |
toolRunning | string | "Çalışıyor" | Tool running. |
toolDone | string | "Tamamlandı" | Tool finished. |
toolError | string | "Hata" | Tool failed. |
toolInput | string | "Girdi" | Tool input title. |
toolOutput | string | "Çıktı" | Tool output title. |
sources | string | "Kaynaklar" | Sources list. |
errorTitle | string | "Yanıt alınamadı" | Default text of the error box. |
placeholder | string | "Mesaj yaz" | Placeholder of the input in messaging. |
placeholderAssistant | string | "Bir şey sor…" | Placeholder in AI chat. |
send | string | "Gönder" | Send button. |
stop | string | "Durdur" | Stop response button. |
attach | string | "Dosya ekle" | Attach file button. |
emoji | string | "Emoji" | Emoji button. |
record | string | "Sesli mesaj kaydet" | Record button. |
sendRecording | string | "Sesli mesajı gönder" | Finish and send the recording. |
cancelRecording | string | "Kaydı sil" | Cancel the recording. |
recording | string | "Kaydediliyor" | While recording. |
micDenied | string | "Mikrofona erişilemedi" | When there is no microphone permission. |
replyingTo | string | "{name} yanıtlanıyor" | Reply bar. |
cancelReply | string | "Yanıtı iptal et" | Close the reply bar. |
editing | string | "Mesajı düzenliyorsun" | Edit bar. |
cancelEdit | string | "Düzenlemeyi iptal et" | Close the edit bar. |
removeFile | string | "{name} kaldır" | Remove button in the attachment preview. |
dropFiles | string | "Dosyaları buraya bırak" | Drag and drop area. |
tooManyFiles | string | "En fazla {max} dosya eklenebilir" | When the file limit is exceeded. |
fileTooLarge | string | "{name} çok büyük (en fazla {max})" | When the size limit is exceeded. |
fileNotAccepted | string | "{name} desteklenmiyor" | When the type is not accepted. |
voiceMessage | string | "Sesli mesaj" | Voice message attachment. |
photo | string | "Fotoğraf" | Image attachment (in quotes). |
video | string | "Video" | Video attachment (in quotes). |
file | string | "Dosya" | File attachment (in quotes). |
play | string | "Oynat" | Play the voice message. |
pause | string | "Duraklat" | Pause the voice message. |
speed | string | "Oynatma hızı" | Speed button. |
download | string | "İndir" | Download the file. |
openMedia | string | "Tam ekran aç" | Open the image/video full screen. |
moreMedia | string | "+{count}" | Count of attachments that do not fit the grid. |
emptyTitle | string | "Henüz mesaj yok" | Empty messaging. |
emptyAssistant | string | "Nasıl yardımcı olabilirim?" | Empty AI chat. |
suggestions | string | "Öneriler" | Screen reader name of the suggestion chips. |
emojiRecent | string | "Son kullanılanlar" | Emoji category. |
emojiSmileys | string | "Yüzler" | Emoji category. |
emojiPeople | string | "İnsanlar" | Emoji category. |
emojiNature | string | "Doğa" | Emoji category. |
emojiFood | string | "Yiyecek" | Emoji category. |
emojiActivity | string | "Etkinlik" | Emoji category. |
emojiTravel | string | "Seyahat" | Emoji category. |
emojiObjects | string | "Nesneler" | Emoji category. |
emojiSymbols | string | "Semboller" | Emoji category. |
ChatStreamPart
typeA part coming from the stream. A plain text part (string) is appended to the response.
{ type: "text", text }: Text appended to the response.{ type: "reasoning", text }: Text appended to the thinking section.{ type: "tool", id, ... }: A tool call; the sameidis updated.{ type: "source", url, title }: Adds a source.{ type: "message", message }: Changes message fields directly (e.g.{ attachments },{ body }).{ type: "error", error }: The response ends with an error.
ChatDate
typeValues accepted as dates: Date, an ISO string or milliseconds.
ChatRole
typeRole of the message author.
"user": The person using the app (on the right)."assistant": The AI or the other party (on the left)."system": Small info line in the middle ("Ayşe joined the group").
ChatToolCall
typeA tool call of the AI (web: the title can be a React element).
ChatSource
typeA source the response relies on.
ChatLinkPreview
typeLink preview.
ChatMessage
typeA chat message. See @yasinsensoy/core/chat ChatMessage.
Delivery status of a message; shows as ticks next to the time of your own messages (like WhatsApp).
"sending": Sending (clock icon)."sent": Reached the server (single tick)."delivered": Reached the recipient (double tick)."read": Read (blue double tick)."failed": Failed to send (red warning; tap to retry).
ChatCustomAction
interfaceCustom action added to the message menu.
| Name | Type | Description |
|---|---|---|
label | string | Display name. |
icon? | IconProp | Icon: a name or an element. |
tone? | "neutral" | "danger" | Red (dangerous) action. |
onSelect | (message: ChatMessage) => void | Called with the message when chosen. |
when? | (message: ChatMessage) => boolean | Show only on these messages. |
ChatUser
interfaceA person in the chat.
| Name | Type | Description |
|---|---|---|
id | string | Unique id; matches the messages' authorId. |
name | string | Display name. |
avatar? | string | Profile photo. |
color? | string | Name color in group chats (e.g. "#e11d48", "var(--ui-primary)"). When omitted, a stable color is picked from the id. |
status? | "online" | "away" | "busy" | "offline" | Online status; a dot on the avatar's corner. |
ChatDraft
interfaceDraft sent from the composer.
| Name | Type | Description |
|---|---|---|
text | string | Text (trimmed). |
files | File[] | Attached files (images, documents, voice messages). |
replyTo? | ChatMessage | Message being replied to; if sent while replying. |
voice? | { duration: number; waveform: number[]; } | Duration (seconds) and waveform if a voice message was recorded. |
Attachment kind. When omitted, it is derived from type (MIME) or the file name.
"image","video": Thumbnail in a grid; full screen on click."audio": Voice message player (waveform, speed)."file": File card (icon, name, size, download).
ChatAttachment
interfaceMessage attachment: image, video, audio or file.
| Name | Type | Description |
|---|---|---|
id? | string | Unique id. When omitted, url or the name is used. |
name? | string | File name. |
url? | string | Address (download, playback, full screen). A local preview can be given while uploading. |
type? | string | MIME type (e.g. "image/png", "audio/webm"). |
kind? | ChatAttachmentKind | Kind. See ChatAttachmentKind. |
size? | number | Size (bytes). |
thumbnail? | string | Thumbnail (shown in the grid instead of url). |
width? | number | Natural width (px); when given, space is reserved before the image loads, so nothing shifts. |
height? | number | Natural height (px). |
duration? | number | Duration of audio and video (seconds). |
waveform? | readonly number[] | Waveform of a voice message: samples between 0 and 1 (30-60 are enough). When omitted, a fixed pattern is drawn. |
progress? | number | Upload progress (0-1). When given, a ring shows over the attachment. |
ChatReaction
interfaceA reaction: the emoji and who reacted.
| Name | Type | Description |
|---|---|---|
emoji | string | Emoji (e.g. "👍"). |
users | readonly string[] | Ids of the people who reacted. The count is its length. |
ChatReasoning
interfaceA thinking step of the AI.
| Name | Type | Description |
|---|---|---|
text | string | Thinking text (Markdown). |
duration? | number | Thinking duration (seconds); written as "Thought for 12 s". |
ChatActionName
typeNames of the actions on a message. ChatProps.actions picks which actions show.
ChatStatus
typeChat state (AI). While "submitted" and "streaming", the send button becomes "Stop".
"ready": Ready."submitted": Request sent, waiting for the first part (three dots)."streaming": The response is streaming."error": The last request failed.
TypingIndicatorProps
interfaceProps of the TypingIndicator component.
Extends: ComponentProps<"span">
| Name | Type | Description |
|---|---|---|
label? | string | Text read by screen readers (e.g. "Jane is typing…"). When omitted it is drawn only visually. |
ChatSendContext
interfaceInfo passed to the UseChatOptions.send function.
| Name | Type | Description |
|---|---|---|
messages | ChatMessage[] | History to respond to: the last message is the user's new message. |
signal | AbortSignal | Aborted when "Stop" is pressed; pass it to fetch. |
files | File[] | Files the user attached (to the last message). |
ChatSendResult
typeResponses the send function can return.
UseChatOptions
interfaceOptions of the useChat hook.
| Name | Type | Default | Description |
|---|---|---|---|
send | (context: ChatSendContext) => ChatSendResult | Promise<ChatSendResult> | Produces the response. Can return a fetch response (plain text or SSE; OpenAI and Anthropic formats are recognized), a ReadableStream, an async function* generator or text. See ChatStreamPart. | |
initialMessages? | readonly ChatMessage[] | Initial messages (e.g. a saved chat). | |
parse? | (data: string) => ChatStreamPart | null | Parsing of an SSE data: line. See parseStreamData. | |
onFinish? | (message: ChatMessage, messages: ChatMessage[]) => void | When the response finishes (even if stopped). | |
onError? | (error: unknown) => void | When the request fails. | |
onFeedback? | (message: ChatMessage, value: "up" | "down" | null) => void | When the user gives 👍/👎. | |
attachment? | (file: File) => ChatAttachment | Promise<ChatAttachment> | Converts an attached file into an attachment shown in the message (e.g. upload it and return its URL). Defaults to a local preview URL (URL.createObjectURL). | |
generateId? | () => string | crypto.randomUUID | Generates a new message id. |
UseChatResult
interfaceWhat the useChat hook returns.
| Name | Type | Description |
|---|---|---|
messages | ChatMessage[] | Messages. |
setMessages | (messages: ChatMessage[] | ((current: ChatMessage[]) => ChatMessage[])) => void | Changes the messages directly (e.g. load a saved chat). |
status | ChatStatus | Status. See ChatStatus. |
error | unknown | Last error. |
send | (input: string | ChatDraft) => Promise<void> | Sends a message (text or a draft). |
stop | () => void | Stops the streaming response; the text received so far stays. |
regenerate | (message?: ChatMessage) => Promise<void> | Regenerates the last (or the given) response. |
edit | (message: ChatMessage, text: string) => Promise<void> | Edits a user message and regenerates what follows. |
props | { messages: ChatMessage[]; status: ChatStatus; onSend: (draft: ChatDraft) => Promise<void>; onStop: () => void; onRegenerate: (message: ChatMessage) => void; onRetry: (message: ChatMessage) => void; onEdit: (message: ChatMessage, text: string) => Promise<void>; onFeedback: (message: ChatMessage, value: "up" | "down" | null) => void; } | Props to spread onto Chat: <Chat mode="assistant" {...chat.props} />. |