quick-cartoon-22764
11/20/2025, 9:20 PMtall-airline-16756
11/20/2025, 9:20 PMtall-airline-16756
11/20/2025, 9:20 PMtel:+1XXXXXXXXXX). This exits the caller from LiveKit and connects them to the Twilio number.
4. Ensure your Twilio trunk has SIP REFER / Call Transfer (PSTN Transfer) enabled so transfers are allowed.
If you’d like, tell me:
• the LiveKit SDK/language you use (JS, Python, etc.), and
• whether you want the transfer to be automatic on arrival or triggered by an agent,
and I’ll give the exact API/sample code and JSON for your setup.
Sources: Inbound calls with Twilio Voice | LiveKit docs | SIP trunk setup | LiveKit docs | Agents telephony integration | LiveKit Docs | Call forwarding | LiveKit docsquick-cartoon-22764
11/20/2025, 9:24 PMtall-airline-16756
11/20/2025, 9:25 PMtransfer_sip_participant to forward the caller to a Twilio number.
Prerequisites
• Inbound trunk configured in LiveKit and a dispatch rule that places each incoming call into a room.
• Twilio trunk has SIP REFER / Call Transfer enabled.
• Your agent process is authorized to call LiveKit server APIs and receives room/participant events.
Example (Python, async)
1. Listen for a participant joining the room (incoming caller).
2. Immediately invoke TransferSIPParticipant to transfer them to tel:+1TARGETNUMBER.
# async_transfer_on_join.py
import asyncio
from livekit import api, grpc
from livekit.api import TransferSIPParticipantRequest
LIVEKIT_API_KEY = "your_api_key"
LIVEKIT_API_SECRET = "your_api_secret"
LIVEKIT_BASE_URL = "https://your-livekit-host" # e.g., https://api.livekit.cloud or your self-hosted URL
TARGET_TWILIO_NUMBER = "tel:+15105550200"
# create LiveKit API client
client = api.LiveKitAPI(base_url=LIVEKIT_BASE_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
async def handle_participant_join(room_name: str, participant_identity: str):
# Immediately transfer the participant to the Twilio number
req = TransferSIPParticipantRequest(
room_name=room_name,
participant_identity=participant_identity,
transfer_to=TARGET_TWILIO_NUMBER,
play_dialtone=False
)
resp = await client.sip.transfer_sip_participant(req)
return resp
# Example: if you already have a mechanism to receive LiveKit webhook events or a ws connection,
# call handle_participant_join when you detect the incoming caller participant join event.
# Below is a placeholder simulation:
async def simulate_incoming_call():
room_name = "call-12345"
participant_identity = "caller-abc"
print(f"Incoming participant {participant_identity} in {room_name} — transferring...")
resp = await handle_participant_join(room_name, participant_identity)
print("Transfer response:", resp)
if __name__ == "__main__":
asyncio.run(simulate_incoming_call())
How to trigger on real arrivals
• Use LiveKit webhooks (participant_joined) or your agent SDK event handlers to detect the incoming caller joining the room created by your dispatch rule.
• On the first participant_joined event for that room (the caller), call the transfer function above immediately.
Notes
• Use the participant identity provided by the join event as participant_identity.
• Keep play_dialtone False for a direct transfer; set True if you want dial tone behavior.
• Ensure your Twilio trunk accepts SIP REFER transfers; otherwise the transfer will fail.
Would you like a complete webhook handler example (Flask/FastAPI) that receives LiveKit participant_joined events and performs the transfer automatically?quick-cartoon-22764
11/21/2025, 1:19 AMtall-airline-16756
11/21/2025, 1:19 AMquick-cartoon-22764
11/21/2025, 4:42 AMtall-airline-16756
11/21/2025, 4:42 AMparticipant_joined or a server-side subscription to room events).
• Server-side code that immediately calls transfer_sip_participant with the caller's participant_identity and the target tel:+... number.
• Twilio trunk configured to allow SIP REFER / Call Transfer.
Flow summary:
1. Dispatch rule creates the room when the SIP call arrives.
2. Your backend sees the participant_joined event.
3. Your backend calls TransferSIPParticipant → caller is removed from the LiveKit room and media is routed to the Twilio number.
If you want, I can provide a minimal Flask/FastAPI webhook example in Python that listens for participant_joined and triggers the transfer. Which framework do you use?quick-cartoon-22764
11/21/2025, 4:55 AMtall-airline-16756
11/21/2025, 4:56 AMkind field on the SIPTrunk object in webhook payloads. Use that field (or correlate a participant's sip.trunkID with your trunk records) to route logic for inbound vs outbound.
Quick facts:
• TRUNK_INBOUND = 1
• TRUNK_OUTBOUND = 2
• TRUNK_LEGACY = 0
Minimal Python webhook example (validate signature then inspect payload):
from flask import Flask, request, jsonify
from livekit.server import WebhookReceiver # adjust import for your SDK version
API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
receiver = WebhookReceiver(API_KEY, API_SECRET)
app = Flask(__name__)
@app.route("/webhook", methods=["POST"])
def webhook():
event = receiver.receive(request.get_data(), request.headers.get("Authorization"))
# example events include sip_trunk_created, sip_trunk_updated, participant_joined, etc.
if hasattr(event, "sip_trunk") and event.sip_trunk is not None:
kind = event.sip_trunk.kind
if kind == 1: # TRUNK_INBOUND
# handle inbound trunk events
pass
elif kind == 2: # TRUNK_OUTBOUND
# handle outbound trunk events
pass
# Alternatively, for participant events, inspect participant.sip.trunkID and look up trunk kind
return jsonify({"status": "ok"}), 200
If your webhook event is a participant event (e.g., participant_joined) and it does not include sip_trunk, inspect participant.sip.trunkID and map that ID to the trunk record (which contains kind) to determine direction.
Would you like a full Flask/FastAPI example that also looks up trunk records by trunkID and triggers an automatic transfer for inbound calls?
Sources: SIP APIs | LiveKit docsquick-cartoon-22764
11/21/2025, 5:05 AMtall-airline-16756
11/21/2025, 5:05 AMsip.trunkID via the LiveKit SIP API, and
• automatically performs a cold transfer to a Twilio number using the Python LiveKit API.
Replace environment variables and the target number as needed.
import os
import asyncio
import logging
from typing import Optional
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
from starlette.responses import JSONResponse
from livekit import api
from livekit.protocol.sip import TransferSIPParticipantRequest
from livekit_server_sdk.webhook import WebhookReceiver # adjust import to your server SDK package
LOG = logging.getLogger("webhook")
LOG.setLevel(logging.INFO)
LIVEKIT_URL = os.getenv("LIVEKIT_URL") # e.g. https://api.livekit.cloud or your self-hosted URL
LIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.getenv("LIVEKIT_API_SECRET")
TARGET_TWILIO_NUMBER = os.getenv("TARGET_TWILIO_NUMBER", "tel:+14155550100")
if not (LIVEKIT_URL and LIVEKIT_API_KEY and LIVEKIT_API_SECRET):
raise RuntimeError("Set LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET")
app = FastAPI()
receiver = WebhookReceiver(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
# Simple cache for trunkID -> kind to avoid extra API calls
TRUNK_KIND_CACHE: dict[str, int] = {}
class WebhookEvent(BaseModel):
event: str
room: Optional[dict] = None
participant: Optional[dict] = None
sip_trunk: Optional[dict] = None
async def get_trunk_kind(lk_api: api.LiveKitAPI, trunk_id: str) -> Optional[int]:
if trunk_id in TRUNK_KIND_CACHE:
return TRUNK_KIND_CACHE[trunk_id]
try:
# Attempt to fetch inbound trunk list and outbound list, and match by ID
inbound = await lk_api.sip.list_sip_inbound_trunk()
for t in inbound.items:
if t.sip_trunk_id == trunk_id:
TRUNK_KIND_CACHE[trunk_id] = 1 # TRUNK_INBOUND
return 1
outbound = await lk_api.sip.list_sip_outbound_trunk()
for t in outbound.items:
if t.sip_trunk_id == trunk_id:
TRUNK_KIND_CACHE[trunk_id] = 2 # TRUNK_OUTBOUND
return 2
# If not found, treat as legacy or unknown
TRUNK_KIND_CACHE[trunk_id] = 0
return 0
except Exception as e:
LOG.error("Failed to lookup trunk kind: %s", e)
return None
async def transfer_call(room_name: str, participant_identity: str):
lk_api = api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
req = TransferSIPParticipantRequest(
room_name=room_name,
participant_identity=participant_identity,
transfer_to=TARGET_TWILIO_NUMBER,
play_dialtone=False
)
try:
await lk_api.sip.transfer_sip_participant(req)
LOG.info("Transferred %s in %s to %s", participant_identity, room_name, TARGET_TWILIO_NUMBER)
except Exception as e:
LOG.error("Transfer failed: %s", e)
@app.post("/webhook")
async def webhook(request: Request):
body = await request.body()
auth_header = request.headers.get("Authorization")
try:
event_proto = receiver.receive(body, auth_header)
except Exception as e:
LOG.error("Webhook validation failed: %s", e)
raise HTTPException(status_code=401, detail="Invalid signature")
# Map proto event to simple dict model
event = WebhookEvent.parse_obj(event_proto)
# Interested in participant_joined events for SIP participants
if event.event == "participant_joined" and event.participant:
participant = event.participant
# participant.kind is expected to be "SIP" for SIP callers
if participant.get("kind") != "SIP":
return JSONResponse({"status": "ignored"}, status_code=200)
# Extract SIP attributes (these are typically under participant.attributes or participant.sip)
# Adjust according to the actual webhook payload you receive
sip_attrs = participant.get("sip") or participant.get("attributes") or {}
sip_trunk_id = sip_attrs.get("trunkID") or sip_attrs.get("sip.trunkID") or sip_attrs.get("sip_trunk_id")
room_name = event.room.get("name") if event.room else None
participant_identity = participant.get("identity")
LOG.info("SIP participant joined: identity=%s room=%s trunk=%s", participant_identity, room_name, sip_trunk_id)
if not sip_trunk_id or not room_name or not participant_identity:
LOG.warning("Missing sip_trunk_id, room, or identity; ignoring")
return JSONResponse({"status": "ignored"}, status_code=200)
# Look up trunk kind
lk_api = api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
kind = await get_trunk_kind(lk_api, sip_trunk_id)
if kind is None:
LOG.error("Could not determine trunk kind; ignoring")
return JSONResponse({"status": "error"}, status_code=500)
# TRUNK_INBOUND = 1
if kind == 1:
# Optional small delay to ensure participant fully connected
await asyncio.sleep(1)
asyncio.create_task(transfer_call(room_name, participant_identity))
return JSONResponse({"status": "transfer_initiated"}, status_code=200)
else:
LOG.info("Non-inbound trunk (%s); ignoring", kind)
return JSONResponse({"status": "ignored_non_inbound"}, status_code=200)
return JSONResponse({"status": "ok"}, status_code=200)
Notes and small adjustments you may need:
• The webhook payload shape can vary by SDK version; inspect an actual payload to confirm where SIP fields live (common places: participant.sip.*, participant.attributes, or top-level sip_trunk).
• The example caches trunk kind lookups to reduce API calls. For large deployments, use a proper cache with TTL.
• Ensure Twilio trunk has SIP REFER / Call Transfer enabled so the cold transfer succeeds.
• Set TARGET_TWILIO_NUMBER to the Twilio number you want to forward to (format: tel:+1...).
Would you like this adapted to Flask or to include retry/error handling for transfer failures?
Sources: Call forwarding | LiveKit docs | Agents telephony integration | LiveKit Docs | Using Wavix to accept and make calls | LiveKit docs | Agent-assisted warm transfer | LiveKit docs | Webhooks | LiveKit docs