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.

Note:

What you'll build

  • A support agent that answers from your help center and stays on topic
  • Order lookups and refunds on your backend, with a question to the user on the phone before a refund
  • A ticket for your team when the agent can't help
  • A help screen that carries on the user's latest support conversation, with ratings and a button that calls support

Starts from: the Quickstart, with agents, AgentMessage, AgentTransport and agentConversation in your project. The screens' icons need implementation("androidx.compose.material:material-icons-extended:1.7.8").

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 on the phone 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 text

Its instructions say what it's for:

agents/support/instructions.md
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:

agents/support/knowledge/urls.yaml
- https://help.acme.com/shipping
- https://help.acme.com/returns
agents/support/guardrail.md
---
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 --sync

Knowledge & 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. Each call knows the user it's for, so a user only finds their own orders:

worker.ts
import { Client } from "@stream-io/stream-agents";
import { z } from "zod";

const client = new Client();
const order = z.object({ order_id: z.string() });

client.tools.register({
  name: "lookup_order",
  description: "Look up one of the customer's orders",
  parameters: order,
  run: ({ order_id }, { user }) => orders.find(order_id, user.id),
});

client.tools.register({
  name: "open_ticket",
  description: "Hand the conversation over to the support team",
  parameters: z.object({ summary: z.string() }),
  run: ({ summary }, { user }) => helpdesk.open(user.id, summary),
});

await client.runDispatch();

orders and helpdesk stand for your own systems. Tool calling & Dispatch shows the same worker in other languages.

The agent is offered them once its agent.yaml names them in a tool group. Add one, and sync the agent again:

agents/support/agent.yaml
tools:
  - name: support
    tools: [lookup_order, open_ticket]
    loading: full

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 app gives the session. The conversation 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 io.getstream.agents.android.core.AgentTool
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonPrimitive

val issueRefund: AgentTool = AgentTool(
    name = "issue_refund",
    description = "Refund one of the customer's orders",
    parameters = AgentTool.strings(
        mapOf(
            "order_id" to "the order to refund",
            "summary" to "the order and the amount, such as Order 1042, $39.90",
        ),
        required = listOf("order_id", "summary"),
    ),
    displayTitle = "Refunding your order",
    approval = AgentTool.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",
    ),
) { arguments ->
    val orderId = arguments["order_id"]?.jsonPrimitive?.contentOrNull ?: error("No order to refund.")
    yourBackend.refund(orderId)
    "Refunded order $orderId."
}

yourBackend.refund stands for a call to 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.

Open the user's support conversation

Carry on the user's latest support session, so the agent has the history, or start one. Pass issueRefund either way, since the session runs it only while the app holds it:

import io.getstream.agents.android.core.AgentSession
import io.getstream.agents.android.core.SessionOptions

suspend fun openSupport(): AgentSession {
    val support = agents.agent("support")
    val latest = support.sessions.query(limit = 1).items.firstOrNull()
    // An incognito session keeps no written conversation.
    if (latest != null && latest.conversationId.isNotEmpty()) {
        return agents.attach(latest.id, listOf(issueRefund))
    }
    return support.sessions.create(SessionOptions(tools = listOf(issueRefund)))
}

Build the support screen

The support screen is the quickstart's conversation with common questions while it's empty, and a button that calls support. Open its conversation the way the quickstart's AssistantViewModel does, with openSupport() in place of agents.agent("my-agent").sessions.create():

class SupportViewModel(application: Application) : AndroidViewModel(application) {
    private val _conversation = MutableStateFlow<AIConversationState<AgentMessage>?>(null)
    val conversation: StateFlow<AIConversationState<AgentMessage>?> = _conversation.asStateFlow()

    // Why the session didn't open, as in the quickstart's AssistantViewModel.
    private val _failure = MutableStateFlow<AgentsException?>(null)
    val failure: StateFlow<AgentsException?> = _failure.asStateFlow()

    init {
        viewModelScope.launch {
            try {
                _conversation.value = agentConversation(application, openSupport(), viewModelScope)
            } catch (e: AgentsException) {
                _failure.value = e
            }
        }
    }
}

Under each answer, the conversation offers to copy, share and rate it. The screen puts it together:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import io.getstream.chat.android.ai.compose.conversation.AIConversationState
import io.getstream.chat.android.ai.compose.ui.component.AIConversation
import io.getstream.chat.android.ai.compose.ui.component.AISuggestions
import io.getstream.chat.android.ai.compose.ui.component.ChatComposer

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SupportScreen(viewModel: SupportViewModel = viewModel()) {
    val conversation by viewModel.conversation.collectAsStateWithLifecycle()
    var isCalling by remember { mutableStateOf(false) }

    if (isCalling) {
        VoiceAgentScreen(agent = "support", onClose = { isCalling = false })
        return
    }
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Help") },
                actions = {
                    IconButton(onClick = { isCalling = true }) {
                        Icon(Icons.Default.Phone, contentDescription = "Call support")
                    }
                },
            )
        },
    ) { padding ->
        val current = conversation
        if (current == null) {
            Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        } else {
            SupportConversation(current, Modifier.padding(padding))
        }
    }
}

@Composable
fun SupportConversation(conversation: AIConversationState<AgentMessage>, modifier: Modifier = Modifier) {
    Column(modifier) {
        AIConversation(
            state = conversation,
            modifier = Modifier.weight(1f),
            emptyContent = {
                AISuggestions(
                    suggestions = listOf("Where is my order?", "I want to return an item", "Talk to a person"),
                    onSuggestionClick = { conversation.send(it) },
                )
            },
        )
        ChatComposer(state = conversation)
    }
}

VoiceAgentScreen is the call screen of the Voice agent use case, and talks to the same agent, with the same knowledge and the tools your worker hosts. The call is a session of its own, and VoiceAgentScreen gives it none of the app's tools, so issueRefund isn't offered on the call.

Everything else comes from the agent and the tools above:

  • Order lookups show in the reply as the agent makes them, so the user sees what it checked.
  • A refund shows "Refund this order?" under its call, with the order and amount and buttons to allow or decline it. The approver from the quickstart's agentConversation answers it. Declined, the refund never runs, and the agent is told so.
  • 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.

Send ratings to your backend

The conversation keeps the ratings on the device unless you send them. Add rate to the quickstart's AgentTransport, and the conversation calls it each time the user rates a reply:

override suspend fun rate(reply: AgentMessage, rating: AIMessageRating?) {
    yourBackend.rate(sessionId = session.id, messageId = reply.id, rating = rating)
}

rating is AIMessageRating.Positive, AIMessageRating.Negative, or null when the user takes their rating back. If rate throws, the reply goes back to the rating it had. The router also reviews and scores each session once it ends, which Sessions describes.

Next steps