cold-eve-87123
08/08/2025, 1:02 PMfrom 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>refined-appointment-81829
08/08/2025, 1:05 PMcold-eve-87123
08/08/2025, 1:07 PMrefined-appointment-81829
08/08/2025, 1:08 PMcold-eve-87123
08/13/2025, 1:49 PM{
"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"
}cold-eve-87123
08/13/2025, 1:53 PMrefined-appointment-81829
08/13/2025, 2:14 PMcold-eve-87123
08/13/2025, 2:18 PMrefined-appointment-81829
08/13/2025, 2:34 PMRingingTimeout 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.refined-appointment-81829
08/13/2025, 2:37 PMcold-eve-87123
08/14/2025, 11:37 AMtransfer_to.
I updated it to use this format:
sip:+15105550100@sip.telnyx.com
instead of just +15105550100.