Customer support agent
A support agent answers the questions your support team answers every day, at any hour, and hands the rest over to your team.
What you'll build
- A support agent that answers from your help center and stays on topic
- Order lookups and tickets on your backend
- Refunds the user allows first, from a question in the reply
- A help page that carries on the user's latest support conversation, with ratings and a way to call support
Starts from: the Quickstart, with api, signIn and useAgentConversation in your project, and the VoiceAgent view of the Voice agent use case.
Best practices
- Give the agent your help center as knowledge, so it answers from what you published rather than from what the model guesses.
- Keep what reaches your systems, such as orders and refunds, on your backend. A tool in the browser only calls your API, which checks who is signed in.
- Ask before anything that can't be undone, such as a refund.
- Always offer a way to reach a person.
Define the support agent
Make the agent from the text template:
getstream agents init support --template textIts instructions say what it's for:
You are Acme's support assistant. Answer questions about Acme orders, shipping,
returns and billing, briefly.
- Look up an order before you answer a question about it.
- When you can't help, or the customer asks for a person, open a ticket.Its knowledge is your help center, and its guardrail turns away what isn't about Acme:
- https://help.acme.com/shipping
- https://help.acme.com/returns---
refusal: I can only help with questions about your Acme account and orders.
---
Answer questions about Acme orders, billing, shipping and returns. Refuse anything else.Sync it, and try it in the terminal:
getstream agents test support --syncKnowledge & Skills and Guardrails cover both in full.
Host its tools on your backend
The tools that reach your systems run on your backend, in a dispatch worker. The worker hosts them for your whole app, and an agent gets them once its agent.yaml names them in a tool group. Every session of the support agent can then use them, including the ones your users open from the browser. Each call knows the user it's for, so a user only finds their own orders:
import { Client, type ToolCallContext } from "@stream-io/stream-agents";
import { z } from "zod";
const client = new Client();
// The user whose turn made the call. It's empty when the router didn't say,
// so refuse those rather than look up orders for nobody in particular.
const customerOf = ({ user }: ToolCallContext) => {
if (!user.id) throw new Error("The call doesn't say who the customer is.");
return user.id;
};
client.tools.register({
name: "lookup_order",
description: "Look up one of the customer's orders",
parameters: z.object({ order_id: z.string() }),
run: ({ order_id }, toolCallContext) =>
orders.find(order_id, customerOf(toolCallContext)),
});
client.tools.register({
name: "open_ticket",
description: "Hand the conversation over to the support team",
parameters: z.object({ summary: z.string() }),
run: ({ summary }, toolCallContext) =>
helpdesk.open(customerOf(toolCallContext), summary),
});
await client.runDispatch();orders and helpdesk stand for your own systems. A call that doesn't name a user fails, and the model is told why, so nothing runs without a customer. The model is told a thrown error's message as it is, and an error from your own systems can name an internal host or table, so client.tools.setOnError((error, call) => ...) can return what the model is told instead. The worker runs with your API key and secret, so it never runs in the browser. Tool calling & Dispatch shows the same worker in other languages.
Name the tools in a tool group of the agent's agent.yaml, with the refund tool the page brings below, then sync it again. The router refuses a session that brings a tool no group names, and doesn't offer the agent a worker's tool that none names:
tools:
- name: support
tools: [lookup_order, open_ticket, issue_refund]
loading: fullYour first tool explains tool groups and loading.
Ask before a refund
A tool the worker hosts asks its question only on a voice call. A refund should ask in writing too, so it's a tool the page gives the session. The page asks the user, and once they allow it, the tool calls your backend, which checks the user and the order and issues the refund:
import { Tools } from "@stream-io/stream-agents";
import { z } from "zod";
export const tools = new Tools().register({
name: "issue_refund",
description: "Refund one of the customer's orders",
parameters: z.object({
order_id: z.string(),
summary: z
.string()
.describe("the order and the amount, such as Order 1042, $39.90"),
}),
displayTitle: "Refunding your order",
approval: {
title: "Refund this order?",
message: "The money goes back to the card the order was paid with.",
reasonArgument: "summary",
allowTitle: "Refund",
declineTitle: "Not now",
},
run: async ({ order_id }) => {
const response = await fetch("/api/refunds", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ order_id }),
});
if (!response.ok) throw new Error("The refund didn't go through.");
return `Refunded order ${order_id}.`;
},
});/api/refunds stands for your backend. The question shows the model's summary under its title, and a tool that throws tells the model what went wrong, so the agent can say so. new Tools({ onError }) changes what the model is told, as setOnError does in the worker.
Open the user's support conversation
Carry on the user's latest support conversation held in writing, so the agent has the history, or start one. A call from the support page is a session of its own, so the page opens its written conversations in a project of their own, support-chat, and finds the latest by it. Add it to support.ts:
import { api } from "./agent";
/** The project of the written conversations this page opens. Calls are left out. */
export const supportChatProject = "support-chat";
/** The user's latest support conversation held in writing, or undefined for a new one. */
export async function latestSupportSession(): Promise<string | undefined> {
// Newest first.
const { items } = await api.agent("support").sessions.query({
limit: 1,
filter: { project_id: supportChatProject },
});
return items[0]?.id;
}Then hold the conversation as the quickstart's useAgentConversation does, with the support agent and the refund tool. Pass the tools whether the session is new or carried on, since the session runs them only while the page holds it, and open a new one in the support-chat project, for the lookup to find. The conversation keeps rating replies and, as in the quickstart, leaves out editing and regenerating: leave actions out to offer them, and the router keeps the earlier versions as branches. The approver sends the user's answer to the refund's question back to the session:
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";
import { supportChatProject, tools } from "./support";
export function useSupportConversation(userId: string, sessionId?: string) {
const [state, setState] = useState<{
chat: AgentChat<LocalMessage>;
conversation: AIConversationController;
}>();
useEffect(() => {
const sessions = api.agent("support").sessions;
// The session opens when the user first asks, or carries on `sessionId`.
const chat = new AgentChat<LocalMessage>({
sessionId,
open: (id) =>
id
? sessions.resume(id, { tools })
: sessions.create({ tools, project_id: supportChatProject }),
});
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 }),
},
});
setState({ chat, conversation });
return () => {
conversation.dispose();
void chat.close();
};
}, [userId, sessionId]);
return state;
}Export the refund's tools from support.ts for it. A session opens only once the user asks something, so a page that renders twice, as in Strict Mode, doesn't start two sessions for a user who has none yet.
Build the support page
The support page is the quickstart's conversation, with common questions while it's empty and a way to call support. It looks up the latest conversation first, then shows it:
import { useEffect, useState } from "react";
import {
AIConversation,
AIMessageComposer,
AISuggestions,
} from "stream-chat-react/ai-components";
import { api } from "./agent";
import { latestSupportSession } from "./support";
import { useSupportConversation } from "./useSupportConversation";
// The call view of the Voice agent use case.
import { VoiceAgent } from "./VoiceAgent";
const starters = [
"Where is my order?",
"I want to return an item",
"Talk to a person",
];
/** `userId` is the signed-in user, as signIn() set them. */
export const SupportPage = ({ userId }: { userId: string }) => {
// Undefined until the lookup is done. A new conversation has no id.
const [latest, setLatest] = useState<{ sessionId?: string }>();
const [failure, setFailure] = useState<string>();
useEffect(() => {
latestSupportSession().then(
(sessionId) => setLatest({ sessionId }),
(error: unknown) =>
setFailure(error instanceof Error ? error.message : String(error)),
);
}, []);
if (failure) return <p role="alert">{failure}</p>;
return latest ? (
<SupportConversation sessionId={latest.sessionId} userId={userId} />
) : null;
};
const SupportConversation = (props: { userId: string; sessionId?: string }) => {
const agent = useSupportConversation(props.userId, props.sessionId);
if (!agent) return null;
const { conversation } = agent;
return (
// `str-chat` is the SDK's theme scope: its fonts, colors and spacing.
<div className="str-chat support">
<aside className="support-call">
<VoiceAgent agent="support" api={api} />
</aside>
<AIConversation
className="support-conversation"
conversation={conversation}
emptyContent={
<AISuggestions
onSelect={(text) => conversation.send({ text })}
suggestions={starters}
/>
}
/>
<div className="support-composer">
<AIMessageComposer conversation={conversation}>
<AIMessageComposer.TextInput placeholder="Ask about an order" />
<AIMessageComposer.Actions>
<AIMessageComposer.SubmitButton />
</AIMessageComposer.Actions>
</AIMessageComposer>
</div>
</div>
);
};The conversation shows a question the router refused, such as one sent while the agent still answers, as its error, with a way to retry. The page renders inside an element with the str-chat class, the SDK's theme scope. Inside it, the SDK's Button takes the SDK's fonts, colors and spacing, which it leaves unset outside it. The AI components bring that scope themselves, and use the page's instead of adding their own.
Lay the page out as a column the height of the page. The conversation scrolls inside itself, so it fills the space the call button and the composer leave. The composer's form grows to fill a flex container it's placed in, so it sits in .support-composer, which takes only the height it needs. AIMessageComposer.Actions puts the send button in a row of its own under the text, lined up at its end:
.support {
display: flex;
flex-direction: column;
height: 100dvh;
}
.support-call {
display: flex;
justify-content: flex-end;
padding: 0.75rem 1rem;
}
.support-composer {
padding: 0 1rem 1rem;
}
/* One centered column for the messages and the composer. */
.support-conversation .str-chat__ai-conversation__turns,
.support-composer {
box-sizing: border-box;
width: 100%;
max-width: 48rem;
margin-inline: auto;
}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.
VoiceAgent is the call view of the Voice agent use case: its button puts the user on a call with the same agent, with the same knowledge and the tools your worker hosts.
Everything else comes from the agent, with nothing more to add in the page:
- Order lookups answer from your systems, and find only the signed-in user's orders.
- A refund shows "Refund this order?" under its call, with the order and amount and buttons to allow or decline it. Declined, the refund never runs, and the agent is told so. Tool approvals covers the card.
- A handover opens a ticket with the agent's summary, so nobody asks the user to start again. The Slack connector lets your team follow along.
For a support assistant that floats over the rest of your app, the AI chat widget cookbook puts the conversation in a small window behind a chat bubble.
Send ratings to your backend
The conversation keeps the user's ratings in the page unless the transport sends them. In useSupportConversation, give the transport a rate that sends each one, with the session and the reply it's for:
const conversation = new AIConversationController({
transport: {
...agentChatTransport(chat, {
adapt: (message, reasoningText) =>
fromStreamMessage(message, { reasoningText }),
}),
rate: async (reply, rating) => {
await fetch("/api/ratings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sessionId: chat.id,
messageId: reply.id,
rating,
}),
});
},
},
// ...the actions and the approver, as above.
});rating is null when the user takes their rating back. Reply actions covers the buttons under each reply.
The router also reviews and scores each session once it ends, which Sessions describes.
Next steps
- Voice agent: the call view beside the support conversation.
- Purchase a phone number and Transfer to a person: the same agent on the phone.
- Tool calling & Dispatch: tools, approvals, timeouts and progress updates.