CreateSIPInboundTrunkRequest Python SDK example t...
# ask-ai
r
CreateSIPInboundTrunkRequest Python SDK example to create Inbound trunk for a number
t
Thanks for reaching out, pritesh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here’s a friendly example to help you create a SIP inbound trunk for a number using the Python SDK:
Copy code
async def manage_sip_resources() -> None:
    # Initialize LiveKit API client
    lk_api = LiveKitAPI(
        url=livekit_url,
        api_key=livekit_api_key,
        api_secret=livekit_api_secret,
    )

    # Create new inbound trunk with basic configuration
    inbound_trunk_request = CreateSIPInboundTrunkRequest(
        trunk=SIPInboundTrunkInfo(
            name="My Inbound Trunk",
            numbers=["+15105550100"],  # Just swap this out with your own phone numbers
            krisp_enabled=True,
        ),
    )
    inbound_trunk = await lk_api.sip.create_sip_inbound_trunk(inbound_trunk_request)
Make sure to replace
livekit_url
,
livekit_api_key
, and
livekit_api_secret
with your actual LiveKit API info. Also, update the
numbers
list with the phone numbers you want linked to your trunk. If you have any questions or want help with more setup options, just let me know—I’m here to help! Sources: Creating SIP Inbound Trunks and Dispatch Rules with Python SDK | SIP APIs | LiveKit Docs
r
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, ) Do we need to pass inboound sip_trunk_id or outbount sip_trunk_id ?
t
Just a quick heads-up: the
sip_trunk_id
in
CreateSIPParticipantRequest
should be an outbound SIP trunk ID. This is because this request kicks off outgoing calls from LiveKit to a SIP endpoint, and for that, you need an outbound trunk set up. Inbound SIP trunks, on the other hand, handle incoming calls and are managed through dispatch rules—not in this request. If anything’s unclear or you want to chat more about it, just let me know—I’m here to help! Sources: livekit-protocol/src/livekit.rs | livekit/livekit_sip.pb.go | SIP APIs | LiveKit Docs
r
I am adding new participant to the room, so I need outbound sip_trunk_id of target number to pass in the CreateSIPParticipantRequest
t
Yes, you’ve got it! When you’re adding a new participant to the room using
CreateSIPParticipantRequest
, just make sure to include the outbound SIP trunk ID that matches the target number. This helps route the call properly through the right outbound trunk. If you have any questions or need a hand with this, feel free to ask—I’m here to help!
r
_# 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 220341,514 - brilo.functions.standard.call_transfer - INFO - Found SIP outbound Trunk ID for +12344043854: ST_ti2gSFqVG43R 2025-08-28 220341,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 220341,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-28T163341.514541+00:00"} 2025-08-28 220342,197 - livekit-utils - INFO - Participant disconnected: sip_+12342175178 2025-08-28 220342,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-28T163342.197529+00:00"} 2025-08-28 220342,200 - livekit.agents - DEBUG - stream closed 2025-08-28 220342,207 - brilo.functions.standard.call_transfer - INFO - Successfully added new agent to room call_+12342175178_58LXnvTSViv9 (warm_message) 2025-08-28 220342,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-28T163342.207145+00:00"}
t
Hey there! When a participant disconnects after a warm transfer, it could be happening for a few reasons: • SIP Trunk Provider Rejection: Sometimes the SIP provider might reject the call due to things like authentication hiccups, network troubles, or policy rules, which would cause the participant to disconnect. • Call Timeout: If the call isn’t answered within the set
ringing_timeout
, the system might clean things up and disconnect the participant. • Call Status Failure: If the SIP call status doesn’t switch to
active
, the participant will get disconnected. Keeping an eye on the
sip.callStatus
attribute can really help figure this out. • SIP Response Errors: Errors like
403 Forbidden
or
486 Busy Here
in the SIP response can cause the call to fail and the participant to drop. Here are some friendly tips to troubleshoot: • Take a look at the
sip.callStatus
attribute to see if the call actually connected. • Check out the
error
and
disconnect_reason
fields in the SIP call logs for clues about what went wrong. • Make sure your outbound trunk setup is solid—double-check credentials and allowed addresses. • Review the logs for SIP response codes and Twirp errors to spot any issues. If you want, I’m here to help you dig into this further—just let me know! Sources: Making outbound calls | LiveKit Docs | livekit-protocol/livekit/protocol/sip.py | examples/warm-transfer/warm_transfer.py | livekit/livekit_sip.pb.go | sipclient.go