# WebRTC transfer

Implement `RequestTransfer` and `AnswerTransferRequest` in your WebRTC client to handle call transfers. Configure destinations with the [Transfer tool](/docs/transfer-tool).

## How WebRTC transfer works

On a WebRTC Channel, `transfer_conversation` delegates the transfer to your application through LiveKit RPC. Your client receives the request, performs the transfer, and reports whether it succeeded.

<Mermaid chart={`sequenceDiagram
    participant Assistant
    participant Client as Your WebRTC Client
    participant Target as Transfer Destination

    Assistant->>Client: RequestTransfer RPC
    Client-->>Assistant: { acknowledged: true }
    Note over Assistant: Mutes caller input
    Note over Assistant: Waits up to 300 seconds
    Client->>Target: Perform transfer
    Target-->>Client: Transfer result
    Client->>Assistant: AnswerTransferRequest RPC
    Assistant-->>Client: { acknowledged: true }
    Note over Assistant: Resumes or disconnects`} />

<br />

### Assistant behaviour

| Phase             | Assistant Behaviour                                               |
| ----------------- | ----------------------------------------------------------------- |
| Request sent      | Disables user audio input while awaiting the answer                      |
| Waiting           | Waits up to 300 seconds for `AnswerTransferRequest`        |
| Transfer accepted | Ends the Reecall conversation and disconnects the Assistant, leaving the room available to your application      |
| Transfer rejected | Re-enables audio, informs user of failure, continues conversation |
| No answer or client disconnect | Shuts down the Assistant session |

***

## RPC interface reference

The transfer protocol uses two RPC methods with JSON payloads.

### `RequestTransfer` (Assistant → client)

The Assistant initiates a transfer by calling the `RequestTransfer` RPC method on your client.

**Payload:**

```json
{
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "destination": "+33612345678",
  "reason": "Customer requested to speak with billing department",
  "conversationSummary": "Customer inquired about invoice #12345..."
}
```

| Field                 | Type   | Required | Description                                                                 |
| --------------------- | ------ | -------- | --------------------------------------------------------------------------- |
| `requestId`           | string | Yes      | Unique identifier for this transfer request. Use it when sending the answer |
| `destination`         | string | Yes      | Transfer target (phone number, extension, queue name, or custom identifier) |
| `reason`              | string | No       | Why the Assistant initiated the transfer                                    |
| `conversationSummary` | string | No       | AI-generated summary of the conversation up to this point                   |

The payload contains an optional summary, not the full message history.

**Expected response:**

```json
{
  "acknowledged": true
}
```

***

### `AnswerTransferRequest` (client → Assistant)

After performing the transfer, your client calls the `AnswerTransferRequest` RPC method to report the outcome to the Assistant.

**Payload:**

Accept:

```json
{
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "accepted": true
}
```

Refuse:

```json
{
  "requestId": "550e8400-e29b-41d4-a716-446655440000",
  "accepted": false,
  "reason": "No human agent was available."
}
```

| Field       | Type    | Required | Description                                                              |
| ----------- | ------- | -------- | ------------------------------------------------------------------------ |
| `requestId` | string  | Yes      | Must match the `requestId` from the original `RequestTransfer` call      |
| `accepted`  | boolean | Yes      | `true` if transfer succeeded, `false` if it failed                       |
| `reason`    | string  | No       | Explanation when `accepted` is `false`. Used to inform the user politely |

**Response from Assistant:**

```json
{
  "acknowledged": true
}
```

The Assistant acknowledges receipt and proceeds based on the `accepted` value:

* **`accepted: true`** - Ends the Reecall conversation and disconnects the Assistant without deleting the LiveKit room
* **`accepted: false`** - Resumes the conversation, informs the user using the `reason` field

***

## Step 1: register the RequestTransfer handler

Use a connected LiveKit `Room` for these examples. Call `setupTransferHandler` or `setup_transfer_handler` to register the handler in your client. The handler acknowledges the request immediately and starts the transfer in the background. See [LiveKit's RPC reference](https://docs.livekit.io/transport/data/rpc/) for SDK method signatures.

```typescript
import { Room, RpcInvocationData } from 'livekit-client';

interface TransferRequest {
  requestId: string;
  destination: string;
  reason?: string;
  conversationSummary?: string;
}

function setupTransferHandler(room: Room) {
  room.localParticipant.registerRpcMethod(
    'RequestTransfer',
    async (data: RpcInvocationData): Promise<string> => {
      const request: TransferRequest = JSON.parse(data.payload);
      
      console.log('Transfer requested:', {
        requestId: request.requestId,
        destination: request.destination,
        reason: request.reason,
      });

      // Process transfer asynchronously
      handleTransferRequest(room, request);

      // Return immediately to acknowledge receipt
      return JSON.stringify({ acknowledged: true });
    }
  );
}
```
```python
import asyncio
import json
from livekit import rtc
from dataclasses import dataclass
from typing import Optional

@dataclass
class TransferRequest:
    request_id: str
    destination: str
    reason: Optional[str] = None
    conversation_summary: Optional[str] = None

def setup_transfer_handler(room: rtc.Room):
    @room.local_participant.register_rpc_method("RequestTransfer")
    async def on_transfer_request(data: rtc.RpcInvocationData) -> str:
        payload = json.loads(data.payload)
        request = TransferRequest(
            request_id=payload["requestId"],
            destination=payload["destination"],
            reason=payload.get("reason"),
            conversation_summary=payload.get("conversationSummary"),
        )

        print(f"Transfer requested: {request.request_id} -> {request.destination}")

        # Process transfer asynchronously
        asyncio.create_task(handle_transfer_request(room, request))

        # Return immediately to acknowledge receipt
        return json.dumps({"acknowledged": True})
```
```go
package main

import (
 "encoding/json"
 "fmt"
 "github.com/livekit/server-sdk-go/v2"
)

type TransferRequest struct {
 RequestID           string              `json:"requestId"`
 Destination         string              `json:"destination"`
 Reason              string              `json:"reason,omitempty"`
 ConversationSummary string              `json:"conversationSummary,omitempty"`
}

func setupTransferHandler(room *lksdk.Room) {
 room.RegisterRpcMethod("RequestTransfer",
  func(data lksdk.RpcInvocationData) (string, error) {
   var request TransferRequest
   if err := json.Unmarshal([]byte(data.Payload), &request); err != nil {
    return "", err
   }

   fmt.Printf("Transfer requested: %s -> %s\n", request.RequestID, request.Destination)

   // Process transfer asynchronously
   go handleTransferRequest(room, request)

   // Return immediately to acknowledge receipt
   ack, _ := json.Marshal(map[string]bool{"acknowledged": true})
   return string(ack), nil
  })
}
```

:::info{title="Note"}

The initial `RequestTransfer` RPC must return within 5 seconds. After that acknowledgement, the Assistant waits up to 300 seconds for `AnswerTransferRequest`. It mutes caller input during the wait; provide hold audio in your application if needed. If the client disconnects or the answer times out, the Assistant shuts down.

:::

***

## Step 2: perform the transfer

Implement `executeTransfer` or `execute_transfer` with your application's transfer logic. The examples below call that function and report its outcome to the Assistant.

```typescript
async function handleTransferRequest(room: Room, request: TransferRequest) {
  try {
    // Your transfer logic here
    const success = await executeTransfer(request);

    if (success) {
      await sendTransferAnswer(room, request.requestId, true);
    } else {
      await sendTransferAnswer(room, request.requestId, false, 'Transfer failed');
    }
  } catch (error) {
    await sendTransferAnswer(room, request.requestId, false,
      error instanceof Error ? error.message : String(error));
  }
}
```
```python
async def handle_transfer_request(room: rtc.Room, request: TransferRequest):
    try:
        # Your transfer logic here
        success = await execute_transfer(request)

        if success:
            await send_transfer_answer(room, request.request_id, True)
        else:
            await send_transfer_answer(room, request.request_id, False, "Transfer failed")
    except Exception as e:
        await send_transfer_answer(room, request.request_id, False, str(e))
```
```go
func handleTransferRequest(room *lksdk.Room, request TransferRequest) {
	// Your transfer logic here
	success, err := executeTransfer(request)

	if err != nil {
		sendTransferAnswer(room, request.RequestID, false, err.Error())
		return
	}

	if success {
		sendTransferAnswer(room, request.RequestID, true, "")
	} else {
		sendTransferAnswer(room, request.RequestID, false, "Transfer failed")
	}
}
```

Your transfer function can:

* Initiate an outbound call through a telephony provider.
* Route the request to another service in your infrastructure.
* Add the conversation to a queue for human agents.

***

## Step 3: report the transfer outcome

After the transfer attempt, send the result back to the Assistant using the `AnswerTransferRequest` RPC method.

```typescript
async function sendTransferAnswer(
  room: Room,
  requestId: string,
  accepted: boolean,
  reason?: string
): Promise<void> {
  const agentParticipant = Array.from(room.remoteParticipants.values())
    .find(p => p.isAgent);

  if (!agentParticipant) {
    console.error('Agent participant not found');
    return;
  }

  const payload = JSON.stringify({
    requestId,
    accepted,
    reason: reason ?? null,
  });

  try {
    const response = await room.localParticipant.performRpc({
      destinationIdentity: agentParticipant.identity,
      method: 'AnswerTransferRequest',
      payload,
    });
    
    console.log('Transfer answer acknowledged:', response);
  } catch (error) {
    console.error('Failed to send transfer answer:', error);
  }
}
```
```python
async def send_transfer_answer(
    room: rtc.Room,
    request_id: str,
    accepted: bool,
    reason: Optional[str] = None,
) -> None:
    # Find the agent participant
    agent_participant = None
    for participant in room.remote_participants.values():
        if participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_AGENT:
            agent_participant = participant
            break

    if not agent_participant:
        print("Agent participant not found")
        return

    payload = json.dumps({
        "requestId": request_id,
        "accepted": accepted,
        "reason": reason,
    })

    try:
        response = await room.local_participant.perform_rpc(
            destination_identity=agent_participant.identity,
            method="AnswerTransferRequest",
            payload=payload,
        )
        print(f"Transfer answer acknowledged: {response}")
    except Exception as e:
        print(f"Failed to send transfer answer: {e}")
```
```go
func sendTransferAnswer(room *lksdk.Room, requestID string, accepted bool, reason string) {
	// Find the agent participant
	var agentParticipant *lksdk.RemoteParticipant
	for _, p := range room.GetRemoteParticipants() {
		if p.Kind() == lksdk.ParticipantAgent {
			agentParticipant = p
			break
		}
	}

	if agentParticipant == nil {
		fmt.Println("Agent participant not found")
		return
	}

	payload, _ := json.Marshal(map[string]interface{}{
		"requestId": requestID,
		"accepted":  accepted,
		"reason":    reason,
	})

	response, err := room.LocalParticipant.PerformRpc(lksdk.PerformRpcParams{
		DestinationIdentity: agentParticipant.Identity(),
		Method:              "AnswerTransferRequest",
		Payload:             string(payload),
	})

	if err != nil {
		fmt.Printf("Failed to send transfer answer: %v\n", err)
		return
	}

	fmt.Printf("Transfer answer acknowledged: %s\n", response)
}
```

:::info{title="Note"}

When the transfer is rejected, the Assistant explains the failure in non-technical terms based on your `reason` field, then asks if it can help with anything else.

:::
