5-09-24 23:41:04,170 - DEBUG livekit.agents - usin...
# ask-ai
e
2025-09-24 234104,170 - DEBUG livekit.agents - using audio io:
RoomIO
->
AgentSession
->
TranscriptSynchronizer
->
DataStreamIO
{"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234104,171 - WARNING livekit.agents - resume_false_interruption is enabled but audio output does not support pause, it will be ignored {"audio_output": "TranscriptSynchronizer", "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234104,171 - DEBUG livekit.agents - using transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
{"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234104,171 - DEBUG livekit.agents - using video io:
RoomIO
>
AgentSession
> (none) {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234104,630 - DEBUG livekit.agents - remote participant ready {"identity": "simli-avatar-agent", "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234112,074 - WARNING livekit.agents - failed to synthesize speech, retrying in 0.1s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run connection = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for return fut.result() ^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection await conn.connect() File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect self._ws = await self._session.ws_connect(url, headers=headers) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect raise WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run raise APIConnectionError("could not connect to ElevenLabs") from e livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234115,679 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run connection = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for return fut.result() ^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection await conn.connect() File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect self._ws = await self._session.ws_connect(url, headers=headers) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect raise WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run raise APIConnectionError("could not connect to ElevenLabs") from e livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234119,201 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run connection = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for return fut.result() ^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection await conn.connect() File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect self._ws = await self._session.ws_connect(url, headers=headers) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect raise WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run raise APIConnectionError("could not connect to ElevenLabs") from e livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true, "pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"} 2025-09-24 234123,034 - ERROR livekit.agents - Error in _tts_inference_task Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 358, in _run connection = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/tasks.py", line 489, in wait_for return fut.result() ^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 239, in current_connection await conn.connect() File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 513, in connect self._ws = await self._session.ws_connect(url, headers=headers) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1084, in _ws_connect raise WSServerHandshakeError( aiohttp.client_exceptions.WSServerHandshakeError: 403, message='Invalid response status', url='https://help.elevenlabs.io/hc/en-us/articles/22497891312401-Do-you-restrict-access-to-the-service-and-platform-for-any-specific-countries-add' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py", line 212, in _tts_inference_task async for audio_frame in tts_node: File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py", line 436, in tts_node async for ev in stream: File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 532, in anext raise exc # noqa: B904 ^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 364, in _run raise APIConnectionError("could not connect to ElevenLabs") from e livekit.agents._exceptions.APIConnectionError: could not connect to ElevenLabs (body=None, retryable=True) {"pid": 286131, "job_id": "AJ_sMuVC9Q2jodb"}
t
Thanks for reaching out, blue. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It looks like the error is showing that the WebSocket connection to ElevenLabs didn’t go through because of a 403 Forbidden status. This usually means the API key might be missing, invalid, or doesn’t have the right permissions. Here’s how we can work through this together: 1. First, please double-check that the ElevenLabs API key is correctly set in the environment variable
ELEVEN_API_KEY
or that it’s properly passed as a parameter when initializing. 2. Next, make sure the API key has the necessary permissions for text-to-speech streaming. 3. It’s also a good idea to look into any network restrictions or firewall settings that might be blocking WebSocket connections to
<wss://api.elevenlabs.io>
. 4. Lastly, take a moment to review your initialization code to confirm the TTS class is set up correctly. If you’re still running into trouble after these steps, it might be worth checking if there are any regional restrictions affecting access to ElevenLabs services. I’m here to help you through this, so don’t hesitate to reach out with any questions! Sources: SIP troubleshooting guide | LiveKit Docs | livekit-plugins/livekit-plugins-elevenlabs/livekit/plugins/elevenlabs/stt.p... | plugins/elevenlabs/src/tts.ts | ElevenLabs TTS integration guide | LiveKit Docs
b
2025-09-25 004159,112 - DEBUG livekit.plugins.simli - starting avatar session {"pid": 295355, "job_id": "AJ_gwEBUpaCUzDh"} Failed to start avatar: Cannot connect to host api.simli.ai:443 ssl:default [Temporary failure in name resolution]
t
It looks like the error is related to a DNS resolution issue, meaning the domain
<http://api.simli.ai|api.simli.ai>
couldn’t be translated into an IP address. This is why the connection to the Simli AI service isn’t going through. Let’s try a few steps to get this sorted out: 1. First, check the DNS resolution by running
host <http://api.simli.ai|api.simli.ai>
on the server or container where your LiveKit agent is running. 2. Make sure that outbound internet access on port 443 is allowed for external domains—sometimes firewalls can block these connections. 3. Also, take a look at any network initialization issues, especially if you’re working with cloud environments or container orchestration systems. 4. Try testing the connectivity directly with
curl -v <https://api.simli.ai>
to see what response you get. 5. It might help to switch to a reliable DNS resolver like Google DNS (
8.8.8.8
), just to be sure. If you’re still running into trouble after these steps, it might be a good idea to reach out to your network administrator for a closer look. We’re here to help you through this! Sources: livekit-plugins/livekit-plugins-inworld/livekit/plugins/inworld/tts.py | Configuring firewalls | LiveKit Docs | Deploy to a VM | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utility
b
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/worker.py", line 649, in _connection_task ws = await self._http_session.ws_connect( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 1067, in _ws_connect resp = await self.request( ^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 770, in _request resp = await handler(req) ^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/client.py", line 725, in _connect_and_send_request conn = await self._connector.connect( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 642, in connect proto = await self._create_connection(req, traces, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1209, in _create_connection _, proto = await self._create_direct_connection(req, traces, timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1581, in _create_direct_connection raise last_exc File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1550, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1291, in _wrap_create_connection raise client_error(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host navigence-85r0jkqk.livekit.cloud:443 ssl:default [Connection reset by peer] 2025-09-25 013647,392 - WARNING livekit.agents - failed to connect to livekit, retrying in 4s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/aiohttp/connector.py", line 1283, in _wrap_create_connection return await self._loop.create_connection(*args, **kwargs, sock=sock) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1112, in create_connection transport, protocol = await self._create_connection_transport( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1145, in _create_connection_transport await waiter File "/usr/local/lib/python3.11/asyncio/sslproto.py", line 575, in _on_handshake_complete raise handshake_exc ConnectionResetError
t
It looks like the connection to the LiveKit server at
navigence-85r0jkqk.livekit.cloud
was unexpectedly reset by the server or something in the network. This can happen for a few common reasons: • Network firewalls or security settings might be blocking traffic to
*.livekit.cloud
on port 443. • There could be SSL/TLS handshake issues, like outdated certificates or incompatible TLS versions. • The server might disconnect due to invalid credentials or timeouts. Here are some friendly steps you can try to get this sorted out: 1. Make sure that outbound connections to
*.livekit.cloud
and
*.turn.livekit.cloud
on TCP port 443 are allowed. 2. Take a look at any firewall or antivirus software that might be affecting WebSocket connections. 3. Try using the LiveKit Connection Test Utility, especially the WebSocket and TURN checks, to see how the connection is doing. 4. Double-check that the server URL and access token you’re using are correct. 5. If you suspect SSL/TLS issues, consider updating your system or application certificate stores. If you’re still running into trouble after these steps, it might be helpful to reach out to your IT team to ensure that traffic to the necessary domains is allowed. We're here to help you through this! Sources: Operational Guidance | livekit/livekit_composite | DeepWiki | errors.go | Configuring firewalls | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utility
b
Connecting to signal connection via WebSocket Connected to server, version 1.9.1. LiveKit Cloud: Singapore Establishing WebRTC connection udp 161.118.222.18:50007 host udp [2603c02445109d000bfbbb8d2da36]50007 host tcp 161.118.222.18:7881 host (passive) tcp [2603c02445109d000bfbbb8d2da36]7881 host (passive) udp 161.118.222.18:50009 host udp [2603c02445109d000bfbbb8d2da36]50009 host tcp 161.118.222.18:7881 host (passive) tcp [2603c02445109d000bfbbb8d2da36]7881 host (passive) Warning: error with ICE candidate: 701 STUN host lookup received error. stunip 161 118 222 18.host.livekit.cloud3478 Warning: error with ICE candidate: 701 TURN host lookup received error. turnip 161 118 222 18.host.livekit.cloud3478?transport=udp Can connect via TURN Can publish audio Error: unable to detect audio from microphone Can publish video Error: Requested device not found Resuming connection after interruption
t
It looks like the errors are happening because the client is having trouble connecting to the STUN and TURN servers, which are really important for setting up WebRTC connections. This can happen due to a few common reasons: • There might be some DNS resolution issues or the domains could be unreachable. • Sometimes, firewall or security settings block outbound connections to
*.turn.livekit.cloud
or similar domains. • Or, the server settings in your LiveKit configuration might need a quick review. Here are some steps that can help you get this sorted out: 1. Try running the LiveKit Connection Test Utility to check your WebSocket, WebRTC, and TURN connectivity. 2. Make sure that domains like
*.turn.livekit.cloud
are allowed on your network, and that TCP/TLS traffic on port 443 is open. 3. To check for DNS issues, you can run
host stun:ip-161-118-222-18.host.livekit.cloud
and
host turn:ip-161-118-222-18.host.livekit.cloud
. 4. You might also want to try forcing TURN usage by setting
iceTransportPolicy: 'relay'
in your client configuration—this helps confirm TURN connectivity. If you’re still running into problems after these steps, it could be helpful to reach out to your network administrator to double-check that the necessary domains and ports are accessible. Please know we’re here to support you through this! Sources: Documentation/ImprovingCallReliability.md | README.md | pkg/service/roommanager.go | Configuring firewalls | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utility
b
Agent ID: AD_rkvkzPNsUWQ7 Room Access Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2aWRlbyI6eyJyb29tSm9pbiI6dHJ1ZSwicm9vbSI6InJvb21fZjZkMDNjYzYiLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwicm9vbUNvbmZpZyI6eyJhZ2VudHMiOlt7ImFnZW50TmFtZSI6ImFnZW50X2M3YThlZmNmIn1dfSwic3ViIjoiZWJiZjM5MmYtNzM4OC00NjhjLThjNDQtY2I0ZjJhZTFjNjNiIiwiaXNzIjoiQVBJcGZueTM5UjZjc0E3IiwibmJmIjoxNzU4ODIxNDQxLCJleHAiOjE3NTg4NDMwNDF9.X_HbQrmEORIWkbG9Cn-trIpxHj3j0_RS4DK-NUdDrMY INFO: 127.0.0.1:53692 - "POST /api/v1/avatar/getToken HTTP/1.1" 200 OK Agent_Name in creation: agent_c7a8efcf, Type: <class 'str'> 2025-09-25 113044,563 - DEBUG asyncio - Using selector: EpollSelector 2025-09-25 113044,564 - INFO livekit.agents - starting worker {"version": "1.2.11", "rtc-version": "1.0.13"} 2025-09-25 113044,564 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.openai", "livekit.plugins.simli", "livekit.plugins.elevenlabs", "livekit.plugins.silero", "av"]} 2025-09-25 113047,102 - INFO livekit.agents - registered worker {"id": "AW_k4vJzDPoF7qc", "url": "wss://navigence-85r0jkqk.livekit.cloud", "region": "Singapore", "protocol": 16} 2025-09-25 113047,570 - INFO livekit.agents - received job request {"job_id": "AJ_sooCdKfy2CnP", "dispatch_id": "", "room_name": "room_f6d03cc6", "agent_name": "agent_c7a8efcf", "resuming": false} 2025-09-25 113049,327 - INFO livekit.agents - initializing process {"pid": 374132} 2025-09-25 113049,974 - INFO livekit.agents - process initialized {"pid": 374132, "elapsed_time": 0.65} 2025-09-25 113049,974 - DEBUG asyncio - Using selector: EpollSelector {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} Failed to load CUDA modules. maybe the NVIDIA driver is not installed? Failed to initialize CUDA context. Failed to open VA display. Maybe the AMD video driver or libva-dev/libdrm-dev is not installed? Failed to open VAAPI display. Failed to load CUDA modules. maybe the NVIDIA driver is not installed? Failed to initialize CUDA context. CTX.Room.Name: room_f6d03cc6 Agent Session Avatar Starting... 2025-09-25 113057,950 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113057,952 - DEBUG livekit.plugins.simli - starting avatar session {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} Agent Start Room:rtc.Room(sid=unknown, name=room_f6d03cc6, metadata={ "job_title": "Full Stack Developer", "job_description": "Full Stack Developer", "company_name": "Full Stack Developer", "interview_type": "medium", "avatar_type": "lina", "avatar_face_id": "b9e5fba3-071a-4e35-896e-211c4d6eaa7b", "voice_id": "OYTbf65OHHFELVut7v2H", "avatar_id": "", "room_name": "room_f6d03cc6", "session_id": "485ae4bc9e1749429a16" }, connection_state=CONN_CONNECTED) ctx connect generate Reply... 2025-09-25 113101,120 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,120 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_CAMERA", "SOURCE_SCREENSHARE"], "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,123 - DEBUG livekit.agents - waiting for the remote participant {"identity": "simli-avatar-agent", "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,125 - DEBUG livekit.agents - using audio io:
RoomIO
->
AgentSession
->
TranscriptSynchronizer
->
DataStreamIO
{"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,125 - WARNING livekit.agents - resume_false_interruption is enabled but audio output does not support pause, it will be ignored {"audio_output": "TranscriptSynchronizer", "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,125 - DEBUG livekit.agents - using transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
{"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,125 - DEBUG livekit.agents - using video io:
RoomIO
>
AgentSession
> (none) {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113101,466 - DEBUG livekit.agents - remote participant ready {"identity": "simli-avatar-agent", "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113103,400 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113103,404 - WARNING livekit.agents - failed to synthesize speech, retrying in 0.1s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run raise e File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113105,439 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113105,440 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run raise e File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113109,363 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113109,364 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task await self._run(output_emitter) File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run raise e File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true, "pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113113,366 - WARNING livekit.plugins.elevenlabs - websocket closed unexpectedly {"pid": 374132, "job_id": "AJ_sooCdKfy2CnP"} 2025-09-25 113113,368 - ERROR livekit.agents - Error in _tts_inference_task Traceback (most recent call last): File "/home/dev/Projects/NavigenceAI/NavigenceAI/venv/lib/python3.11/site-packages/livekit/agents/tts/tts.py", line 529, in anext val = await self._event_aiter.__anext__() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ StopAsyncIteration
t
Thanks for sharing the error logs! It looks like the ElevenLabs TTS plugin is running into some unexpected WebSocket closures and an APIStatusError. To help us get to the bottom of this together, could you please check a few things for me? • Is your ElevenLabs API key set up correctly and still valid? • Are there any network restrictions or firewalls that might be blocking WebSocket connections to ElevenLabs? • Have you had a chance to test the connection to ElevenLabs using their API or a direct WebSocket connection? Once we have this info, we’ll be in a much better spot to figure out what’s going on. I’m here to help every step of the way!
b
current very slow, how to update speed to fast
t
Thanks for reaching out! Could you please share a bit more about which part of LiveKit feels slow for you? For example: • Is it the audio or video streaming that’s causing trouble? • Are you noticing delays when agents respond or during TTS synthesis? • Or maybe it’s something specific to a certain plugin or feature? Understanding these details will really help us get to the bottom of the issue and find the best way to improve your experience.
b
Copy code
from dotenv import load_dotenv
import os,aiohttp,json
from livekit import agents
from livekit.agents import WorkerOptions, WorkerType,cli,AutoSubscribe,JobProcess
from livekit.agents import AgentSession, Agent, RoomInputOptions,metrics
from livekit.plugins import (
    openai,
    noise_cancellation,
    simli,
    elevenlabs,
    silero
)
from jinja2 import Template
from livekit.agents.voice import MetricsCollectedEvent
from livekit.agents.metrics import LLMMetrics,STTMetrics,TTSMetrics
from app.core.config import settings


prompt_template=f"""You are an AI interviewer conducting a professional interview. Your interface with users will be voice, so you must avoid usage of unpronounceable punctuation and should use short and concise responses. Deliver the response in plain text without any Markdown or formatting.
 
 You are conducting an interview for the position of {{job_title}} at {{company_name}}. This is a {{interview_type}} interview.
 
 Your role is to:
 1. Conduct a professional, engaging interview
 2. Ask relevant questions based on the position and company
 3. Listen actively to responses and ask follow-up questions
 4. Maintain a friendly but professional tone
 5. Guide the conversation naturally
 6. Provide feedback when appropriate
 7. Keep the interview flowing smoothly
 
 Interview guidelines:
 - Start with a warm welcome and brief introduction
 - Ask 5-7 main questions plus follow-ups
 - Allow the candidate to ask questions at the end
 - Provide constructive feedback
 - Keep responses concise and natural for voice interaction
 - Be encouraging and supportive
 
 Remember: You are speaking, not writing. Use natural speech patterns and avoid complex punctuation or formatting."""

def formate_template(data):
    data=json.loads(data)
    template = Template(prompt_template)
    rendered_prompt = template.render(**data)
    return rendered_prompt

def validate_configuration():
    """Validate that all required configuration is present"""
    missing_configs = []
    
    if not settings.OPENAI_API_KEY:
        missing_configs.append("OPENAI_API_KEY")
    
    if not settings.ELEVENLABS_API_KEY:
        missing_configs.append("ELEVENLABS_API_KEY")
        print("WARNING: ELEVENLABS_API_KEY not found. Will use OpenAI TTS as fallback.")
    
    if not settings.SIMLI_API_KEY:
        missing_configs.append("SIMLI_API_KEY")
        print("WARNING: SIMLI_API_KEY not found. Avatar functionality will be disabled.")
    
    if not settings.LIVEKIT_URL or not settings.LIVEKIT_API_KEY or not settings.LIVEKIT_API_SECRET:
        missing_configs.extend(["LIVEKIT_URL", "LIVEKIT_API_KEY", "LIVEKIT_API_SECRET"])
    
    if missing_configs:
        print(f"Missing required configuration: {', '.join(missing_configs)}")
        print("Please check your .env file and ensure all required API keys are set.")
        return False
    
    print("Configuration validation passed.")
    return True

class Assistant(Agent):
    def __init__(self,ctx) -> None:
        super().__init__(instructions= formate_template(ctx.room.metadata))

def prewarm_process(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load(min_silence_duration=0.3)
    
async def entrypoint(ctx: agents.JobContext):
    # Validate configuration first
    validate_configuration()
    
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    print(f"CTX.Room.Name: {ctx.room.name}")

    metadata=json.loads(ctx.room.metadata)
    # Prefer explicit voice_id from metadata; fallback to gender defaults
    voice_id = metadata.get("voice_id")
    if not voice_id:
        if metadata.get('avatar_type', '').lower()=="female":
            voice_id="21m00Tcm4TlvDq8ikWAM"
        elif metadata.get('avatar_type', '').lower()=="male":
            voice_id="GBv7mTt0atIp3Br8iCZE"
        else:
            voice_id = "21m00Tcm4TlvDq8ikWAM"

    print("Agent Session")
    total_llm_tokens = 0
    total_stt_duration = 0.0
    total_tts_duration = 0.0

    def _on_metrics_collected(event: MetricsCollectedEvent):
        # Use 'nonlocal' to modify variables from the outer scope
        nonlocal total_llm_tokens, total_stt_duration, total_tts_duration
        
        metrics = event.metrics

        if isinstance(metrics, LLMMetrics):
            # This is the missing block from your previous code
            print("LLM METRICS RECEIVED:", metrics.model_dump())
            tokens_used = metrics.completion_tokens
            total_llm_tokens += tokens_used
            print(f"Tokens Used in this turn: {tokens_used}")

        elif isinstance(metrics, STTMetrics):
            total_stt_duration += metrics.audio_duration

        elif isinstance(metrics, TTSMetrics):
            total_tts_duration += metrics.audio_duration
    async def print_final_summary():
        print("\n--- FINAL USAGE SUMMARY ---")
        print(f"Total LLM Tokens Used: {total_llm_tokens}")
        print(f"Total STT Audio Duration: {total_stt_duration:.2f} seconds")
        print(f"Total TTS Audio Duration: {total_tts_duration:.2f} seconds")
        print("---------------------------\n")

    # Use only VAD to avoid turn-detector model requirement
    # Initialize TTS with better error handling
    tts_instance = None
    try:
        if settings.ELEVENLABS_API_KEY:
            print(f"Initializing ElevenLabs TTS with voice_id: {voice_id}")
            tts_instance = elevenlabs.TTS(
                api_key=settings.ELEVENLABS_API_KEY,
                voice_id=voice_id,
                # Add connection timeout and retry settings
                timeout=30.0,
                retry_attempts=3
            )
        else:
            print("ELEVENLABS_API_KEY not found, using OpenAI TTS as fallback")
            tts_instance = openai.TTS(api_key=settings.OPENAI_API_KEY)
    except Exception as e:
        print(f"Failed to initialize ElevenLabs TTS: {e}")
        print("Falling back to OpenAI TTS")
        tts_instance = openai.TTS(api_key=settings.OPENAI_API_KEY)
    
    session = AgentSession(
        turn_detection=None,
        vad=ctx.proc.userdata["vad"],
        stt=openai.STT(api_key=settings.OPENAI_API_KEY),
        tts=tts_instance,
        allow_interruptions=True,
        llm=openai.LLM(
            model="gpt-4o-mini",  # or gpt-4 / gpt-3.5-turbo depending on your needs
            api_key=settings.OPENAI_API_KEY
        ),
        max_endpointing_delay=0.3
    )
    async with aiohttp.ClientSession() as http_session:
        enable_avatar = os.environ.get("SIMLI_ENABLE_AVATAR", "0") in ["1", "true", "True"]
        avatar = None
        if enable_avatar:
            avatar_face_id = metadata.get("avatar_face_id") or metadata.get("face_id") or "cace3ef7-a4c4-425d-a8cf-a5358eb0c427"
            avatar = simli.AvatarSession(
                simli_config=simli.SimliConfig(
                    api_key=settings.SIMLI_API_KEY,
                    face_id=avatar_face_id,
                ),
            )


    try:
        if avatar is not None:
            print("Avatar Starting...")
            await avatar.start(session, room=ctx.room)
        else:
            print("SIMLI_ENABLE_AVATAR disabled. Running audio-only agent.")
    except Exception as e:
        print(f"Failed to start avatar: {e}")
        if avatar is not None:
            print("Trying again with hardcoded conversation_id (NOT recommended for production)")
            try:
                avatar.conversation_id = metadata.get("session_id")
                await avatar.start(session, room=ctx.room)
            except Exception as e2:
                print(f"Avatar failed again: {e2}")
                print("Continuing with audio-only mode")
                avatar = None

    print("Agent Start")
    print(f"Room:{ctx.room}")

    print("ctx connect")
    await ctx.connect()
    session.on("metrics_collected", _on_metrics_collected)
    ctx.add_shutdown_callback(print_final_summary)

    await session.start(
        room=ctx.room,
        agent=Assistant(ctx),  
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
            video_enabled=True,
            audio_enabled=True   
            
        ),
    )
    print("generate Reply...")
    greeting = f"""Hello! Welcome to your interview for the {metadata['job_title']} position at {metadata['company_name']}. I'm your AI interviewer, and I'm excited to learn more about you today. Let's start with a brief introduction. Can you tell me about yourself and what interests you about this role?"""
    try:
        await session.say(greeting)
    except Exception as e:
        print(f"Failed to say greeting: {e}")
        # Continue without greeting if TTS fails

if __name__ == "__main__":
    # agent_name ="Test"
    agent_name =os.environ["AGENT_NAME"]
    print(f"Agent_Name in creation: {agent_name}, Type: {type(agent_name)}")
    opts = WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=prewarm_process,
        worker_type=WorkerType.ROOM,
        agent_name=agent_name,
        initialize_process_timeout=90
    )    
    
    cli.run_app(opts)
t
To help your LiveKit agent run faster and smoother, here are some friendly tips you might find useful: 1. Enable Preemptive Speech Generation: This means your agent can start crafting responses even before the user finishes speaking, which helps cut down waiting time. You can do this by using the
preemptive_generation
parameter in
AgentSession
. 2. Use Fast "Pre-Response" Fillers: While the main response is being prepared, your agent can quickly say things like "Let me think..." using a lightweight model—this keeps the conversation flowing naturally. 3. Optimize Network Proximity: Try to deploy your agent close to the services it uses (like LLM, STT, TTS) to reduce any network lag. 4. Monitor Metrics: Keep an eye on important performance indicators such as Time To First Token (TTFT) and latency for STT and TTS using the Agents Metrics API—this helps you spot and address any slowdowns. 5. Reduce Connection Setup Time: Using long-expiration tokens and dispatching agents during token generation can help minimize any idle waiting periods. 6. Optimize Data Loading: Preloading static data with the
prewarm
function and passing user-specific data through metadata can speed up initialization. 7. Leverage LiveKit Cloud: Deploying on LiveKit Cloud brings handy features like stateful load balancing, elastic scaling, and operational observability that boost performance. These steps can really make your agent feel more responsive and efficient. If you’d like, I’d be happy to walk you through any of these tips in more detail—just let me know! Sources: Docs::Agents | Agent Testing &amp; Evaluation | livekit/livekit_composite | DeepWiki | Docs::Agents | Deploy and scale agents on LiveKit Cloud | Agent speech and audio | LiveKit Docs