# AI Bot to Human Handoff

An AI bot can answer a customer first and hand the same conversation to a person when it needs one. With Stream Chat, both happen in one channel: the customer and the bot talk there, someone from your support team joins it later, and they read everything that was said before they joined. Nothing is copied to a second inbox, and the customer stays in the same chat.

## I want an AI support bot to answer first, then hand the same conversation over to a human when needed. What should I use?

Use one Stream Chat channel per conversation, and keep who owns it in the channel's custom data:

1. Your backend creates an [`agent` channel](https://getstream.io/chat/docs/java/channel-features/#the-agent-channel-type) with the customer and your bot as members, and sets `handoff` to `bot`.
2. The bot answers each new message while `handoff` is `bot`.
3. When the conversation needs a person, the bot or your backend sets `handoff` to `waiting`, and the bot stops answering.
4. Your support agents' inbox lists the channels where `handoff` is `waiting`.
5. An agent takes one: your backend adds the agent as a member, removes the bot and sets `handoff` to `human`. The agent sees the full history, the bot's answers included.

```mermaid
sequenceDiagram
    participant C as Customer
    participant B as AI bot
    participant S as Your backend
    participant A as Support agent
    C->>B: Asks a question
    B->>C: Answers (handoff: bot)
    C->>B: Asks for a person
    B->>S: Hands off (handoff: waiting)
    A->>S: Takes the conversation
    S->>A: Adds the agent, removes the bot (handoff: human)
    A->>C: Replies in the same channel
```

The bot can be one you run yourself, as the sections below show, or one built with the [Stream Chat AI SDK](#with-the-stream-chat-ai-sdk).

## Start the conversation

Create the channel from your backend when the customer opens the support chat. `handoff` is a custom field: name it and its values as you like. This page uses `bot`, `waiting` and `human`.

```java label="Java"
chat.getOrCreateChannel("agent", "support-anya-1", GetOrCreateChannelRequest.builder()
    .data(ChannelInput.builder()
        .createdByID("anya")
        .members(List.of(
            ChannelMemberRequest.builder().userID("anya").build(),
            ChannelMemberRequest.builder().userID("support-bot").build()))
        .custom(Map.of("handoff", "bot"))
        .build())
    .build()).execute();
```

## Let the bot answer only while it owns the conversation

Your backend gets each new message from the [`message.new` webhook](https://getstream.io/chat/docs/java/webhook-events/#messagenew), including the messages the bot sends, so skip those first. The webhook carries the message but not the channel's custom data, so read `handoff` before the bot answers. [AI Message Streaming](https://getstream.io/chat/docs/java/ai-message-streaming/) shows how to post the answer as the bot.

```java label="Java"
// channelType and channelId come from the message.new webhook
var current = chat.getChannel(channelType, channelId,
    GetChannelRequest.builder().State(false).build()).execute();
if ("bot".equals(current.getData().getChannel().getCustom().get("handoff"))) {
  // Ask your LLM, then post its answer as the bot
}
```

## Hand the conversation to a person

Decide in your backend when a person should take over. Common reasons:

- The customer asks for a person, by tapping a "Talk to a person" button that calls your backend, or in their own words.
- The bot can't solve the problem, for example after two answers that didn't help.
- The conversation is sensitive, such as a refund dispute or a cancellation, or the customer is on a plan with priority support.

To let the LLM decide, give it a tool such as `hand_off_to_human` and run this code when it calls the tool. It sets `handoff` to `waiting`, which stops the bot at the check above, and tells the customer what happens next:

```java label="Java"
chat.updateChannelPartial("agent", "support-anya-1", UpdateChannelPartialRequest.builder()
    .set(Map.of("handoff", "waiting", "handoff_reason", "Customer asked for a person"))
    .build()).execute();
chat.sendMessage("agent", "support-anya-1", SendMessageRequest.builder()
    .message(MessageRequest.builder()
        .text("I'm connecting you with someone from our team.")
        .userID("support-bot")
        .build())
    .build()).execute();
```

The partial update changes only the fields you set. Every member's app gets a `channel.updated` event, so your UI can show that a person is on the way.

## Show waiting conversations to your agents

Custom fields work in [query filters](https://getstream.io/chat/docs/java/query-channels/), so one query lists the conversations waiting for a person, the longest wait first:

```java label="Java"
var response = chat.queryChannels(QueryChannelsRequest.builder()
    .filterConditions(Map.of("type", "agent", "handoff", "waiting"))
    .sort(List.of(SortParamRequest.builder().field("updated_at").direction(1).build()))
    .limit(30)
    .build()).execute();
```

Keep anything else your inbox needs, such as `handoff_reason` or a priority, in the same custom data, and filter or sort on it the same way.

## Let an agent take over

When an agent picks a conversation, add them as a member and remove the bot in one update. The update can also post a message, which members see as a system message. Then set `handoff` to `human`:

```java label="Java"
chat.updateChannel("agent", "support-anya-1", UpdateChannelRequest.builder()
    .addMembers(List.of(ChannelMemberRequest.builder().userID("maria").build()))
    .removeMembers(List.of("support-bot"))
    .message(MessageRequest.builder().text("Maria joined the conversation.").userID("maria").build())
    .build()).execute();
chat.updateChannelPartial("agent", "support-anya-1", UpdateChannelPartialRequest.builder()
    .set(Map.of(
        "handoff", "human",
        "assignee_id", "maria",
        "config_overrides", Map.of("typing_events", true)))
    .build()).execute();
```

- **The agent sees the whole conversation.** A member added later reads the full channel history, the bot's answers included, unless you [hide it](https://getstream.io/chat/docs/java/channel-members/#hide-history).
- **Typing indicators turn on.** The `agent` channel type has them off, since a bot doesn't type. `config_overrides` turns them on for this channel now that two people talk in it.
- **Only one agent takes it.** If two agents can pick the same conversation at once, assign it in your own database first, or read `handoff` and go ahead only while it is still `waiting`.

To give the conversation back to the bot, add the bot again and set `handoff` back to `bot`.

## With the Stream Chat AI SDK

The [Stream Chat AI SDK](https://getstream.io/chat/docs/sdk/react/ai-components/stream-chat-ai-sdk/) (`@stream-io/chat-ai-sdk`) runs the bot for you in Node.js: `AgentManager.startAgent` adds a bot user to the channel and answers its messages with the LLM you pick. Two additions give it the handoff:

- A server tool the LLM calls to hand off, which sets `handoff` to `waiting`.
- A `userMessageHandler` that keeps the bot quiet once `handoff` isn't `bot`. Returning `true` skips the LLM for that message.

```ts title="support-bot.ts"
import {
  AgentManager,
  AgentPlatform,
  type AgentTool,
} from "@stream-io/chat-ai-sdk";
import { z } from "zod";

declare module "stream-chat" {
  interface CustomChannelData {
    handoff?: "bot" | "waiting" | "human";
    handoff_reason?: string;
  }
}

const handOffToHuman: AgentTool = {
  name: "handOffToHuman",
  description: "Hand the conversation to a person from the support team.",
  instructions:
    "Call this when the customer asks for a person, or when you can't solve their problem.",
  parameters: z.object({
    reason: z.string().describe("Why the conversation needs a person"),
  }),
  async execute(args, { channel }) {
    const { reason } = args as { reason: string };
    await channel.updatePartial({
      set: { handoff: "waiting", handoff_reason: reason },
    });
    return "Tell the customer that someone from the team will join this conversation.";
  },
};

const botIdFor = (channelId: string) => `support-bot-${channelId}`;

const manager = new AgentManager({
  serverToolsFactory: () => [handOffToHuman],
  agentIdResolver: botIdFor,
  // The bot stays quiet once the conversation isn't its own.
  userMessageHandler: ({ channel }) =>
    (channel.data?.handoff ?? "bot") !== "bot",
});

await manager.startAgent({
  userId: botIdFor("support-anya-1"),
  channelId: "support-anya-1",
  channelType: "agent",
  platform: AgentPlatform.OPENAI,
  instructions:
    "You are the first line of support. Hand off to a person when needed.",
});
```

When an agent takes the conversation, call `manager.stopAgent(botIdFor("support-anya-1"))` instead of removing the bot yourself: it disconnects the bot and removes it from the channel. Then add the agent and set `handoff` to `human` as shown above.

## Going further

- [The `agent` channel type](https://getstream.io/chat/docs/java/channel-features/#the-agent-channel-type): the defaults for conversations with an AI bot.
- [AI Message Streaming](https://getstream.io/chat/docs/java/ai-message-streaming/): stream the bot's answer into a message as the LLM writes it.
- [Channel Members](https://getstream.io/chat/docs/java/channel-members/): add, remove and hide history for members.
- [Webhook Events](https://getstream.io/chat/docs/java/webhook-events/): every event your backend can receive.

---

For the most recent version of this documentation, visit [https://getstream.io/chat/docs/java/ai-human-handoff/](https://getstream.io/chat/docs/java/ai-human-handoff/).