_# brilo/functions/standard/call_transfer.py_
import logging
from livekit
import api
import asyncio
import json
import os
from livekit.protocol.sip
import (
TransferSIPParticipantRequest,
ListSIPOutboundTrunkRequest,
CreateSIPOutboundTrunkRequest,
SIPOutboundTrunkInfo,
)
from brilo.functions.context
import ToolState
from livekit.agents
import RunContext
from typing
import Dict, Any
from brilo.utils.function_utils
import get_fn_data_from_ctx
logger = logging.getLogger(
name)
async def get_outbound_trunk_id_from_number(_livekit_api_, _phone_number_):
response =
await livekit_api.sip.list_sip_outbound_trunk(
ListSIPOutboundTrunkRequest()
)
for trunk_info
in response.items:
if phone_number in trunk_info.numbers:
logger.info(
f"Found SIP outbound Trunk ID for {phone_number}: {trunk_info.sip_trunk_id}"
)
return trunk_info.sip_trunk_id
logger.info(f"No outbound SIP trunk found for number: {phone_number}")
logger.info(f"Creating new outbound trunk for {phone_number}")
# Create a new SIP outbound Trunk
create_req = CreateSIPOutboundTrunkRequest(
trunk=SIPOutboundTrunkInfo(
name=f"Trunk for {phone_number}",
numbers=[phone_number],
_krisp_enabled_=True,
metadata="{}",
),
)
new_trunk =
await livekit_api.sip.create_sip_outbound_trunk(create_req)
logger.info(
f"Created new outbound trunk {new_trunk.sip_trunk_id} for {phone_number}"
)
return new_trunk.sip_trunk_id
async def call_transfer(_context_: RunContext[ToolState]) -> Dict[str, Any]:
"""
Transfers the call to the configured phone number using LiveKit's SIP transfer API.
Args:
context: The RunContext containing the tool state
Returns:
Dict containing the result of the operation
"""
# Get function metadata from shared context
function_data = get_fn_data_from_ctx(context)
if not function_data:
return "Function configuration not found."
user_data = context.userdata
participant = user_data.participant
ctx = user_data.call_ctx
call_sid = participant.attributes.get("sip.twilio.callSid")
config = function_data.get("config", {})
config = json.loads(config)
transfer_to_phone = config.get("phone_number")
transfer_type = config.get("transfer_type")
transfer_message = config.get("transfer_prompt")
warm_transfer_message = config.get("warm_transfer_prompt")
# Get participant identity and room name
participant_identity = participant.identity
room_name = ctx.room.name
# Get room name from the context instead of participant
if not transfer_to_phone:
logger.error("No transfer_to_phone configured for call_transfer.")
return "Transfer number not configured."
_try_:
session = context.session
# Format the phone number (ensure it has + prefix and tel: protocol)
if not transfer_to_phone.startswith("+"):
transfer_to_phone = f"+{transfer_to_phone.lstrip('+')}"
# Add tel: protocol if not present
if not transfer_to_phone.startswith("tel:"):
transfer_to_phone = f"tel:{transfer_to_phone}"
# Inform the caller about the transfer
await session.say(transfer_message, _add_to_chat_ctx_=True)
# Initialize LiveKit API
_# livekit_api = api.LiveKitAPI(_
_# url=os.getenv("LIVEKIT_URL"),_
_# api_key=os.getenv("LIVEKIT_API_KEY"),_
_# api_secret=os.getenv("LIVEKIT_API_SECRET"),_
# )
livekit_api = user_data.lkapi
if transfer_type == "cold":
# Create transfer request
transfer_request = TransferSIPParticipantRequest(
_participant_identity_=participant_identity,
_room_name_=room_name,
_transfer_to_=transfer_to_phone,
_play_dialtone_=True,
)
logger.debug(f"Cold Transfer request: {transfer_request}")
# Transfer caller
await livekit_api.sip.transfer_sip_participant(transfer_request)
logger.info(
f"Successfully transferred participant {participant_identity} to {transfer_to_phone} (cold transfer)"
)
return transfer_message
elif transfer_type in ["warm_message", "warm_summary"]:
# Warm transfer - add agent to current room
sip_trunk_id =
await get_outbound_trunk_id_from_number(
livekit_api, transfer_to_phone.replace("tel:", "")
)
# Create SIP participant request to add human agent to room
create_request = api.CreateSIPParticipantRequest(
_sip_trunk_id_=sip_trunk_id,
_sip_call_to_=transfer_to_phone,
_room_name_=room_name,
_participant_identity_=participant_identity,
_krisp_enabled_=True,
)
logger.debug(f"Warm transfer request: {create_request}")
# Add human agent to the room
await livekit_api.sip.create_sip_participant(create_request)
logger.info(
f"Successfully added new agent to room {room_name} ({transfer_type})"
)
# Wait a moment for the agent to connect
await asyncio.sleep(2)
await session.say(warm_transfer_message, _add_to_chat_ctx_=True)
logger.info(
f"Successfully transferred participant {participant_identity} to {transfer_to_phone} (warm transfer)"
)
return transfer_message
except Exception
as e:
error_msg = f"Failed to transfer call: {e}"
logger.error(error_msg)
return error_msg
After transferring call, why it dropped the participant ?
2025-08-28 22
0341,514 - brilo.functions.standard.call_transfer - INFO - Found SIP outbound Trunk ID for
+12344043854: ST_ti2gSFqVG43R
2025-08-28 22
0341,515 - brilo.functions.standard.call_transfer - DEBUG - Warm transfer request: sip_trunk_id: "ST_ti2gSFqVG43R"
sip_call_to: "tel:+12344043854"
room_name: "call_+12342175178_58LXnvTSViv9"
participant_identity: "sip_+12342175178"
krisp_enabled: true
2025-08-28 22
0341,514 - brilo.functions.standard.call_transfer - INFO - Found SIP outbound Trunk ID for
+12344043854: ST_ti2gSFqVG43R
{"message": "Found SIP outbound Trunk ID for
+12344043854: ST_ti2gSFqVG43R", "level": "INFO", "name": "brilo.functions.standard.call_transfer", "pid": 30480, "job_id": "AJ_8FULfciMstQG", "timestamp": "2025-08-28T16
3341.514541+00:00"}
2025-08-28 22
0342,197 - livekit-utils - INFO - Participant disconnected: sip_+12342175178
2025-08-28 22
0342,197 - livekit-utils - INFO - Participant disconnected: sip_+12342175178
{"message": "Participant disconnected: sip_+12342175178", "level": "INFO", "name": "livekit-utils", "pid": 30480, "job_id": "AJ_8FULfciMstQG", "timestamp": "2025-08-28T16
3342.197529+00:00"}
2025-08-28 22
0342,200 - livekit.agents - DEBUG - stream closed
2025-08-28 22
0342,207 - brilo.functions.standard.call_transfer - INFO - Successfully added new agent to room call_+12342175178_58LXnvTSViv9 (warm_message)
2025-08-28 22
0342,207 - brilo.functions.standard.call_transfer - INFO - Successfully added new agent to room call_+12342175178_58LXnvTSViv9 (warm_message)
{"message": "Successfully added new agent to room call_+12342175178_58LXnvTSViv9 (warm_message)", "level": "INFO", "name": "brilo.functions.standard.call_transfer", "pid": 30480, "job_id": "AJ_8FULfciMstQG", "timestamp": "2025-08-28T16
3342.207145+00:00"}