Quickstart
The AI components give your React app the screens of an AI assistant: a conversation that streams the agent's replies, a prompt composer with attachments and dictation, the agent's reasoning and tool calls, and a face for a voice agent. They ship with stream-chat-react in its stream-chat-react/ai-components entry point. The agent behind them runs on Stream Agents: you describe it once, with its instructions, knowledge, tools and voice, and your app talks to it with the @stream-io/stream-agents SDK.
This page shows what you can build, how the pieces fit together, and takes you from an empty project to a working assistant.
What you can build
| You want to build | Start with |
|---|---|
| An AI-first app, like ChatGPT or Claude: one user, one assistant, many conversations | This page, then the Personal assistant use case |
| A support agent that answers from your help center, looks up orders and hands over to your team | The Customer support agent use case |
| A voice agent the user talks to, with a visual presence and a written transcript | The Voice agent use case |
| An agent that shows its work and asks before it acts | Reasoning and tool calls |
| An agent that runs tools in the browser, on the page the user has open | The Personal assistant use case |
| Replies that are UI, such as a trip plan with a map and a form | Generative UI |
AI replies in a chat you already built with MessageList |
SDK integration |
Voice runs through all of them. The composer has a microphone button that dictates into it, and the same agent can hold the conversation out loud: VoiceSession puts it on a call with the user, VoiceGlow or VoiceWave shows what it's doing, and AIConversation writes out what was said.
How it fits together
Your app never talks to the model, and it doesn't run the agent. It opens a session with your agent and asks it things. The agent runs on Stream's router, which calls the model, runs the agent's tools and writes the conversation into a Stream Chat channel as it goes. The components show that channel:
sequenceDiagram
participant App as React app
participant Router as Stream Agents
participant LLM as Model
participant Chat as Stream Chat
App->>Router: sessions.create() with @stream-io/stream-agents
App->>Router: responses.create("How do I...?")
Router->>LLM: The conversation so far
LLM-->>Router: Reasoning, tool calls, tokens
Router-->>Chat: The question, and the reply as it streams, with its steps
Chat-->>App: The channel's messages
Note over App: AIConversation shows them@stream-io/stream-agentssigns the user in, opens sessions, asks, stops a reply, answers the questions of tools that ask first, and runs the tools your page gives the agent.stream-chat-react/ai-componentsshows it all:AIConversationandAIMessageComposer, the reasoning and tool calls of each reply, the UI the agent writes, and the voice visualizations.- Your agent lives in a folder of plain files that you sync with the Stream CLI: its instructions, knowledge, skills, tools, connectors and models.
For voice, VoiceSession starts the agent on a call and joins it from the browser. The agent hears the user and answers out loud, and what is said is written into the session's channel.
Before you start
- A Stream app, from the Stream Dashboard.
- The Stream CLI.
- A React 18 or later app.
Step 1: Create the agent
Install the CLI, pick your Stream app, and make an agent from the text template:
curl -fsSL https://getstream.io/cli.sh | bash
getstream init # pick or create a Stream app
getstream agents init my-agent --template text # or --template voiceThat creates agents/my-agent/, with the agent's settings in agent.yaml, its system prompt in instructions.md, and a guardrail in guardrail.md. The template's guardrail turns away anything that isn't about Acme Corp, its example company, so write what the agent is for in both files, then sync it to Stream and try it in the terminal:
getstream agents sync my-agent
getstream agents test my-agentThe Stream Agents quickstart covers the agent's folder: knowledge, skills, tools, connectors and guardrails.
Step 2: Install the SDKs
Add @stream-io/stream-agents, the client for your agent, and stream-chat-react, which has the views. stream-chat is the Stream Chat client that reads the conversation the agent writes:
npm install @stream-io/stream-agents stream-chat stream-chat-reactThis page uses stream-chat-react v15, with stream-chat v10. The stream-chat-react/ai-components entry point needs no other package. Load its stylesheet next to the default SDK styles, once, where your app starts:
import "stream-chat-react/dist/css/index.css";
import "stream-chat-react/dist/css/ai-components.css";In a Next.js App Router app, these components and hooks run in the browser only. Put "use client" at the top of each file that renders a stream-chat-react component or calls a hook, such as the files of steps 4 to 6 below.
If your agent answers with generative UI, also install the packages of the format it writes, A2UI or OpenUI, as that guide describes. The composer's microphone button dictates with the browser's Web Speech API, so it needs no package, and it renders nothing in browsers without it, such as Firefox.
Is your agent on a backend of your own? Skip @stream-io/stream-agents, and have your backend write the agent's replies into a Stream Chat channel, by hand or with the Stream Chat AI SDK or the Stream Chat LangChain SDK. Conversation state describes what it sends: the ai_generated and generating fields of a reply, and the AI indicator events that say what the agent is doing. The client keeps the latest of those on the channel, as one of the states stream-chat exports as AIStates:
AIStates.Thinking,AI_STATE_THINKING: the model is working out an answer.AIStates.ExternalSources,AI_STATE_EXTERNAL_SOURCES: the model is checking external sources, such as with a tool call.AIStates.Generating,AI_STATE_GENERATING: the answer is being written into the message.AIStates.Error,AI_STATE_ERROR: the reply failed.AIStates.Stop,AI_STATE_STOP: the user asked to stop the reply.AIStates.Idle,AI_STATE_IDLE: nothing is happening.
The useAIState hook from stream-chat-react reads it.
Step 3: Sign the user in
Create one Client for your app with your API key, and set the user once they sign in. The user's Stream token comes from your backend, which mints it with your API secret, as described in authentication. The client asks for it again when it expires:
import { Client } from "@stream-io/stream-agents";
export const api = new Client({ apiKey: "your_api_key" });
export async function signIn(user: { id: string; name: string }) {
await api.setUser(user, async () => {
const response = await fetch("/api/stream-token");
if (!response.ok) throw new Error(`token: ${response.status}`);
return response.text();
});
}/api/stream-token is a route of your backend that mints the token for the user signed in to your app, with your API secret and Stream's Node.js SDK, which you add to your server with npm install @stream-io/node-sdk. In a Next.js App Router app, it can be a route handler:
import { StreamClient } from "@stream-io/node-sdk";
// Your own sign-in: the user the request comes from, or undefined.
import { getSignedInUser } from "@/auth";
const client = new StreamClient(
process.env.STREAM_API_KEY!,
process.env.STREAM_API_SECRET!,
);
export async function GET(request: Request) {
const user = await getSignedInUser(request);
if (!user) return new Response("Not signed in", { status: 401 });
const token = client.generateUserToken({
user_id: user.id,
validity_in_seconds: 60 * 60,
});
return new Response(token);
}The API secret stays on your server: never send it to the browser. A token is good for an hour here, and the client asks the route for a new one when it expires.
To try things out before you have a backend, mint a token for a test user with the CLI, getstream token jane --ttl 2h, and pass it as api.setUser({ id: "jane" }, "...").
Step 4: Connect a conversation to the agent
A session is one conversation with your agent, and its channel is where the agent writes it: the user's questions, each reply as it streams, and the reasoning and tool calls of each reply as the reply's attachments.
AgentChat, from the @stream-io/stream-agents/chat entry point, reads the session's channel and asks through the session. agentChatTransport hands it to an AIConversationController, which the views take. Add a hook that makes both:
import { AgentChat, agentChatTransport } from "@stream-io/stream-agents/chat";
import { useEffect, useState } from "react";
import type { LocalMessage } from "stream-chat";
import {
AIClientIdentity,
AIConversationController,
fromStreamMessage,
} from "stream-chat-react/ai-components";
import { api } from "./agent";
export type AgentConversation = {
chat: AgentChat<LocalMessage>;
conversation: AIConversationController;
};
/** A conversation with the agent: `sessionId` carries one on, undefined starts a new one. */
export function useAgentConversation(userId: string, sessionId?: string) {
const [state, setState] = useState<AgentConversation>();
useEffect(() => {
const sessions = api.agent("my-agent").sessions;
// The session opens when the user first asks.
const chat = new AgentChat<LocalMessage>({
sessionId,
open: (id) => (id ? sessions.resume(id) : sessions.create()),
});
const conversation = new AIConversationController({
transport: agentChatTransport(chat, {
adapt: (message, reasoningText) =>
fromStreamMessage(message, { reasoningText }),
}),
// Hides regenerate and edit. Leave this out to offer them: earlier versions are kept as branches.
actions: { edit: false, regenerate: false },
// Answers the tools that ask before they run.
approver: {
userId,
clientId: AIClientIdentity.installId(),
decide: (call, allowed) => chat.decide(call.id, { allowed }),
},
});
setState({ chat, conversation });
return () => {
conversation.dispose();
void chat.close();
};
}, [userId, sessionId]);
return state;
}fromStreamMessage turns each of the channel's messages into the AIMessage the views show: a reply is a message with custom.ai_generated: true, it's being written while custom.generating is true, and its steps are its ai_reasoning and ai_tool_call attachments. The session opens when the user first asks, so a conversation the user only looked at is never created. When the component unmounts, chat.close() closes the conversation: a new one that nothing was asked in is deleted, and any other is ended, keeping what it recorded.
Step 5: Show the conversation
Show the conversation with AIConversation, and the composer below it. Both take the controller:
import type { ReactNode } from "react";
import {
AIConversation,
type AIConversationController,
AIMessageComposer,
} from "stream-chat-react/ai-components";
export const AgentConversationView = ({
conversation,
actions,
}: {
conversation: AIConversationController;
/** More buttons for the composer, such as step 6's Talk button. */
actions?: ReactNode;
}) => (
<div
style={{
display: "flex",
flexDirection: "column",
height: "100dvh",
maxWidth: "48rem",
marginInline: "auto",
}}
>
<AIConversation conversation={conversation} />
{/* In an element of its own, or the form grows to fill the column. */}
<div style={{ padding: "0 1rem 1rem" }}>
<AIMessageComposer conversation={conversation} layout="inline">
<AIMessageComposer.TextInput />
<AIMessageComposer.SpeechToTextButton />
{actions}
<AIMessageComposer.SubmitButton />
</AIMessageComposer>
</div>
</div>
);AIConversation scrolls inside itself, so it needs a height: here it fills the column above the composer. The inline layout puts the text and the buttons on one line. The column is at most 48rem wide and centered, so lines stay short enough to read on a wide window.
The controller shows the question as soon as it's sent and the agent thinking until its reply starts, turns the send button into a stop button while the agent answers, and loads older messages as the user scrolls up.
The AI components bring the SDK's theme scope, the str-chat class, so they take the SDK's fonts, colors and spacing without a wrapper. Render them inside Chat for the SDK's translations, as described in Localization, and its theme for their light or dark theme.
Sign the user in, then show the conversation, for example from a button:
import { useState } from "react";
import { Button } from "stream-chat-react";
import { signIn } from "./agent";
import { AgentConversationView } from "./AgentConversationView";
import { useAgentConversation } from "./useAgentConversation";
const user = { id: "jane", name: "Jane" };
export const App = () => {
const [signedIn, setSignedIn] = useState(false);
return signedIn ? (
<Conversation />
) : (
<div className="str-chat">
<Button
appearance="solid"
onClick={() => void signIn(user).then(() => setSignedIn(true))}
size="md"
type="button"
variant="primary"
>
Ask the agent
</Button>
</div>
);
};
const Conversation = () => {
const agent = useAgentConversation(user.id);
return agent ? (
<AgentConversationView conversation={agent.conversation} />
) : null;
};Run the app and ask something. While the agent works on a reply that shows nothing yet, the conversation shows it thinking. Then the reply writes itself out, with Markdown, code and charts, and with the reasoning and tool calls that led to it. While it writes, the Stop button stops it, and under each finished reply the user can copy, share and rate it.
The Conversation view guide covers what else the screen can show, such as an empty state and a footer. The Composer guide adds attachments and chat options.
Step 6: Add voice
The composer already takes voice: its microphone button dictates into it.
To let the user talk to the agent instead, put the agent on a call in the conversation. The page joins the call with the microphone on. VoiceSession lives in the @stream-io/stream-agents/video entry point, and the Video React SDK plays the agent's audio:
npm install @stream-io/video-react-sdkGive the agent a face with VoiceGlow, which moves differently while the agent is connecting, listening, thinking and speaking. What is said on the call is written into the session's channel, so the conversation shows it as a transcript:
import type { AgentChat } from "@stream-io/stream-agents/chat";
import { VoiceSession } from "@stream-io/stream-agents/video";
import {
ParticipantsAudio,
StreamCall,
StreamVideo,
useCallStateHooks,
} from "@stream-io/video-react-sdk";
import { useEffect, useSyncExternalStore } from "react";
import type { LocalMessage } from "stream-chat";
import { Button } from "stream-chat-react";
import {
AIConversation,
type AIConversationController,
VoiceGlow,
} from "stream-chat-react/ai-components";
/** Puts the agent on a call in the conversation. Call it from a click. */
export async function startVoice(chat: AgentChat<LocalMessage>) {
// Opens the session if nothing was asked yet, and keeps the conversation.
const session = await chat.use();
await session.voice.start();
return VoiceSession.of(session);
}
export const AgentVoice = (props: {
voice: VoiceSession;
conversation: AIConversationController;
onHangUp: () => void;
}) => {
const { voice, conversation, onHangUp } = props;
const { call, client, failure, muted, status } = useSyncExternalStore(
voice.subscribe,
voice.get,
);
// Joins with the microphone on. A failure, such as a denied microphone, lands in `failure`.
useEffect(() => {
voice.join().catch(() => undefined);
}, [voice]);
// Leaves the call and takes the agent off it. The conversation goes on in writing.
const hangUp = async () => {
await voice.leave().catch(() => undefined);
await voice.session.voice.stop().catch(() => undefined);
onHangUp();
};
return (
<div className="str-chat">
<VoiceGlow state={status} style={{ width: 240, height: 240 }} />
{failure && <p role="alert">{failure.message}</p>}
{call && client && (
<StreamVideo client={client}>
<StreamCall call={call}>
<AgentAudio />
</StreamCall>
</StreamVideo>
)}
{/* What was said, written out. It scrolls inside itself, so it needs a height. */}
<div style={{ height: 360 }}>
<AIConversation conversation={conversation} />
</div>
<Button
appearance="outline"
onClick={() => void voice.setMuted(!muted).catch(() => undefined)}
size="md"
type="button"
variant="secondary"
>
{muted ? "Unmute" : "Mute"}
</Button>
<Button
appearance="solid"
onClick={() => void hangUp()}
size="md"
type="button"
variant="danger"
>
Hang up
</Button>
</div>
);
};
/** Plays the agent. */
const AgentAudio = () => {
const { useRemoteParticipants } = useCallStateHooks();
return <ParticipantsAudio participants={useRemoteParticipants()} />;
};Then, in App.tsx, replace step 5's Conversation with one that has a Talk button, which switches the conversation to voice and back:
import type { VoiceSession } from "@stream-io/stream-agents/video";
import { AgentVoice, startVoice } from "./AgentVoice";
// In place of step 5's Conversation.
const Conversation = () => {
const agent = useAgentConversation(user.id);
const [voice, setVoice] = useState<VoiceSession>();
if (!agent) return null;
if (voice) {
return (
<AgentVoice
conversation={agent.conversation}
onHangUp={() => setVoice(undefined)}
voice={voice}
/>
);
}
const talk = () => startVoice(agent.chat).then(setVoice, console.error);
return (
<AgentConversationView
actions={
<Button
appearance="outline"
onClick={() => void talk()}
size="sm"
type="button"
variant="secondary"
>
Talk
</Button>
}
conversation={agent.conversation}
/>
);
};The Talk button calls startVoice from a click: a browser asks for the microphone and plays audio only after one. The transcript is the same conversation the chat shows, and hanging up goes back to it. @stream-io/stream-agents/video runs on @stream-io/video-client, which the Video React SDK brings in, so don't install it separately.
The Voice agent use case builds a whole voice screen: the agent's state, the visualizations, mute and hang up, and what was said written out as a conversation. For a call without a chat first, start one with VoiceSession.start(api.agent("my-agent")), whose leave() ends the session too. An agent made with --template voice also lets you pick its speech-to-text and text-to-speech models, its voice and its greeting.
Theming
The AI components follow the stream-chat-react theme. Each one puts the str-chat class and Chat's theme on its root, unless an ancestor such as ChatView, Channel or another AI component already has them, so they pick up the SDK's light and dark theme tokens. Set the dark theme with <Chat theme="str-chat__theme-dark">.
To keep an element of your own as the scope instead, such as a dark container rendered without Chat, render ThemeScopeProvider inside it, from version 15.0.1. An AI component can't see a class on your element, so without the provider it adds a scope of its own, which resets the tokens your element sets:
import {
AIConversation,
ThemeScopeProvider,
} from "stream-chat-react/ai-components";
<div className="str-chat str-chat__theme-dark">
<ThemeScopeProvider>
<AIConversation messages={messages} />
</ThemeScopeProvider>
</div>;To change them, set the --str-chat__ai-* CSS variables. The stylesheet never declares these variables itself, so your values win at any scope, including :root:
:root {
--str-chat__ai-accent: #7c3aed;
--str-chat__ai-user-message-bg: #ede9fe;
--str-chat__ai-syntax-keyword: #c084fc;
--str-chat__ai-voice-color: #7c3aed;
}| Variable | Styles |
|---|---|
--str-chat__ai-text-primary, --str-chat__ai-text-secondary |
Text |
--str-chat__ai-accent |
Accents, such as the icons of a reply's steps |
--str-chat__ai-user-message-bg, --str-chat__ai-user-message-text |
The user's message bubbles |
--str-chat__ai-border |
Borders, such as the composer's |
--str-chat__ai-syntax-* |
Code highlighting |
--str-chat__ai-voice-color, --str-chat__ai-voice-backdrop |
VoiceGlow and VoiceWave, and the surface they sit on, which picks their look |
The AI components section of the component variables reference lists more of them, with the SDK token each follows, and the stylesheet's _tokens.scss has every one. Focus rings use the SDK's --str-chat__border-utility-focused token.
The rules use the str-chat__ai- class prefix (for example str-chat__ai-message-composer__form and str-chat__ai-streaming-message), so you can target them with your own CSS, in a CSS layer like the rest of the SDK styles. The components draw stream-chat-react icons, which you replace through WithComponents like any other SDK icon.
Localization
Every text the components show, such as the composer's "Ask a question..." placeholder or "Thought for 12s", goes through Streami18n like the rest of the SDK. Inside Chat (or a TranslationProvider) they follow the active language, and outside it they show their built-in English copy.
The keys are namespaced under aiComponents.. To change some of the English copy, pass Chat an instance whose translationsForLanguage lists the keys to change:
import { Chat, Streami18n } from "stream-chat-react";
const streamI18n = new Streami18n({
translationsForLanguage: {
"aiComponents.messageComposer.textInput.placeholder":
"Message the assistant",
},
});
<Chat client={client} i18nInstance={streamI18n}>
{/* the conversation and the composer */}
</Chat>;Every other text stays as it is. English is the only bundled language, so register a dictionary with registerTranslation() to translate them, as described in the Localization guide. The library's README lists every key with its English copy.
The components
Everything below is exported from stream-chat-react/ai-components.
| Component or hook | What it does | Guide |
|---|---|---|
AIConversation |
Lays out a conversation the way AI assistants do | Conversation view |
AIUserMessage, AIAssistantMessage, AIReplyActions, AIMessageAttachment |
Show the user's messages and the agent's replies, their images and files, and the actions under each reply | Conversation view |
AISuggestions |
Offers conversation starters | Conversation view |
fromStreamMessage |
Turns a Stream Chat message into the AIMessage the views show |
Conversation state |
AIMessageComposer, ChatOptionsList, SelectedChatOptionChip, useText, useAttachments, useIsDisabled, useAIMessageComposerContext |
Takes what the user writes, with attachments, chat options and a model picker | Composer |
useSpeechToText |
Dictates with the browser's Web Speech API | Composer |
StreamingMessage, AIMarkdown |
Types out Markdown, code, tables and charts as they stream | Streaming messages |
AIStateIndicator, AITypingIndicator |
Shows what the agent is doing before its reply has text | Streaming messages |
AIMessageParts, AIMessagePart, AIReasoning, AIThinking, AIToolCall |
Shows a reply's reasoning and tool calls | Reasoning and tool calls |
AIToolApproval, AIToolApprovalCard, AIToolArguments, AIToolApproverProvider, useAIToolApprover, AIClientIdentity |
Asks the user before a tool runs | Reasoning and tool calls |
AIToolAuthorization, AIToolAuthorizationCard, createPopupAuthorizer, completeConnectorSignIn |
Signs the user in to a connector a tool call waits for | Reasoning and tool calls |
AIUIHost, AIUIView, defineAIUIComponent, AIUIComponentView, AIUIRuntimeView, AIUIEntrance, AIUIEntranceStage, useAIUIEntrance, useAIUIHostRefresh |
Shows UI the agent writes in place of a reply's text | Generative UI |
VoiceGlow, VoiceWave, useAudioLevel |
Shows what a voice agent is doing | Voice visualizations |
useHeardText |
Reveals a spoken reply at the pace the user hears it | Voice agent |
--str-chat__ai-* CSS variables |
Set the colors of all of them | Theming |
The main stream-chat-react entry point has AI support of its own, for chats built with MessageList: StreamedMessageText, an AIStateIndicator that follows the channel's AI state, and the StopAIGenerationButton the default composer shows, described in SDK integration. Its useAIState and useMessageTextStreaming hooks are in the AI hooks reference, with useSpeechToText from this entry point.
Migrating from @stream-io/chat-react-ai
The components used to ship as the standalone @stream-io/chat-react-ai package, which they replace. To move to stream-chat-react/ai-components:
-
Dependencies. Remove
@stream-io/chat-react-ai, and upgradestream-chat-reactto v15. Removematerial-symbolsas well if you only installed it for these components: they renderstream-chat-reacticons now. -
Imports. Replace the package name in imports, and the stylesheet path:
Before After @stream-io/chat-react-aistream-chat-react/ai-components@stream-io/chat-react-ai/styles/index.cssstream-chat-react/dist/css/ai-components.css -
Class names and CSS variables. The
aicr__prefix becamestr-chat__ai-.aicr__ai-message-composer…becomesstr-chat__ai-message-composer…, every otheraicr__…class becomesstr-chat__ai-…, and--aicr__…variables become--str-chat__ai-…. The full mapping table lists every renamed class and variable. -
useMessageTextStreaming. The hook is no longer exported next to the AI components. Import it fromstream-chat-reactand rename itsletterIntervalMsoption tostreamingLetterIntervalMs. TheStreamingMessageprops haven't changed. -
SpeechToTextButton. It's only available asAIMessageComposer.SpeechToTextButton, and itsoptionsprop is now passed to the speech recognizer.
The component APIs are otherwise unchanged.
Coming from stream-chat-react/ai-components on v14? Its exports, props, class names and CSS variables are the same on v15. Only the translation keys changed, to the namespaced keys described in Localization, so rename the ones you registered translations for.
Next steps
- Customer support agent: answers from your help center, order lookups, a refund the user confirms, and a handover to your team.
- Personal assistant: a list of conversations, tools that run in the browser, and a voice mode.
- Voice agent: a voice conversation with the agent as a glowing globe, and what was said written out.
- The AI cookbooks: an AI chat widget, streamed answers with a stop button, and voice agent visuals.
- The React assistant sample, a complete app built on these components with a list of conversations, photos, voice mode, connector sign-ins and tools that run in the browser, and the ChatGPT-style app in the
examples/ai-chatbotfolder of thestream-chat-reactrepository. - Stream Agents: the agent itself, its tools, knowledge, connectors and phone numbers.