We have created elastic SIP trunk for outbound cal...
# ask-ai
q
We have created elastic SIP trunk for outbound call. We want to forward call to another twilio number incase we receive any incoming call to the SIP trunk. How can we do that?
t
Thanks for reaching out, Harsh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to forward incoming calls to your Elastic SIP Trunk to another Twilio number. You can do this by receiving the inbound call in LiveKit and performing a cold transfer (SIP REFER) to the target Twilio number. Steps: 1. Configure an inbound trunk in LiveKit tied to your Twilio SIP trunk so LiveKit can receive incoming calls. 2. Create a dispatch rule to route each incoming call into a LiveKit room (one room per call). 3. From your agent or server-side logic, call the TransferSIPParticipant API to perform a cold transfer to the target Twilio number (e.g.,
tel:+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 docs
q
I am using Python livekit-agent SDK and we want transfer to be automatic on arrival
t
Acknowledged — you want an automatic cold transfer on call arrival using the Python livekit-agent SDK. Below is a concise guide and a Python example showing how to: • accept incoming SIP calls into a room via your dispatch rule, then • immediately call
transfer_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
.
Copy code
# 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?
q
Once the agent transfers the incoming call, would the communication still happen via livekit room?
t
Regarding the TransferSIPParticipant (cold transfer): once the agent performs the transfer, the call is handed off and media no longer flows through the LiveKit room. The transferred participant is removed from the room and the session ends in LiveKit; media is routed directly between the caller and the transfer target (Twilio). If you want media to continue inside LiveKit (so the room stays active and participants remain connected), you would need a warm/bridged transfer or to implement an in-room bridge where LiveKit dials out while keeping the caller in the room. I can provide sample patterns or code for a warm transfer / bridged flow in Python if you’d like.
q
So to do cold transfer I do not need to create any agent?
t
You do not need a LiveKit "agent" (human or Agent SDK client) to perform a cold transfer. However, you do need a backend process that detects the incoming call and calls the TransferSIPParticipant API. What you need: • A way to detect the incoming caller joining the room (webhook event
participant_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?
q
Is there a way we can filter webhook request depending if they are coming from inbound trunk or outbound trunk?
t
You can distinguish inbound vs outbound trunk events by checking the
kind
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):
Copy code
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 docs
q
yes
t
Below is a concise FastAPI webhook handler that: • validates LiveKit webhook signatures, • detects SIP caller joins, • determines whether the call came from an inbound trunk by looking up the participant's
sip.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.
Copy code
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