AI Chat Pro
Chat is the whole conversation for an assistant, at the depth of ChatGPT, Claude and Perplexity, and useChat connects it to any backend. Replies stream in as Markdown with live reasoning ("Thinking 4s"), a plan that ticks itself off, tool cards (web search with its results, code with its output, files, generated images), cited sources with hover cards, deep research reports, and artifacts (code, documents, tables, charts) that open in a side panel with versions. Editing a message or regenerating a reply keeps the old one as a version you can step back to, "‹ 2/3 ›". The composer grows with the text and takes pasted and dropped files with upload progress, / commands, @ mentions, mode chips such as Search, Deep research and Think, dictation and voice mode, and its send button turns into Stop while a reply streams.
AIChatScreen puts it together with a history (search, projects, pinned, rename, share, delete with Undo), a model picker, a hero to start from, voice mode and offline and rate limit banners. Everything uses React Native core and react-native-svg, like the rest of Pro. For just a bubble and an input, use the free MessageBubble & ChatComposer.
import { AIChatScreen, Chat, useChat } from '@patine-ui/pro';
<View style={{ height: 720, width: '100%' }}> <AIChatScreen title="Atlas" subtitle="Your travel assistant" suggestions={AI_CHAT_PROMPTS} models={AI_CHAT_MODELS} modes={AI_CHAT_MODES} commands={AI_CHAT_COMMANDS} mentions={AI_CHAT_MENTIONS} conversations={demoConversations(NOW)} projects={AI_CHAT_PROJECTS} loadConversation={(id) => demoThread(id, NOW)} shareUrl={(id) => `https://atlas.example/share/${id}`} onAttach={() => [{ id: String(Date.now()), name: 'itinerary.pdf', size: 184000, mimeType: 'application/pdf' }]} onUpload={demoUpload} onVoiceStart={() => {}} /> </View>
Without an adapter it runs demoAssistant, which shows a different part for each kind of question: Research the best month runs deep research, Write a packing script writes code into the panel and runs it (then ask it to "add walking shoes" for version 2), Draw Lisbon at sunset generates an image, Compare flights builds a table, Chart a budget a chart, and anything with "fail" errors so you can try Retry.
Connect your backend
useChat takes an adapter: a function that gets the thread, an AbortSignal and the mode the message was sent in, and returns the reply. Return a string for a whole reply, or an async iterable of chunks to stream it. Throw to mark the message failed. Spread what useChat returns onto <Chat />.
const chat = useChat({ adapter });
return <Chat {...chat} />;
Plain text over fetch
streamText(response) reads a response body as it downloads. Pass signal to fetch so Stop cancels the request.
import { Chat, streamText, useChat } from '@patine-ui/pro';
const adapter = async ({ messages, signal, mode }) => {
const response = await fetch('https://api.example.com/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode, messages: messages.map(({ role, text }) => ({ role, content: text })) }),
signal,
});
return streamText(response);
};
React Native's built-in fetch waits for the whole body, so streamText yields it once and the reply appears at the end. In Expo (SDK 52+), import { fetch } from 'expo/fetch' streams on every platform. The browser's fetch streams on the web.
Server-sent events (OpenAI, Anthropic and most AI APIs)
streamServerEvents(response) yields each event's data and stops at [DONE]. Turn each event into chunks:
import { streamServerEvents } from '@patine-ui/pro';
async function* adapter({ messages, signal }) {
const response = await fetch('/api/chat', { method: 'POST', body: JSON.stringify({ messages }), signal });
for await (const data of streamServerEvents(response)) {
const event = JSON.parse(data);
if (event.type === 'text') yield event.delta;
if (event.type === 'reasoning') yield { type: 'reasoning', text: event.delta };
if (event.type === 'tool') yield { type: 'tool', id: event.id, name: event.name, kind: 'search', status: event.status, results: event.results };
}
}
Keep API keys on your server: call your own endpoint from the app, never the AI provider directly.
The chunks
Each chunk adds to the reply. Ones with an id add a block the first time and update it after, so a tool can go from running to done.
| Chunk | What it shows |
|---|---|
'text' or { type: 'text', text } | More of the reply, as Markdown. [1], [2] cite the sources |
{ type: 'reasoning', text } | Thinking, live with a timer, then folded into "Thought for 12s" |
{ type: 'step', id, label, status, detail? } | A plan that ticks itself off; the phases of deep research |
{ type: 'tool', id, name, status, kind?, input?, output?, results?, progress?, image? } | A tool card: kind is 'search', 'code', 'file', 'image' or 'generic'. Timed from its first chunk to its last |
{ type: 'source', id, title, url, snippet?, site?, icon? } | A source: cards under the reply, hover cards on its citations |
{ type: 'artifact', id, title?, kind?, language?, text?, done? } | Writes into an artifact. The same id in a later reply is its next version |
{ type: 'research', title?, progress?, activity? } | Deep research: the progress card, its bar (0 to 1) and what it's doing now |
{ type: 'followUps', items } | Questions to ask next, under the latest reply |
Older history and your own state
Give useChat a loadOlder that fetches the messages before the oldest one; return [] when there are no more. Or keep messages in your own store: Chat is controlled, and useChat is optional.
const chat = useChat({ adapter, initialMessages: latestPage, loadOlder: (oldest) => api.messages({ before: oldest?.id }) });
<Chat messages={messages} status={typing ? 'streaming' : 'idle'} onSend={(text, files, { mode } = {}) => store.send({ text, files, mode })} />
Versions: edit and regenerate
Editing a message adds it as a new version beside the old one, with its own reply; Regenerate adds a new reply beside the old. A "‹ 2/3 ›" switcher on the message steps through them, and everything after follows the version shown. useChat keeps the tree and gives onBranchChange; messages is always the thread on screen, with branch: { index, count } on messages that have versions. Press ↑ in an empty composer to edit your last message.
<View style={{ height: 460, width: '100%', maxWidth: 560 }}> <Chat {...chat} suggestions={chat.messages.length ? [] : ['When should I visit Lisbon?']} onCopy={() => {}} /> </View>
The composer
The message box grows to eight lines, then scrolls. Pass what you need and it appears:
modesturns on chips such as Search, Deep research and Think; the one on is sent with the message (mode) and shown on it. On narrow screens they fold into a Tools menu.commandsopens a menu when/starts the message;mentionsopens one on@. Arrow keys move through it, Enter or Tab picks, Escape closes. A command can turn a mode on or insert a template.onAttachadds a + for your picker. On the web, files can also be pasted (screenshots) or dropped on the composer. WithonUpload, each shows its progress, and Send waits until they're all up.maxLengthshows a count near the limit and blocks sending past it; long messages show a token estimate.onDictateadds a microphone for your speech-to-text (write into the draft withdraftandonDraftChange);onVoiceModeturns the empty composer's send button into a voice mode button.composerToolssits before the send button, such as a model picker.noticeanddisabledcover offline and rate limits.
<View style={{ height: 520, width: '100%', maxWidth: 640 }}> <Chat {...chat} modes={AI_CHAT_MODES} commands={AI_CHAT_COMMANDS} mentions={AI_CHAT_MENTIONS} onAttach={() => [{ id: String(Date.now()), name: 'boarding-pass.pdf', size: 92000 }]} onUpload={demoUpload} maxLength={4000} onDictate={() => {}} placeholder="Type / for commands, @ for tools" emptyState={null} /> </View>
Thinking and tools
Reasoning streams open, with "Thinking 4s" counting and a band of light passing over it, then folds into "Thought for 12s". Tool calls draw by kind: a web search with its query, the sites' icons and its results; code with its output in a terminal; a file it read; an image being generated, breathing as its progress climbs, then the picture, which opens full screen. Each shows how long it took and opens to show what it was asked and returned.
<View style={{ height: 640, width: '100%', maxWidth: 640 }}> <Chat messages={messages} onSend={() => {}} /> </View>
Tool cards and approvals
A tool call can draw as your own card: renderToolCall(call, message) gets each call (its result is in call.data) and returns a node, or undefined to keep the built-in block. A call that changes something can wait for the person: give it status 'approval' and the block shows what it will do with Approve and Cancel, calling onToolApproval(call, approved). For a richer card, draw an ApprovalCard from renderToolCall. After Cancel, set the status to 'denied'.
<View style={{ height: 520, width: '100%', maxWidth: 640 }}> <Chat messages={messages} onSend={() => {}} renderToolCall={(call) => call.name === 'spending_summary' ? ( <Card title={call.data.total} description={`Most went to ${call.data.top}`} /> ) : call.status === 'approval' ? ( <ApprovalCard title="Add $50 to Japan" changes={[{ label: 'Japan', before: '$3,420', after: '$3,470' }]} approveLabel="Add $50" onApprove={() => {}} onDeny={() => {}} /> ) : undefined } /> </View>
The Pro app kit's @kit/ai does this for you on the AI SDK: tools that run on the device, approval cards for writes and Undo for reversible changes. See Kit: AI assistant.
Artifacts
When a reply writes an artifact, it shows as a card in the thread and opens in a panel: beside the thread from 900 points wide (by itself as it streams, as Claude does), full screen on phones. Code has line numbers and highlighting; documents, tables (CSV) and charts ({ type, xKey, series, data } as JSON) have Preview and Code tabs; HTML previews in a sandboxed frame on the web. The same artifact id in a later reply is its next version, and ‹ › steps between them. Copy uses onCopy; Download saves the file on the web, or calls onArtifactDownload on phones.
<View style={{ height: 560, width: '100%' }}> <Chat messages={messages} onSend={() => {}} onCopy={() => {}} /> </View>
ArtifactPanel works on its own too: give it versions (each with a messageId), onClose and optionally version, onVersionChange, onCopy and onDownload.
Sources and citations
[1], [2] in a reply become citation chips. Hover one on the web (or long-press it on a phone) for a card with the site's icon, the title and a line from the page; press it to open the source. Under the reply, the first sources show as cards, and the rest fold into a "+9 more" card that opens them all in a side drawer. Without a site, a source is named by its host; without an icon, it gets a tile with its first letter in a color of its own.
<View style={{ height: 420, width: '100%', maxWidth: 640 }}> <Chat messages={messages} onSend={() => {}} /> </View>
Deep research
Stream a research chunk and the reply opens with a progress card: the question, a bar through its phases (its step chunks), what it's reading now with the sites it has read, and the time so far. Searches and sources arrive as it works; the report streams into a document artifact, so it opens in the panel with its headings, tables and citations, while the reply gives the short answer. Try it with the Deep research chip, or /research:
<View style={{ height: 640, width: '100%' }}> <Chat {...chat} modes={AI_CHAT_MODES} suggestions={chat.messages.length ? [] : ['Research the best month to visit Lisbon']} emptyState={null} /> </View>
async function* adapter({ messages, signal }) {
yield { type: 'research', title: 'Best month to visit Lisbon', progress: 0.05, activity: 'Planning' };
yield { type: 'step', id: 'search', label: 'Search the web', status: 'running' };
for await (const source of searchAndRead(messages.at(-1).text, signal)) {
yield { type: 'source', ...source };
yield { type: 'research', progress: source.progress, activity: `Reading ${source.site}` };
}
for await (const text of writeReport(signal)) yield { type: 'artifact', id: 'report', title: 'Research report', kind: 'document', text };
yield { type: 'research', progress: 1 };
}
A whole assistant screen
AIChatScreen is the live example at the top of this page. On wide screens the history sits beside the thread; on phones it's a drawer from the side. It groups conversations under Pinned, Today, Yesterday, Previous 7 days and Older, searches them, files them in projects, and each has a menu to rename it in place, pin it, move it, share it (a dialog with the link from shareUrl) or delete it, with an Undo toast. A new chat becomes a conversation, titled from its first message, as soon as it's sent (onConversationCreate). loadConversation gives the thread of one that's opened. While scrolled up, a pill counts the messages that came in; the thread stays at the bottom while you're there, and stops following when you scroll up.
<AIChatScreen
title="Atlas"
adapter={adapter}
models={models}
modes={[{ id: 'search', label: 'Search', icon: 'globe' }, { id: 'research', label: 'Deep research', icon: 'telescope' }]}
conversations={history}
projects={projects}
loadConversation={(id) => api.thread(id)}
onConversationCreate={api.create}
onConversationRename={api.rename}
onConversationPin={api.pin}
onConversationMove={api.move}
onConversationDelete={api.remove}
shareUrl={(id) => `https://atlas.app/share/${id}`}
/>
Errors, offline and rate limits
A failed message shows Retry; a reply that broke off keeps what came in. offline shows "You're offline" above the composer and blocks sending; limit shows when the user is out of messages, when it resets and an Upgrade button.
<AIChatScreen title="Atlas" initialMessages={demoThread('c1', Date.now())} limit={{ message: 'You’ve reached the Atlas Pro limit', resetAt: Date.now() + 3600000, actionLabel: 'Upgrade', onAction: () => {} }} />
Voice mode
VoiceMode is the full-screen voice conversation: a glowing orb that swells with the voice (amplitude, 0 to 1) while listening or speaking and breathes while thinking, the state, live captions of both sides, and Mute and End. It's only the screen: feed it your audio adapter's state and levels. useDemoVoice plays a pretend session. In AIChatScreen, pass onVoiceStart (and voice with your live values) and the composer's voice button opens it.
<VoiceMode title="Atlas" {...voice} onEnd={() => {}} />
Markdown on its own
Markdown renders replies, and works anywhere: headings, lists, quotes, GFM tables, fenced code that scrolls sideways, inline code, bold, italic, strikethrough and links. Only http, https, mailto and tel links open. An unfinished code fence renders as code while it streams.
<Markdown>{`### Release notes - **Faster** cold start - Fixed ~~flicker~~ on Android - nested lists work too > Update before Friday. \`npm i patine-ui\` and see [the docs](https://example.com).`}</Markdown>
Designs
| Replies | Quick replies | Code and tables | |
|---|---|---|---|
brand | On the page, full width | Outlined, round | Filled |
ios | Grey bubbles, like Messages | Filled capsules | Filled |
material | On the page, like Gemini | Outlined chips, 8dp corners | Filled |
web | On the page, like ChatGPT and Claude | Outlined | Outlined |
Accessibility
- The thread is named "Conversation", and each finished reply is read out to screen readers (iOS and Android). A streaming reply is marked busy.
- Enter sends and Shift+Enter adds a line on hardware keyboards; ↑ in an empty composer edits your last message; Escape stops a streaming reply or closes the
/and@menus, which arrow keys and Enter or Tab drive. - Reasoning, plans and tool calls are disclosure buttons with their expanded state; the plan marks the running step as current; image generation is a progress bar with its value.
- Mode chips are switches with their checked state; the version switcher, citation chips (links named "Source 2: title"), artifact cards, sources and every icon button are labelled, and every label can be translated with
labels. - Voice mode announces its state and captions as they change; Mute is a toggle with its pressed state.
- Touch targets are at least 44 points. The caret, shimmer, orb and pulses hold still, and "Jump to latest" doesn't animate, when the OS asks to reduce motion.
Props
Chat
| Prop | Type | Default | Description |
|---|---|---|---|
messages | ChatMessage[] | — | Required. The thread, oldest first. |
onSend | (text, attachments, extra?) => void | — | Required. extra holds the mode it was sent in. |
status | 'idle' | 'streaming' | 'idle' | While 'streaming', send turns into Stop. |
onStop / onRetry(id) | — | Stop the reply; resend a failed message or replace a failed reply. | |
onRegenerate(id) / onEdit(id, text) | — | Regenerate under replies, Edit on the user's messages. | |
onBranchChange(id, index) | — | Shows "‹ 2/3 ›" on messages with versions. | |
onCopy / onFeedback | — | Copy under messages, on code and artifacts; thumbs under replies. | |
onLoadOlder / hasOlder / loadingOlder | — | Loads older messages near the top. | |
modes / mode / onModeChange | ChatMode[] | — | Mode chips in the composer, sent with the message. |
commands / mentions / onCommand | ChatCommand[] | — | The / and @ menus. |
onAttach / onUpload | — | The + button; uploads with progress, also for pasted and dropped files. | |
maxLength | number | — | A count near the limit; blocks sending past it. |
draft / onDraftChange | — | The composer's text, controlled: for dictation. | |
onDictate / onVoiceMode | — | A microphone; a voice mode button while the composer is empty. | |
composerTools / composerTop | ReactNode | — | Before the send button (a model picker); above the composer. |
notice / disabled | — | A banner above the composer; blocks sending. | |
autoFocus | boolean | false | Focuses the message box as the chat appears, such as in a panel opened with a keyboard at hand. |
autoFocus | boolean | false | Focuses the message box as the chat appears, e.g. an assistant panel opened with a keyboard at hand. |
onArtifactDownload / autoOpenArtifacts | — / true | Download on phones; open artifacts as they stream on wide screens. | |
contentWidth | number | full width | The thread and composer's widest, centered. |
suggestions / onSuggestionPress | string[] | [] | Quick replies above the composer. |
onSourcePress / onLinkPress / onFollowUpPress | open the link / send it | ||
emptyState / renderMessage | — | Shown while empty; draw a message yourself. | |
renderToolCall | (call, message) => ReactNode | undefined | — | Draws a tool call as your card (its result in call.data); undefined keeps the built-in block. |
onToolApproval | (call, approved) => void | — | Answers a call with status 'approval': its block shows Approve and Cancel. |
placeholder / keyboardOffset / labels | 'Message' / 0 / English |
useChat
| Option | Type | Description |
|---|---|---|
adapter | ({ messages, signal, mode }) => string | AsyncIterable<ChatChunk> | Required. Your backend; may be async. |
initialMessages | ChatMessage[] | The thread to start with. |
loadOlder | (oldest) => Promise<ChatMessage[]> | Older messages, oldest first; [] when there are no more. |
createId | () => string | Ids for new messages. |
Returns messages, status, onSend, onStop, onRetry, onRegenerate, onEdit, onBranchChange, onFeedback, onLoadOlder, hasOlder, loadingOlder and setMessages.
ChatMessage
| Field | Type | Description |
|---|---|---|
id / role / text | text is Markdown. | |
reasoning / reasoningMs | string / number | Thinking, and how long it took. |
toolCalls | ChatToolCall[] | { id, name, status, kind?, input?, output?, data?, results?, progress?, image?, language?, startedAt?, durationMs? }. status: 'running', 'approval', 'done', 'error' or 'denied'; data is the result for renderToolCall. |
steps | { id, label, status, detail? }[] | The plan, or deep research's phases. |
sources | { id, title, url, snippet?, site?, icon? }[] | Cited as [1], [2]… |
artifacts | { id, title, kind, language?, content, streaming? }[] | kind: 'code', 'document', 'table', 'chart' or 'html'. |
research | { title, progress?, activity?, startedAt?, durationMs? } | Deep research's progress. |
mode | string | The mode it was sent in. |
branch | { index, count } | Set by useChat on messages with versions. |
followUps / feedback / attachments | ||
status / error / createdAt | 'sending' | 'streaming' | 'done' | 'stopped' | 'failed'. |
AIChatScreen
Everything Chat takes for the composer (modes, commands, mentions, onAttach, onUpload, onDictate), plus:
| Prop | Type | Description |
|---|---|---|
adapter / onSend | Your backend, or (text, history) => Promise<string>. Default: demoAssistant. | |
title / subtitle / suggestions | The header, and prompt cards for the empty state. | |
models / model / onModelChange | { id, label, description? }[] | The model menu in the composer. |
conversations / activeConversation / projects | The history, { id, title, updatedAt, pinned?, projectId? }[], and its folders. | |
loadConversation | (id) => ChatMessage[] | Promise | The thread of a conversation that's opened. |
onConversationSelect / onConversationCreate / onConversationRename / onConversationPin / onConversationMove / onConversationDelete | Keep your store in step. Delete is called after Undo has gone. | |
shareUrl | (id) => string | Shows Share, with this link. |
onVoiceStart / onVoiceEnd / voice | Voice mode, and your live { state, amplitude, caption, userCaption, muted, onMutedChange }. | |
offline / limit | boolean / { message, resetAt?, actionLabel?, onAction? } | Banners that block sending. |
onCopy / onSourcePress / onBack / now / labels |
VoiceMode
| Prop | Type | Description |
|---|---|---|
state | 'connecting' | 'listening' | 'thinking' | 'speaking' | Required. |
amplitude | number | The live level, 0 to 1. |
caption / userCaption | string | What's being said, and the user's last words. |
muted / onMutedChange | The Mute toggle. | |
onEnd | () => void | Required. The End button. |
title / labels |
Parts
Build your own layout from the same pieces: Markdown, Plan, Sources (sources, onPress, onShowAll, max), Reasoning (children, streaming, startedAt, durationMs), ToolCall (call, onSourcePress, onImagePress), ArtifactPanel, VoiceMode, ChatSuggestions and AttachmentList. Helpers: streamText, streamServerEvents, simulateStream(text, { delay, reasoning, signal }), createTree and threadOf for the versions tree, collectArtifacts, estimateTokens and titleFromPrompt. Demo data: demoAssistant, demoThread, demoConversations, demoUpload, useDemoVoice, DEMO_SOURCES, AI_CHAT_MODES, AI_CHAT_COMMANDS, AI_CHAT_MENTIONS, AI_CHAT_PROJECTS, AI_CHAT_PROMPTS and AI_CHAT_MODELS.
Related
- MessageBubble & ChatComposer: the free bubble and input.
- Messenger: a chat between people.
- Image Viewer: opens images in messages full screen.