Personal assistant
A personal assistant knows what's on the user's plate. It knows where they are and what time it is for them, searches their email, keeps every conversation they've had with it, and listens when they'd rather talk than type.
What you'll build
- A side menu with the user's conversations, titled and searchable
- The user's local time and location, as tools the agent runs in the browser
- A question before the agent reads the user's location
- The user's Gmail, which they connect from the conversation
- Photos the user attaches to a question
- A voice mode in the same conversation
Starts from: the Quickstart, with api, signIn, useAgentConversation, startVoice and AgentVoice in your project.
Best practices
- Run in the browser what only the browser has, such as the user's local time or location. Only a tool's answer leaves the page.
- Let the browser ask for a permission when a tool first needs it, not when the page loads.
- Ask before a tool that shares or changes something, such as the user's location.
- Let users connect their own accounts, such as Gmail, from the conversation. The agent never sees their password.
Define the assistant
Make the agent from the voice template, so it can talk as well as write, and give it each user's Gmail as a connector:
getstream agents init assistant --template voicename: assistant
mode: voice
llm: llm-fast
connectors:
- gmail # each user signs in to their own Gmail
tools:
- name: device
tools: [get_local_context, get_location]
loading: fullThe tool group names the two tools the page gives the agent below. The router refuses a session that brings a tool no group names, as Your first tool explains.
Write what the assistant is for in instructions.md, then sync it with getstream agents sync assistant. Each user's account covers connectors that act as the user, and Catalog lists the others, such as Google Calendar and Notion.
Give the agent the browser's tools
A tool the page gives the agent runs in the browser. When the model calls it, its run runs and returns the answer the model sees. get_location declares an approval, so the user is asked first, with the reason the model gives:
import { Tools } from "@stream-io/stream-agents";
import { z } from "zod";
export const tools = new Tools()
.register({
name: "get_local_context",
description:
"The user's current date, local time, timezone and language. Call it before " +
"answering anything that depends on today or the time.",
parameters: z.object({}),
run: () =>
`It is ${new Date().toString()}, in ` +
`${Intl.DateTimeFormat().resolvedOptions().timeZone}. ` +
`Their language is ${navigator.language}.`,
})
.register({
name: "get_location",
description:
"Where the user is. Only call it when the answer depends on it, " +
"such as the weather or places nearby.",
parameters: z.object({
reason: z.string().describe("why you need it, in a few words"),
}),
displayTitle: "Checking where you are",
approval: {
title: "Share your location?",
reasonArgument: "reason",
allowTitle: "Share",
declineTitle: "Not now",
},
run: () =>
new Promise<string>((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
({ coords }) =>
resolve(
`Latitude ${coords.latitude}, longitude ${coords.longitude}.`,
),
() => reject(new Error("The browser couldn't tell where they are.")),
),
),
});The browser asks for the location the first time get_location runs, once the user has allowed the call. A tool that throws tells the model what went wrong, so the agent can say so. To keep an error's details from the model, new Tools({ onError: (error, call) => ... }) returns what it's told instead. Client-side tools covers them in full.
Open a conversation
Hold a conversation as the quickstart's useAgentConversation does, with the assistant and its tools. Pass the tools every time a conversation opens, new or carried on, since the session runs them only while the page holds it. A new one also names where a connector's sign-in comes back to, a page of your app, and belongs to the assistant project, which the list finds the assistant's conversations by. The approver answers the questions of the browser's tools, and gets an authorizer from createPopupAuthorizer, so when the agent first needs Gmail, the reply shows a Connect Gmail card that signs the user in, in a popup:
import { AgentChat, agentChatTransport } from "@stream-io/stream-agents/chat";
import { useEffect, useState } from "react";
import type { LocalMessage } from "stream-chat";
import {
AIClientIdentity,
AIConversationController,
createPopupAuthorizer,
fromStreamMessage,
} from "stream-chat-react/ai-components";
import { api } from "./agent";
import { tools } from "./tools";
export const returnUrl = `${window.location.origin}/connected.html`;
/** The project of the conversations this page opens, for the list to find. */
export const conversationProject = "assistant";
/** The conversation the user picked: `sessionId` carries one on, undefined starts a new one. */
export type Pick = { sessionId?: string; count: number };
export type Assistant = {
pick: Pick;
chat: AgentChat<LocalMessage>;
conversation: AIConversationController;
};
export function useAssistantConversation(userId: string, pick: Pick) {
const [state, setState] = useState<Assistant>();
useEffect(() => {
const sessions = api.agent("assistant").sessions;
// The session opens when the user first asks, or carries on `sessionId`.
const chat = new AgentChat<LocalMessage>({
sessionId: pick.sessionId,
open: (id) =>
id
? sessions.resume(id, { tools })
: sessions.create({
tools,
returnUrl,
project_id: conversationProject,
}),
});
const conversation = new AIConversationController({
transport: agentChatTransport(chat, {
adapt: (message, reasoningText) =>
fromStreamMessage(message, { reasoningText }),
}),
actions: { edit: false, regenerate: false },
approver: {
userId,
clientId: AIClientIdentity.installId(),
decide: (call, allowed) => chat.decide(call.id, { allowed }),
authorizer: createPopupAuthorizer({
returnUrl,
decline: async (call) => (await chat.session()).declineLogin(call.id),
}),
},
});
setState({ pick, chat, conversation });
return () => {
conversation.dispose();
void chat.close();
};
}, [userId, pick]);
// Undefined while the picked conversation opens.
return state?.pick === pick ? state : undefined;
}Each pick is a new object, and count tells them apart, so New conversation starts another one even while a new one is open. A new conversation's session opens only once the user asks something, so one the user only looked at is never created, Strict Mode included. A conversation that's no longer shown is closed, and picking it again carries it on.
The sign-in comes back to connected.html, which reports how it went and closes:
<script type="module">
import { completeConnectorSignIn } from "stream-chat-react/ai-components";
completeConnectorSignIn();
</script>Build it as a second entry of your app, such as a second input of a Vite build.
List the user's conversations
Each conversation is a session, which the router titles after its first answers. ConversationList lists the conversations this page opened, by their project, most recent first, and searches them. A conversation the user switched to voice keeps its project, so it stays in the list, and a call started elsewhere, which has none, stays out. It loads again whenever version changes, which AssistantHome below bumps when a conversation is created or answered:
import type { Schemas } from "@stream-io/stream-agents";
import { useEffect, useState } from "react";
import { Button } from "stream-chat-react";
import { api } from "./agent";
import { conversationProject } from "./assistant";
export const ConversationList = ({
onSelect,
selectedId,
version,
}: {
onSelect: (sessionId: string | undefined) => void;
/** The open conversation, marked in the list. */
selectedId?: string;
/** Changes when the list may have: a conversation created, or answered. */
version: number;
}) => {
const [sessions, setSessions] = useState<Schemas["Session"][]>([]);
const [search, setSearch] = useState("");
useEffect(() => {
let isCurrent = true;
const all = api.agent("assistant").sessions;
// The conversations this page opened, typed or switched to voice.
const filters = { limit: 50, filter: { project_id: conversationProject } };
const page = search ? all.search(search, filters) : all.query(filters);
page.then(
({ items }) => {
// An incognito session keeps no conversation to open.
if (isCurrent)
setSessions(items.filter((each) => each.conversation_id));
},
() => undefined,
);
return () => {
isCurrent = false;
};
}, [search, version]);
return (
<nav className="conversations">
<Button
appearance="solid"
onClick={() => onSelect(undefined)}
size="sm"
type="button"
variant="primary"
>
New conversation
</Button>
<input
className="conversations__search"
onChange={(event) => setSearch(event.target.value)}
placeholder="Search"
type="search"
value={search}
/>
{sessions.map((session) => (
<button
aria-current={session.id === selectedId}
className="conversations__item"
key={session.id}
onClick={() => onSelect(session.id)}
type="button"
>
{session.title || "New conversation"}
</button>
))}
</nav>
);
};An incognito session records nothing, so it never shows in the list. To offer one, such as from a toggle on a new conversation, create it in useAssistantConversation's open with incognito in place of the project:
sessions.create({ incognito: true, tools, returnUrl });It has no channel, so AgentChat draws its messages from the session's socket, and its replies can't be regenerated or edited.
Put it together
AssistantHome puts the list beside the open conversation, and opens a conversation when the user picks one in the list. Once a reply ends, which is when the router titles a new conversation, it loads the list again. A Talk button switches the open conversation to voice with the quickstart's startVoice and AgentVoice:
import type { VoiceSession } from "@stream-io/stream-agents/video";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "stream-chat-react";
import {
AIConversation,
AIMessageComposer,
type AIConversationControllerState,
isAIConversationAnswering,
useAIConversationState,
} from "stream-chat-react/ai-components";
import { AgentVoice, startVoice } from "./AgentVoice";
import {
type Assistant,
type Pick,
useAssistantConversation,
} from "./assistant";
import { ConversationList } from "./ConversationList";
const selectStatus = ({ status }: AIConversationControllerState) => ({
status,
});
/** `userId` is the signed-in user, as signIn() set them. */
export const AssistantHome = ({ userId }: { userId: string }) => {
const [pick, setPick] = useState<Pick>({ count: 0 });
const assistant = useAssistantConversation(userId, pick);
// Bumped when the list may have changed, so it loads again.
const [listVersion, setListVersion] = useState(0);
const refreshList = useCallback(() => setListVersion((n) => n + 1), []);
return (
// `str-chat` is the SDK's theme scope: its fonts, colors and spacing.
<div className="str-chat assistant">
<ConversationList
onSelect={(sessionId) =>
setPick(({ count }) => ({ sessionId, count: count + 1 }))
}
selectedId={assistant?.chat.id}
version={listVersion}
/>
{assistant ? (
<AssistantConversation
assistant={assistant}
key={pick.count}
onReplied={refreshList}
/>
) : (
<p className="assistant-placeholder">Opening…</p>
)}
</div>
);
};
const AssistantConversation = ({
assistant: { chat, conversation },
onReplied,
}: {
assistant: Assistant;
/** Called when a reply ends, which is when the router titles a new conversation. */
onReplied: () => void;
}) => {
const { status } = useAIConversationState(conversation, selectStatus);
const isAnswering = isAIConversationAnswering(status);
const wasAnswering = useRef(false);
useEffect(() => {
if (wasAnswering.current && !isAnswering) onReplied();
wasAnswering.current = isAnswering;
}, [isAnswering, onReplied]);
const [voice, setVoice] = useState<VoiceSession>();
const [failure, setFailure] = useState<string>();
// Off the call when the conversation closes mid-call, such as when the user
// opens another one. Leaving twice does nothing.
useEffect(() => {
if (!voice) return;
return () => {
void voice.leave().catch(() => undefined);
void voice.session.voice.stop().catch(() => undefined);
};
}, [voice]);
if (voice) {
return (
<AgentVoice
conversation={conversation}
onHangUp={() => setVoice(undefined)}
voice={voice}
/>
);
}
// From the Talk button's click, since the browser plays audio and asks for
// the microphone only after one.
const talk = () => {
setFailure(undefined);
startVoice(chat).then(setVoice, (error: unknown) =>
setFailure(error instanceof Error ? error.message : String(error)),
);
};
return (
<main className="assistant-conversation">
<AIConversation
className="assistant-messages"
conversation={conversation}
/>
<div className="assistant-composer">
{failure && <p role="alert">{failure}</p>}
<AIMessageComposer conversation={conversation}>
<AIMessageComposer.TextInput placeholder="Ask anything" />
<AIMessageComposer.Actions>
<Button
appearance="outline"
onClick={talk}
size="sm"
type="button"
variant="secondary"
>
Talk
</Button>
<AIMessageComposer.SubmitButton />
</AIMessageComposer.Actions>
</AIMessageComposer>
</div>
</main>
);
};Lay the page out as a row: the list in a fixed-width column, and the conversation in a column the height of the page, which the messages fill above the composer, since the conversation scrolls inside itself. The page renders inside an element with the str-chat class, the SDK's theme scope, so the AI components and the SDK's Button take the SDK's fonts, colors and spacing. The composer's form grows to fill a flex container it's placed in, so it sits in .assistant-composer, which takes only the height it needs. AIMessageComposer.Actions puts its buttons in a row of their own under the text, lined up at its end:
.assistant {
display: flex;
height: 100dvh;
}
.conversations {
display: flex;
flex: none;
flex-direction: column;
width: 260px;
overflow-y: auto;
}
.assistant-placeholder,
.assistant-conversation {
flex: 1;
min-width: 0;
}
.assistant-conversation {
display: flex;
flex-direction: column;
}
.conversations {
gap: 0.25rem;
padding: 0.75rem;
background: var(--str-chat__background-core-surface-subtle);
}
.conversations__search {
padding: 0.375rem 0.75rem;
border: 1px solid var(--str-chat__border-core-default);
border-radius: var(--str-chat__radius-max);
font: inherit;
}
.conversations__item {
padding: 0.5rem 0.75rem;
border: none;
border-radius: var(--str-chat__radius-md);
background: none;
color: var(--str-chat__text-primary);
font: inherit;
text-align: start;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
}
.conversations__item:hover {
background: var(--str-chat__background-utility-hover);
}
.conversations__item[aria-current="true"] {
background: var(--str-chat__background-utility-selected);
}
.assistant-placeholder {
align-self: center;
text-align: center;
color: var(--str-chat__text-secondary);
}
.assistant-composer {
padding: 0 1rem 1rem;
}
/* One centered column for the messages and the composer. */
.assistant-messages .str-chat__ai-conversation__turns,
.assistant-composer {
box-sizing: border-box;
width: 100%;
max-width: 48rem;
margin-inline: auto;
}The list sits on the SDK's subtle surface, with the open conversation marked, and the last rule keeps the messages and the composer in one centered column, so lines stay short enough to read on a wide window. The conversation still scrolls across the full width, so its scrollbar stays at the window's edge.
On a narrow window, show the list in a drawer the user opens from a menu button instead.
The reply shows the question of get_location under its call, and the Connect Gmail card when a Gmail call waits for the user. Not now calls session.declineLogin, so the call runs nothing and the agent is told the user didn't connect. Tool approvals and Tool sign-ins cover both cards.
Send photos
The composer above sends only the text. To send the photos the user attaches, add <AIMessageComposer.FileInput accept="image/*" name="attachments" /> to the composer, and have the transport read them as images for the model. A page has nowhere public to put a photo, so send each one inline, as a data URI, shrunk to a size the model needs:
import type { ImageSource } from "@stream-io/stream-agents";
export async function imageSource(file: File): Promise<ImageSource> {
const bitmap = await createImageBitmap(file);
const scale = Math.min(1, 1280 / Math.max(bitmap.width, bitmap.height));
const canvas = document.createElement("canvas");
canvas.width = Math.round(bitmap.width * scale);
canvas.height = Math.round(bitmap.height * scale);
canvas.getContext("2d")?.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
return { url: canvas.toDataURL("image/jpeg", 0.7) };
}In useAssistantConversation, give the transport images, and reasoningEffort for an option such as "Think harder", which chat options add to the composer:
transport: agentChatTransport(chat, {
adapt: (message, reasoningText) =>
fromStreamMessage(message, { reasoningText }),
// The files the user picked, in the browser.
images: (attachments) =>
Promise.all(
(attachments as File[])
.filter((file) => file.type.startsWith("image/"))
.map(imageSource),
),
reasoningEffort: (option) =>
option?.id === "think_harder" ? "high" : undefined,
}),Without images, the transport refuses a question with attachments. Pick a model that reads images in agent.yaml.
Talk instead of typing
The Talk button switches the open conversation to voice. startVoice puts the agent on a call with everything said so far, and what's said on the call is written into the same conversation, which AgentVoice shows under the agent's glow. Hang up leaves the call and takes the agent off it, and the conversation goes on in writing. The effect does the same when the conversation closes mid-call, as the Voice agent use case describes.
Next steps
- Voice agent: the call view in full.
- Sessions: listing, searching, forking and rewinding conversations.
- Tool calling & Dispatch: tools, approvals, timeouts and tools that return images.
- Generative UI: answers that are UI, such as a day plan with a form to change it.