Call forwarding using bot in Pipecat + Twilio
I'm currently working on implementing call forwarding using Twilio in combination with Pipecat. I've set up function calling successfully to trigger the forwarding logic, but I need clarity on how to properly forward the call to another Twilio phone number.
The goal is to transfer the active call from the user to a different Twilio number without disconnecting the user. Ideally, the transition should be seamless, the bot should gracefully hand off the call, and the user should be connected to the new number directly.
One aspect I'm uncertain about is how to disconnect or gracefully remove the bot from the call flow once the forwarding is triggered. I assume the call can be redirected by making an inbound request to the secondary Twilio number, but I’m unsure how to manage the transfer flow properly within the Twilio call session.
Any guidance or examples on handling this kind of handoff in Twilio, especially with Pipecat in the loop, would be appreciated.
Hi @Ahmer967,
based on Twilio's documentation, the following should work:
During an active call, you can use TwiML's <Dial> Dial to connect the current caller to another party.
The following example shows the most basic use of "Dial":
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial>415-123-4567</Dial>
</Response>
If the party at 415-123-4567 answers the call, the two parties can communicate until one hangs up.
- If someone answers, Twilio connects the caller with the called party.
- If the initial caller hangs up, the Twilio session ends and the "Say" does not execute.
- If the line is busy, if there is no answer, or if the called party hangs up, "Dial" exits and the initial caller hears the "Say" text ("Goodbye") before the call flow ends.
So if you are working with python, this should do the job:
from twilio.twiml.voice_response import Dial, VoiceResponse, Say
from twilio.rest import Client
twilio = Client(
os.environ.get("TWILIO_ACCOUNT_SID"), os.environ.get("TWILIO_AUTH_TOKEN")
)
async def forward_twilio_call(function_name, tool_call_id, args, llm, context, result_callback):
response = VoiceResponse()
response.dial(args.get('target_number'))
response.say(args.get('forward_message'))
call = twilio.calls.get(sid=args.get('call_sid'))
end_call = call.update(twiml=response)
Since I need to do this soon aswell, you're welcome to give some feedback! :-)
Best
In this case, the AI Agent is still on the call, or are you cancelling it?
The goal is to transfer the active call from the user to a different Twilio number without disconnecting the user.
This is only possible using Twilio SIP. This can't be done using the Websockets connection.