transfer call with twilio sip
# ask-ai
d
transfer call with twilio sip
t
Thanks for reaching out, Billy. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to guide you through transferring a call using Twilio SIP in LiveKit! Here’s a simple step-by-step to help you get it done smoothly: 1. Enable Call Transfers on Twilio SIP Trunk: First, make sure your Twilio SIP trunk is set up to allow SIP REFER and PSTN transfers. You can easily do this through the Twilio Console or CLI: ◦ In the Twilio Console, just head over to Elastic SIP Trunking » Manage » Trunks, select your trunk, and turn on Call Transfer (SIP REFER) and PSTN Transfer. ◦ If you prefer the CLI, here’s the command you can use:
Copy code
twilio api trunking v1 trunks update --sid <twilio-trunk-sid> \
--transfer-mode enable-all \
--transfer-caller-id from-transferee
1. Use the TransferSIPParticipant API: Once your trunk is all set, you can use LiveKit’s
TransferSIPParticipant
API to carry out a cold transfer. This will end the current LiveKit session and forward the call to another number or SIP endpoint. Here are some example formats you can use for the transfer target: ◦
tel:+15105550100
◦
sip:+15105550100@sip.telnyx.com
◦
sip:+15105550100@my-livekit-demo.pstn.twilio.com
If you’d like to explore more, the LiveKit Phone Assistant Agent example is a great resource. It even shows how to use DTMF input to trigger transfers, which might be really helpful! Sources: Docs::Telephony | Docs::Telephony | Agents telephony integration | LiveKit Docs | sip-refer/README.mdoc
d
Copy code
class AlreadyBooked(AgentTask[bool]):
    def __init__(self, chat_ctx=None):
        super().__init__(
        instructions="""Let caller know they have an existing booking and them if they want to speak with someone""",
        chat_ctx=chat_ctx,
    )
    async def on_enter(self) -> None:
        logger.info("👀 Booking EXISTS!")
        await self.session.generate_reply(
            instructions="Ask if they want to speak with someone in regards to their painting project"
        )


    @function_tool
    async def transfer_caller(self) -> None:
        """use function is user wants to transfered"""
        logger.info("👀 Running Send or End")
        send = True
        if send:
            return self.complete(True)
        else:
            return self.complete(False)
i have some starter code here can you provide some starter code
t
I'm happy to share some starter code to help you transfer a call using Twilio SIP in LiveKit. Let's walk through it together: Python Example
Copy code
import asyncio
from livekit import api
from livekit.protocol.sip import TransferSIPParticipantRequest

async def transfer_call(participant_identity: str, room_name: str):
    async with api.LiveKitAPI(
        url="https://your-livekit-url",
        api_key="your-api-key",
        api_secret="your-api-secret"
    ) as lk_api:
        transfer_to = "tel:+14155550100"
        transfer_request = TransferSIPParticipantRequest(
            participant_identity=participant_identity,
            room_name=room_name,
            transfer_to=transfer_to,
            play_dialtone=False
        )

        try:
            await lk_api.sip.transfer_sip_participant(transfer_request)
            print("Transfer successful")
        except Exception as e:
            print(f"Transfer failed: {e}")
Node.js Example
Copy code
import { SipClient } from 'livekit-server-sdk';

async function transferParticipant(participantIdentity, roomName) {
  const sipClient = new SipClient(
    process.env.LIVEKIT_URL,
    process.env.LIVEKIT_API_KEY,
    process.env.LIVEKIT_API_SECRET
  );

  const transferTo = "tel:+15105550100"; // Replace with destination number
  const sipTransferOptions = {
    playDialtone: false
  };

  try {
    await sipClient.transferSipParticipant(
      roomName,
      participantIdentity,
      transferTo,
      sipTransferOptions
    );
    console.log("Transfer successful");
  } catch (error) {
    console.error("Transfer failed:", error);
  }
}
Just a quick reminder to replace placeholders like
your-livekit-url
,
your-api-key
, and
your-api-secret
with your actual LiveKit credentials. If you have any questions or need a hand with anything else, feel free to reach out—I'm here to help! Sources: Docs::Telephony | Docs::Agents | Transferring calls | LiveKit Docs
d
so i can create a transfer_call.py file and do all this jazz in there and import the asycn def transfer_caller
or name it twilio_utils.py
t
Absolutely, you can create a
transfer_call.py
file and include the
async def transfer_call
function there. Once you’ve got it set up, you can easily import and use this function in other parts of your project whenever you need. Just a couple of things to keep in mind: • Make sure you have the LiveKit SDK installed for Python. • Set up the necessary environment variables (
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
). • Call the function with the right parameters, like the participant identity and room name. If you'd like, I’m here to help you with organizing your project or if you need any extra guidance along the way!
Absolutely, you can create a file like
transfer_call.py
or
twilio_utils.py
to keep your
async def transfer_caller
function. This is a great way to keep your code organized and reusable. Then, you can easily import that function wherever you need it in your project. For instance, if you decide to name the file
twilio_utils.py
, you can import and use the function like this:
Copy code
from twilio_utils import transfer_caller

await transfer_caller(participant_identity="example_id", room_name="example_room")
If you'd like, I’m here to help you with setting up the file or integrating it smoothly into your project—just let me know!
d
Copy code
import asyncio
import os
from dotenv import load_dotenv
from livekit import api
from livekit.agents import AgentSession
from livekit.protocol.sip import TransferSIPParticipantRequest

load_dotenv(".env.local")

async def transfer_caller(participant_identity: str, room_name: str):
    async with api.LiveKitAPI(
        url=os.getenv("LIVEKIT_URL"),
        api_key=os.getenv("LIVEKIT_API_KEY"),
        api_secret=os.getenv("LIVEKIT_SECRET")
    ) as lk_api:
        transfer_to = "tel:+12267902753"
        transfer_request = TransferSIPParticipantRequest(
            participant_identity=participant_identity,
            room_name=room_name,
            transfer_to=transfer_to,
            play_dialtone=False
        )

        try:
            await lk_api.sip.transfer_sip_participant(transfer_request)
            print("Transfer successful")
        except Exception as e:
            print(f"Transfer failed: {e}")
just got errors with this code... {"message": "👀 Booking EXISTS!", "level": "INFO", "name": "collect-name-task", "pid": 134, "job_id": "AJ_yWuveQb9QcTM", "timestamp": "2025-09-30T061631.971893+00:00"} {"message": "🏃‍♂️‍➡️ Running transfer_call function", "level": "INFO", "name": "collect-name-task", "pid": 134, "job_i id": "AJ_yWuveQb9QcTM", "timestamp": "2025-09-30T061639.974730+00:00"} Transfer failed: TwirpError(code=permission_denied, message=twirp error unknown: sip status 403: Forbidden, status=403, metadata={'error_details': 'CAcSGXNpcCBzdGF0dXMgNDAzOiBGb3JiaWRkZW4aNwoldHlwZS5nb29nbGVhcGlzLmNvbS9saXZla2l0LlNJUFN0YXR1cxIOCJMDEglGb3JiaWRkZW4=', 'sip_status': 'Forbidden', 'sip_status_code': '403'}) {"message": "process exiting", "level": "INFO", "name": "livekit.agents", "reason": "", "pid": 134, "job_id": "AJ_yWuveQb9QcTM", "timestamp": "2025-09-30T061640.098992+00:00"}
t
The SIP status 403 Forbidden error usually points to a couple of common issues, and I’m here to help you navigate through them: 1. Authentication or Permission Errors: It’s a good idea to double-check that the username and password you’ve set up for your SIP trunk in LiveKit exactly match what your SIP provider has given you. Sometimes a small mismatch can cause this error. Take a moment to review your LiveKit configuration alongside your SIP provider’s console. 2. Regional Compliance Issues: Depending on where you are, there might be regulations that require calls to stay within national borders. If your call is routed through another country, your SIP provider might block it. To fix this, you can use region pinning to keep call routing within a specific area. For outbound calls, specifying the
destination_country
parameter when creating an outbound trunk can really help. If you’d like, I’m more than happy to assist you with verifying your credentials or setting up region pinning—just let me know! Sources: SIP troubleshooting guide | LiveKit Docs | Docs::Telephony
d
where does it ask for SIP theres no SIP inpit the code
t
Hi there! Just to clarify, the SIP credentials are usually set up in your SIP trunk configuration with your provider (like Twilio) rather than directly in the code. The code then connects to the SIP trunk through LiveKit's API, which uses the SIP trunk settings you’ve already configured in your LiveKit environment. To make sure everything is working smoothly with your SIP trunk, here’s a quick checklist: 1. Log in to your SIP provider’s console (for example, Twilio). 2. Double-check that your SIP trunk has the correct credentials (username and password). 3. Confirm that the SIP trunk supports call transfers and is set up to handle the destination number or endpoint you want. If you haven’t set up a SIP trunk in your LiveKit environment yet, no worries at all! Just let me know, and I’ll happily walk you through the steps.
d
It all works except for the transer call using SIP, calls come in fine. If you dont know the answer just say so instead assuming
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
d
You have the exact information needed: Enable call transfers for your Twilio SIP trunk Enable call transfer and PSTN transfers for your Twilio SIP trunk. To learn more, see Twilio's Call Transfer via SIP REFER documentation. When you transfer a call, you have the option to set the caller ID to display the phone number of the transferee (the caller) or the transferor (the phone number associated with your LiveKit trunk). The following command enables call transfers and sets the caller ID to display the number of the transferee: N*ote* • To list trunks, execute •
twilio api trunking v1 trunks list
. • To set the caller ID to the transferor, set
transfer-caller-id
to
from-transferor
. `````` thanks 1. Sign in to the Twilio console 2. 3. . 4. Navigate to Elastic SIP Trunking » Manage » Trunks, and select a trunk. 5. In the Features » Call Transfer (SIP REFER) section, select Enabled. 6. In the Caller ID for Transfer Target field, select an option. 7. Select Enable PSTN Transfer. 8. Save your changes.