Hello, I tried a 'cold transfer'. this is agent co...
# telephony
c
Hello, I tried a 'cold transfer'. this is agent code. i'm using the Telnyx Trunking.
from livekit.agents import Agent
import logging
from dotenv import load_dotenv,load_dotenv
from livekit.agents import (
AgentSession,
Agent,
RoomInputOptions,
function_tool,
RunContext,
ChatContext,
get_job_context
)
import requests
from pathlib import Path
from pydantic import Field
from typing import Annotated
from models import ContactPayload
from utils import read_file_text
import os
import asyncio
import os
import uuid
from pathlib import Path
from dotenv import load_dotenv
from livekit.agents import JobContext, WorkerOptions, cli
from livekit import rtc
from livekit import api
from livekit.agents.llm import function_tool
from livekit.agents.voice import Agent, AgentSession, RunContext
import aiohttp
import asyncio
import requests
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
phonepilote_token  = os.getenv("PHONE_PILOT")
dotenv_path = Path('.env')
load_dotenv(dotenv_path)
class internAgent(Agent):
def __init__(self, job_context=None) -> None:
agent_name = self.__class__.__name__
self.job_context = job_context
logger.info(f"entering task {agent_name}")
filepath = os.path.join("prompts", "intern-system-prompt.txt")
prompt = read_file_text(filepath)
super().__init__(instructions=prompt)
@function_tool()
async def on_enter(context: RunContext) -> None:
logger.info(f"Enter the on_enter() node in intern Agent....")
# callee  = context.session.userdata.caller.callee
caller  = context.session.userdata.caller
job_ctx = get_job_context()
from livekit.api import ListParticipantsRequest
res = await job_ctx.api.room.list_participants(ListParticipantsRequest(
room=job_ctx.room.name
))
# logger.info(f'List of participants: {res}')
instructions = (
f"Greet the {caller.name} and tell him. and welcome him to Diamanda services."
)
await context.session.generate_reply(
instructions = instructions,
allow_interruptions = True
)
@function_tool()
async def transfer_call(self, context: RunContext, phone_number: str) -> str:
"""
Cold transfer the SIP call to another number (agent is removed from the call).
"""
job_ctx = get_job_context()
print(job_ctx.room.num_participants)
remote_participants =  list(job_ctx.room.remote_participants.keys())[0]
logger.info(remote_participants)
# SIP participant
# job_ctx.room.remote_participants
transfer_to = "+33" + phone_number.lstrip("0").replace(" ", "")
logger.info(f"Cold transferring {remote_participants} to {transfer_to}")
await context.session.generate_reply(
instructions=f"Transferring you to {phone_number}. Please hold.",
allow_interruptions=False
)
try:
livekit_api = api.LiveKitAPI(
url=os.getenv("LIVEKIT_URL"),
api_key=os.getenv("LIVEKIT_API_KEY"),
api_secret=os.getenv("LIVEKIT_API_SECRET"),
)
from livekit.protocol import sip as proto_sip
transfer_request = proto_sip.TransferSIPParticipantRequest(
participant_identity=remote_participants,
room_name=job_ctx.room.name,
transfer_to=transfer_to,
play_dialtone=True
)
await livekit_api.sip.transfer_sip_participant(transfer_request)
logger.info(f"Transfer successful: {remote_participants} → {transfer_to}")
return f"Call transferred to {phone_number}."
except Exception as e:
logger.error(f"Transfer failed: {e}", exc_info=True)
return "I'm sorry, I couldn't transfer your call at this time."
However i got this error.
2025-08-08 14:51:19,627 - DEBUG livekit.agents - received user transcript {"user_transcript": "Je veux que tu aies fait un.", "language": "fr"}
2025-08-08 14:51:24,712 - DEBUG livekit.plugins.turn_detector - eou prediction {"eou_probability": 0.37390074133872986, "input": "<|im_start|>assistant\nBonjour et bienvenue chez Diamanda services, comment puis-je vous aider aujourd'hui ?<|im_end|>\n<|im_start|>user\nJe veux que tu aies fait un.", "duration": 0.027}
2025-08-08 14:51:25,816 - DEBUG livekit.agents - received user transcript {"user_transcript": "Appel vers le numéro suivant : 01 80 96 31 15", "language": "fr"}
2025-08-08 14:51:25,863 - DEBUG livekit.plugins.turn_detector - eou prediction {"eou_probability": 0.027022218331694603, "input": "<|im_start|>assistant\nBonjour et bienvenue chez Diamanda services, comment puis-je vous aider aujourd'hui ?<|im_end|>\n<|im_start|>user\nJe veux que tu aies fait un.Appel vers le numéro suivant : 01 80 96 31 15", "duration": 0.044}
2025-08-08 14:51:31,231 - DEBUG livekit.agents - executing tool {"function": "transfer_call", "arguments": "{\"phone_number\":\"0180963115\"}", "speech_id": "speech_08e7bc927cd8"}
2
2025-08-08 14:51:31,232 - INFO agents.intern_agent - sip_+33180963014
2025-08-08 14:51:31,232 - INFO agents.intern_agent - Cold transferring sip_+33180963014 to +33180963115
2025-08-08 14:52:17,003 - ERROR agents.intern_agent - Transfer failed: TwirpError(code=deadline_exceeded, message=twirp error unknown: request timed out, status=408)
Traceback (most recent call last):
File "C:\Users\Rey Ayayos\livekit-diamanda\agents\intern_agent.py", line 172, in transfer_call
await livekit_api.sip.transfer_sip_participant(transfer_request)
File "C:\Users\Rey Ayayos\livekit-diamanda\venv\Lib\site-packages\livekit\api\sip_service.py", line 434, in transfer_sip_participant
return await self._client.request(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
...<11 lines>...
)
^
File "C:\Users\Rey Ayayos\livekit-diamanda\venv\Lib\site-packages\livekit\api\twirp_client.py", line 129, in request
raise TwirpError(
...<4 lines>...
)
livekit.api.twirp_client.TwirpError: TwirpError(code=deadline_exceeded, message=twirp error unknown: request timed out, status=408)
2025-08-08 14:52:17,005 - ERROR asyncio - Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000229216E6850>
2025-08-08 14:52:17,005 - ERROR asyncio - Unclosed connector
connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x00000229223E37D0>, 354090.3735444)])']
connector: <aiohttp.connector.TCPConnector object at 0x00000229255BAC10>
r
In the future please put large code snips in a thread instead of in the main channel. Or better attach a file in a thread. Telnyx requires you to request transfer to be enabled from them. They don't allow it by default.
c
Sorry about putitng a large code , thank you for your respond, unfortunatly i couldn't find any docs about how to enable this request transfer. In livekit docs , only twilio configuration of cold transfer is available
r
Transfer will be pretty much the same for Twilio or Telnyx. But it won't work until Telnyx enables it for you.
👍 1
c
Hello again sorry to bother you again. i contacted the telynx support to enable the Incoming SIP REFER and they replied it is activated now by defaults. so i still have the same problem my configuration as follows:
{
"sipTrunkId": "ST_TmuUHo4dggwg",
"name": "My trunck",
"numbers": [
"+33423330751"
],
"krispEnabled": true}
Dispatch rule:
{
"sipDispatchRuleId": "SDR_aeDtxwHMo6HS",
"rule": {
"dispatchRuleIndividual": {
"roomPrefix": "call"
}
},
"trunkIds": [
"ST_TmuUHo4dggwg"
],
"name": "My rule",
"roomConfig": {
"agents": [
{
"agentName": "my-telephony-agent"
}
]
}
}
outbound
{
"sipTrunkId": "ST_HmABTkLetTjG",
"name": "Outbund Trunk",
"address": "sip.telnyx.com",
"numbers": [
"+33423330751"
],
"authUsername": "my-user-name",
"authPassword": "my_password"
}
r
Is that PCAP a transfer? Looks like a regular INVITE.
c
I'm sorry i sent the wrong file
r
That LiveKit expects a NOTIFY message with a "SIP/2.0 200 OK" status in the message body to signal successful transfer completion. Based on the PCAP data and logs provided, the SIP call transfer is failing due to a timeout issue. Here's the analysis: Root Cause: Transfer Timeout The SIP call transfer is failing because the transfer operation is timing out before it can complete successfully. The error message "refer canceled" indicates that the transfer context was canceled due to a timeout. Technical Details The transfer process works as follows: 1. Transfer Initiation: The system sends a REFER request to transfer the call from the original caller (+33180963014) to the destination number (+33758611523) outbound.go:965-1008 2. Timeout Configuration: The system uses a default timeout of 80 seconds for transfer operations when no specific
RingingTimeout
is configured service.go:240-243 3. Context Cancellation: When the timeout expires, the transfer context is canceled, resulting in the "refer canceled" error outbound.go:998-1001 4. Error Logging: This cancellation triggers the error log message "inbound call failed to transfer" with the "refer canceled" error inbound.go:1101-1105 Evidence from Logs and PCAP Looking at the timeline in the logs: • Transfer attempts started at 81111 AM with multiple "transfering SIP call" messages • The final failure was logged at 81231 AM (approximately 80 seconds later) • The PCAP shows that the REFER request received a "202 Accepted" response, but the actual transfer to +33758611523 never completed successfully Potential Solutions 1. Increase Timeout: Configure a longer
RingingTimeout
in the transfer request if the destination number requires more time to answer 2. Check Destination: Verify that +33758611523 is reachable and properly configured to accept transferred calls 3. Network Issues: Investigate potential network connectivity or routing issues between the SIP infrastructure and the destination number Notes The failure is not due to a protocol error or system malfunction, but rather a timing issue where the destination number (+33758611523) is not answering within the configured timeout period. The REFER request was properly sent and accepted, but the actual call establishment to the transfer target timed out.
Would expect the PCAP to look more like this
c
Good morning, @refined-appointment-81829 I’ve resolved the issue. The problem was caused by the format of
transfer_to
. I updated it to use this format:
sip:+15105550100@sip.telnyx.com
instead of just
+15105550100
.
🎉 1