# 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/php/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`.

```php label="PHP"
use GetStream\GeneratedModels as Models;

$client->getOrCreateChannel('agent', 'support-anya-1', new Models\ChannelGetOrCreateRequest(
    data: new Models\ChannelInput(
        createdByID: 'anya',
        members: [
            new Models\ChannelMemberRequest(userID: 'anya'),
            new Models\ChannelMemberRequest(userID: 'support-bot'),
        ],
        custom: (object) ['handoff' => 'bot'],
    ),
));
```

## 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/php/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/php/ai-message-streaming/) shows how to post the answer as the bot.

```php label="PHP"
// $channelType and $channelId come from the message.new webhook
$channel = $client->getChannel($channelType, $channelId, state: false)->getData()->channel;
if (($channel->custom->handoff ?? null) === 'bot') {
    // 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:

```php label="PHP"
$client->updateChannelPartial('agent', 'support-anya-1', new Models\UpdateChannelPartialRequest(
    set: (object) ['handoff' => 'waiting', 'handoff_reason' => 'Customer asked for a person'],
));
$client->sendMessage('agent', 'support-anya-1', new Models\SendMessageRequest(
    message: new Models\MessageRequest(text: "I'm connecting you with someone from our team.", userID: 'support-bot'),
));
```

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/php/query-channels/), so one query lists the conversations waiting for a person, the longest wait first:

```php label="PHP"
$response = $client->queryChannels(new Models\QueryChannelsRequest(
    filterConditions: (object) ['type' => 'agent', 'handoff' => 'waiting'],
    sort: [new Models\SortParamRequest(field: 'updated_at', direction: 1)],
    limit: 30,
));
```

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`:

```php label="PHP"
$client->updateChannel('agent', 'support-anya-1', new Models\UpdateChannelRequest(
    addMembers: [new Models\ChannelMemberRequest(userID: 'maria')],
    removeMembers: ['support-bot'],
    message: new Models\MessageRequest(text: 'Maria joined the conversation.', userID: 'maria'),
));
$client->updateChannelPartial('agent', 'support-anya-1', new Models\UpdateChannelPartialRequest(
    set: (object) [
        'handoff' => 'human',
        'assignee_id' => 'maria',
        'config_overrides' => (object) ['typing_events' => true],
    ],
));
```

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

---

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