ElevenLabs STT stream does not reconnect after mid-stream WebSocket disconnection
Bug Description
When using elevenlabs.STT (version 1.3.6) in streaming mode, if the WebSocket connection drops mid-stream (e.g., due to network instability or ElevenLabs service issues), the SpeechStream raises APIStatusError with retryable=True but does not attempt to reconnect. The stream effectively dies, and my transcription becomes non-English characters. I also see LiveKit start repeating the same sentence (I am not sure this repeat behavior is related to stream issue).
Current Behavior
SpeechStream._run()establishes WebSocket connection via_connect_ws()recv_taskmonitors incoming messages- When WebSocket closes unexpectedly,
recv_taskraises:APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True) - Exception propagates through
task.result()and breaks out of thewhile Trueloop - Stream ends without reconnection attempt
- AgentSession receives error with
recoverable=True
Expected Behavior
Either:
-
Plugin-level:
SpeechStreamshould catch connection errors and attempt reconnection (similar to how_reconnect_eventtriggers reconnection forupdate_options) -
Framework-level:
AgentSessionshould recreate STT streams when receiving recoverable STT errors
Relevant Code
In stt.py, the _run method's reconnection logic only triggers on _reconnect_event:
async def _run(self) -> None:
while True:
try:
ws = await self._connect_ws()
# ... tasks created ...
for task in done:
if task != wait_reconnect_task:
task.result() # <-- Exception raised here breaks out of loop
if wait_reconnect_task not in done:
break # <-- Exits loop on error
self._reconnect_event.clear() # <-- Only reconnects if event was set
Reproduction Steps
- Configure
AgentSessionwithelevenlabs.STT, setrealtimetoTrueto useScribe V2 - Start a voice conversation
- Just talk with agent for a few minutes in LiveKit playground
- Observe error in logs with
retryable=True, and my transcription becomes non-English characters.
This is how I create a session with ElevenLabs STT:
from livekit.plugins import elevenlabs,
params = {"use_realtime": True}
stt = elevenlabs.STT(**params)
...
session = AgentSession[ParticipantData](
userdata=participant_data,
stt=stt, # scribe v2
llm=llm, # OpenAI "gpt-5" model
tts=tts, # eleven_multilingual_v2
)
Operating System
MacOS
Models Used
Scribe V2
Package Versions
livekit-agents~=1.3.6
livekit-api~=1.1.0
livekit-plugins-elevenlabs~=1.3.6
Python: 3.11
Screenshots and Recordings
Thanks for opening the issue.
Reconnection and retry are handled differently:
- retry when there is an exception: this is handled by
_main_taskinlivekit-agents/livekit/agents/stt/stt.py, and a reconnection is included when triggering_runagain; Additionally, we don't check theretryableflag in STT as we always retry, unlike other components. - reconnection: when STT options changes without any exception and it happens within an attempt/try.
So the error, if any, must be from somewhere else. If you could provide any logs that occurred after the API error, it would be very helpful.
Hi @chenghao-mou ,
Thanks for working on it. Here is the log which I found in the test:
{"logger": "agent-voice", "severity": "ERROR", "message": "LiveKit error. recoverable=True, error=type='stt_error' timestamp=1769135835.2023711 label='livekit.plugins.elevenlabs.stt.STT' error=APIStatusError('ElevenLabs STT connection closed unexpectedly') recoverable=True", "caller_method": "on_error", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1267]", "asctime": "2026-01-22 18:37:15,202", "msecs": 202.0, "version": "v2601.02.tony-dev", "exc_info": "
Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 289, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 370, in _run
task.result()
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)
", "worker_id": "AW_8QKnnwmQAz46", "room_name": "voice-tony-dev-01", "product_area": "Default"}
I also see some other error logs, not sure these logs are related to this issue, do you want me post it here as well?
Yes, please. Any subsequent logs that might tell us how the system reacted to that error.
Here you are:
{"logger": "livekit.plugins.elevenlabs", "severity": "ERROR", "message": "Error in recv_task
Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "caller_method": "async_fn_logs", "line": "[/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py:21]", "asctime": "2026-01-26 12:04:42,779", "msecs": 779.0, "version": "v2601.02.tony-dev", "exc_info": "livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005", "pid": 22638, "job_id": "AJ_7TgNYxMm8SJ3", "room_id": "RM_TfMgWyWR7GhU"}
{"logger": "agent-voice", "severity": "ERROR", "message": "LiveKit error. recoverable=True, error=type='stt_error' timestamp=1769457882.7820082 label='agent_worker.agents.shared.voice_arch_config.ElevenLabsSTTWithRetry' error=APIStatusError('ElevenLabs STT connection closed unexpectedly') recoverable=True", "caller_method": "on_error", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1267]", "asctime": "2026-01-26 12:04:42,782", "msecs": 782.0, "version": "v2601.02.tony-dev", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 289, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 370, in _run
task.result()
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "livekit.agents", "severity": "WARNING", "message": "failed to recognize speech, retrying in 2.0s
Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 289, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 370, in _run
task.result()
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "caller_method": "_main_task", "line": "[/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py:303]", "asctime": "2026-01-26 12:04:42,784", "msecs": 784.0, "version": "v2601.02.tony-dev", "exc_info": "livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "tts": "agent_worker.agents.shared.voice_arch_config.ElevenLabsSTTWithRetry", "attempt": 1, "streamed": true, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005", "pid": 22638, "job_id": "AJ_7TgNYxMm8SJ3", "room_id": "RM_TfMgWyWR7GhU"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='llm_metrics' label='livekit.plugins.openai.llm.LLM' request_id='chatcmpl-D2N7CaGs0ivbyP80x9jkt37oWfJ9e' timestamp=1769457884.2794182 duration=2.1306554580805823 ttft=1.855894458014518 cancelled=False completion_tokens=38 prompt_tokens=1505 prompt_cached_tokens=1408 total_tokens=1543 tokens_per_second=17.834887314081556 speech_id='speech_49464bade571' metadata=Metadata(model_name='gpt-5', model_provider='api.openai.com')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:44,279", "msecs": 279.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:44,281", "msecs": 281.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='tts_metrics' label='livekit.plugins.elevenlabs.tts.TTS' request_id='35a5646f9489' timestamp=1769457885.9615848 ttfb=0.5984409999800846 duration=1.8371458330657333 audio_duration=5.746938775510203 cancelled=False characters_count=122 streamed=True segment_id='35a5646f9489' speech_id='speech_49464bade571' metadata=Metadata(model_name='eleven_multilingual_v2', model_provider='ElevenLabs')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:45,962", "msecs": 962.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:45,963", "msecs": 963.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracking conversation item added for worker_type: voice,lk_event: type='conversation_item_added' item=ChatMessage(id='item_01b096924a40', type='message', role='assistant', content=['I\u2019m sorry, but I can\u2019t assist with that right now.\
\
Would you like me to transfer you to a live operator for further help?'], interrupted=False, transcript_confidence=None, extra={}, metrics={'started_speaking_at': 1769457884.724566, 'stopped_speaking_at': 1769457890.473176, 'llm_node_ttft': 1.8568385420367122, 'tts_node_ttfb': 0.7179128329735249}, created_at=1769457882.1781461, hash=None) created_at=1769457890.47331:conversation_id: *********0005", "caller_method": "on_conversation_message", "line": "[/Users/tony/src/python-core/services/agent_worker/services/tracking.py:345]", "asctime": "2026-01-26 12:04:50,473", "msecs": 473.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-assistant-turn-with-plain-text-transcript", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:50,474", "msecs": 474.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Guardian: Recommended action: TERMINATE due to {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats have exceeded the termination threshold.", "caller_method": "get_base_guardian_response", "line": "[/Users/tony/src/python-core/common/guardian/src/dialpad/guardian/__init__.py:514]", "asctime": "2026-01-26 12:04:50,476", "msecs": 476.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Guardian: Response for event agent_message: recommended_action=<RecommendedAction.TERMINATE: 'terminate'> threat_types={<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} reasoning=\"This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.\" highest_threat_assessment=None", "caller_method": "process_event", "line": "[/Users/tony/src/python-core/common/guardian/src/dialpad/guardian/__init__.py:215]", "asctime": "2026-01-26 12:04:50,477", "msecs": 477.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "WARNING", "message": "THREAT DETECTED: {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} recommended action: RecommendedAction.TERMINATE - This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.", "caller_method": "take_action", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:118]", "asctime": "2026-01-26 12:04:50,477", "msecs": 477.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "WARNING", "message": "TERMINATING CONVERSATION due to {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>}", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:183]", "asctime": "2026-01-26 12:04:50,477", "msecs": 477.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "[GUARDIAN_TERMINATE] Emitting terminate_conversation event to agent", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:186]", "asctime": "2026-01-26 12:04:50,477", "msecs": 477.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "[GUARDIAN_TERMINATE] Event emitted successfully, agent should handle termination", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:195]", "asctime": "2026-01-26 12:04:50,478", "msecs": 478.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "VoiceOrchestratorAgent terminate conversation: This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.", "caller_method": "terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/agent.py:181]", "asctime": "2026-01-26 12:04:50,480", "msecs": 480.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='llm_metrics' label='livekit.plugins.openai.llm.LLM' request_id='chatcmpl-D2N7KWMi7DeIhOCLXPavwac08Tx3z' timestamp=1769457891.9121668 duration=1.4267677079187706 ttft=1.11668550001923 cancelled=False completion_tokens=38 prompt_tokens=1540 prompt_cached_tokens=1408 total_tokens=1578 tokens_per_second=26.633627737083206 speech_id='speech_7bf57119634d' metadata=Metadata(model_name='gpt-5', model_provider='api.openai.com')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:51,912", "msecs": 912.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:51,913", "msecs": 913.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='tts_metrics' label='livekit.plugins.elevenlabs.tts.TTS' request_id='bd5b0acaab45' timestamp=1769457893.3656 ttfb=0.5595163749530911 duration=1.5542094999691471 audio_duration=5.433469387755101 cancelled=False characters_count=122 streamed=True segment_id='bd5b0acaab45' speech_id='speech_7bf57119634d' metadata=Metadata(model_name='eleven_multilingual_v2', model_provider='ElevenLabs')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:53,365", "msecs": 365.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:53,366", "msecs": 366.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracking conversation item added for worker_type: voice,lk_event: type='conversation_item_added' item=ChatMessage(id='item_b28fb2bb9d73', type='message', role='assistant', content=['I\u2019m sorry, but I can\u2019t assist with that right now.\
\
Would you like me to transfer you to a live operator for further help?'], interrupted=False, transcript_confidence=None, extra={}, metrics={'started_speaking_at': 1769457892.372731, 'stopped_speaking_at': 1769457897.806428, 'llm_node_ttft': 1.1180620410013944, 'tts_node_ttfb': 0.7685435829916969}, created_at=1769457890.508277, hash=None) created_at=1769457897.8064902:conversation_id: *********0005", "caller_method": "on_conversation_message", "line": "[/Users/tony/src/python-core/services/agent_worker/services/tracking.py:345]", "asctime": "2026-01-26 12:04:57,806", "msecs": 806.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-assistant-turn-with-plain-text-transcript", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Guardian: Recommended action: TERMINATE due to {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats have exceeded the termination threshold.", "caller_method": "get_base_guardian_response", "line": "[/Users/tony/src/python-core/common/guardian/src/dialpad/guardian/__init__.py:514]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Guardian: Response for event agent_message: recommended_action=<RecommendedAction.TERMINATE: 'terminate'> threat_types={<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} reasoning=\"This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.\" highest_threat_assessment=None", "caller_method": "process_event", "line": "[/Users/tony/src/python-core/common/guardian/src/dialpad/guardian/__init__.py:215]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "WARNING", "message": "THREAT DETECTED: {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} recommended action: RecommendedAction.TERMINATE - This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.", "caller_method": "take_action", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:118]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "WARNING", "message": "TERMINATING CONVERSATION due to {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>}", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:183]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "[GUARDIAN_TERMINATE] Emitting terminate_conversation event to agent", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:186]", "asctime": "2026-01-26 12:04:57,807", "msecs": 807.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "[GUARDIAN_TERMINATE] Event emitted successfully, agent should handle termination", "caller_method": "_terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/guardian_action_handler.py:195]", "asctime": "2026-01-26 12:04:57,808", "msecs": 808.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "VoiceOrchestratorAgent terminate conversation: This conversation has exceeded the termination threshold of 90 for {<ThreatType.PROMPT_INJECTION: 'prompt_injection'>} threats.", "caller_method": "terminate_conversation", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/agent.py:181]", "asctime": "2026-01-26 12:04:57,808", "msecs": 808.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='llm_metrics' label='livekit.plugins.openai.llm.LLM' request_id='chatcmpl-D2N7Suqen11u2fTyGFgWvSxNYu933' timestamp=1769457898.942639 duration=1.1317952499957755 ttft=0.7437123750569299 cancelled=False completion_tokens=38 prompt_tokens=1575 prompt_cached_tokens=1536 total_tokens=1613 tokens_per_second=33.57497745298174 speech_id='speech_0ee28120c610' metadata=Metadata(model_name='gpt-5', model_provider='api.openai.com')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:58,942", "msecs": 942.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:58,943", "msecs": 943.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "INFO", "message": "Metrics collected for conversation_id: *********0005: type='tts_metrics' label='livekit.plugins.elevenlabs.tts.TTS' request_id='c2b684549aac' timestamp=1769457899.814753 ttfb=0.43182824994437397 duration=1.135456082993187 audio_duration=5.694693877551019 cancelled=False characters_count=122 streamed=True segment_id='c2b684549aac' speech_id='speech_0ee28120c610' metadata=Metadata(model_name='eleven_multilingual_v2', model_provider='ElevenLabs')", "caller_method": "_on_metrics_collected", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1344]", "asctime": "2026-01-26 12:04:59,815", "msecs": 815.0, "version": "v2601.02.tony-dev", "metadata": {"m-org-id": "******a8af", "m-app-id": "*******efd9", "m-conversation-id": "*********0005"}, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracing span: AgentEval-session-metrics-collected", "caller_method": "trace_span", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1208]", "asctime": "2026-01-26 12:04:59,815", "msecs": 815.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "livekit.plugins.elevenlabs", "severity": "ERROR", "message": "Error in recv_task
Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "caller_method": "async_fn_logs", "line": "[/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py:21]", "asctime": "2026-01-26 12:05:02,950", "msecs": 950.0, "version": "v2601.02.tony-dev", "exc_info": "livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005", "pid": 22638, "job_id": "AJ_7TgNYxMm8SJ3", "room_id": "RM_TfMgWyWR7GhU"}
{"logger": "agent-voice", "severity": "ERROR", "message": "LiveKit error. recoverable=True, error=type='stt_error' timestamp=1769457902.952393 label='agent_worker.agents.shared.voice_arch_config.ElevenLabsSTTWithRetry' error=APIStatusError('ElevenLabs STT connection closed unexpectedly') recoverable=True", "caller_method": "on_error", "line": "[/Users/tony/src/python-core/services/agent_worker/agents/common/worker.py:1267]", "asctime": "2026-01-26 12:05:02,952", "msecs": 952.0, "version": "v2601.02.tony-dev", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 289, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 370, in _run
task.result()
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
{"logger": "livekit.agents", "severity": "WARNING", "message": "failed to recognize speech, retrying in 2.0s
Traceback (most recent call last):
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 289, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 370, in _run
task.result()
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 337, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "caller_method": "_main_task", "line": "[/Users/tony/src/python-core/.venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py:303]", "asctime": "2026-01-26 12:05:02,953", "msecs": 953.0, "version": "v2601.02.tony-dev", "exc_info": "livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "tts": "agent_worker.agents.shared.voice_arch_config.ElevenLabsSTTWithRetry", "attempt": 2, "streamed": true, "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005", "pid": 22638, "job_id": "AJ_7TgNYxMm8SJ3", "room_id": "RM_TfMgWyWR7GhU"}
{"logger": "agent-voice", "severity": "DEBUG", "message": "Tracking conversation item added for worker_type: voice,lk_event: type='conversation_item_added' item=ChatMessage(id='item_d7a989e3484c', type='message', role='assistant', content=['I\u2019m sorry, but I can\u2019t assist with that right now.\
\
Would you like me to transfer you to a live operator for further help?'], interrupted=False, transcript_confidence=None, extra={}, metrics={'started_speaking_at': 1769457899.1118941, 'stopped_speaking_at': 1769457904.808406, 'llm_node_ttft': 0.7441889999900013, 'tts_node_ttfb': 0.5563522499287501}, created_at=1769457897.830747, hash=None) created_at=1769457904.808542:conversation_id: *********0005", "caller_method": "on_conversation_message", "line": "[/Users/tony/src/python-core/services/agent_worker/services/tracking.py:345]", "asctime": "2026-01-26 12:05:04,808", "msecs": 808.0, "version": "v2601.02.tony-dev", "worker_id": "AW_tTk6DSufVyzp", "room_name": "voice-tony-dev-02", "org_id": "******a8af", "app_id": "*******efd9", "product_area": "Default", "conversation_id": "*********0005"}
... ...
By the way, are you able to reproduce this error on your side? I can constantly reproduce it after talking in LiveKit playground for 5 minutes.
Thanks for the logs.
I could not reproduce this using the basic agent with 11labs stt and tts.
I don't see any DEBUG logs coming from livekit.agents, which makes it harder to understand what happened.
Here is what you can try next:
- try the basic agent example with 11labs and share the logs
- try upgrading to the latest versions
- double check your API key and usage so that it is still valid
Hi @chenghao-mou ,
I can't reproduce the issue with basic agent, but I can reproduce the issue with following tiny demo agent (which is similar to our agent's behavior):
import asyncio
from collections.abc import AsyncIterable
from dataclasses import dataclass, field
from datetime import date
from typing import Any, Optional
import os
from dotenv import load_dotenv
from livekit.plugins.openai import LLM
from livekit import agents
from livekit.agents.llm import ChatChunk, RawFunctionTool
from livekit.agents import (
AgentSession,
Agent,
AgentTask,
ChatContext,
ConversationItemAddedEvent,
FunctionToolsExecutedEvent,
ModelSettings,
RoomInputOptions,
RoomOutputOptions,
RunContext,
function_tool,
FunctionTool,
)
from livekit.plugins import (
openai, elevenlabs
)
from openai import realtime
# from phoenix.otel import register
# By default, it won't override the system environment variables
# with the variables from the `.env` file.
load_dotenv()
# Update this with your self-hosted endpoint
PHOENIX_ENDPOINT = "http://0.0.0.0:6006/v1/traces"
# configure the Phoenix tracer
tracer_provider = register(
project_name="livekit-app", # Default is 'default'
auto_instrument=True,
endpoint=PHOENIX_ENDPOINT,
)
tracer = tracer_provider.get_tracer(__name__)
@dataclass
class UserData:
agents: dict[str, Agent] = field(default_factory=dict)
prev_agent: Optional[Agent] = None
# user_request is a short summary of the current user request
user_request: Optional[str] = None
RunContext_T = RunContext[UserData]
class WeatherSkill(Agent):
"""This AgentTask is a Skill AgentTask that runs a skill."""
def __init__(self, chat_ctx: Optional[ChatContext] = None) -> None:
self._greeting = ("You are a helpful voice AI assistant that can help "
"user with weather information request. "
"If the user did not provide a location, ask them "
"which location they would like to know the weather "
"about. Only reply in English. You must call the "
"function tool lookup_weather on each user input that "
"contains a request that seeks your help. "
"If the request is fulfilled, let the user "
"know and call the function tool skill_finished_successfully."
)
super().__init__(
instructions=self._greeting,
chat_ctx=chat_ctx,
)
async def on_enter(self):
"""Handler called when the agent enters a session.
Generates an initial reply using the greeting message when the agent
is added to the session.
"""
print(f"{self}: on_enter")
userdata: UserData = self.session.userdata
chat_ctx = self.chat_ctx.copy()
# add the previous agent's chat history to the current agent
if isinstance(userdata.prev_agent, Agent):
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
exclude_instructions=True,
exclude_function_call=False
).truncate(max_items=50)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if
item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
await self.update_chat_ctx(chat_ctx)
await self.session.generate_reply(
instructions="Repeat user's request from the context word by word "
"and ask the user whether it is accurate.", # self._greeting,
allow_interruptions=False,
)
@function_tool()
async def lookup_weather(
self,
context: RunContext,
location: str,
) -> dict[str, Any]:
"""Use this function when the user wants to look up
weather information for a given location.
Args:
context: RunContext
location: The location to look up weather information for.
"""
return {"location": location, "weather": "sunny", "temperature_f": 70}
@function_tool()
async def skill_finished_successfully(self) -> None:
"""Use this when the user request is fulfilled successfully."""
await self.session.generate_reply(
instructions="Ask the user if they have anything else that needs help."
)
self.session.userdata.prev_agent = self.session.current_agent
return EntrypointAgent(chat_ctx=self.chat_ctx)
@function_tool()
async def skill_finished_incorrectly(self) -> None:
"""Use this when the user request cannot be done."""
await self.session.generate_reply(
instructions="Inform the user that you are unable to proceed and will end the call."
)
self.session.shutdown()
class EntrypointAgent(Agent):
def __init__(self, chat_ctx: Optional[ChatContext] = None) -> None:
super().__init__(
instructions=("You are a helpful voice AI assistant. "
"Only reply in English. You can call the "
"function tool to_weather_skill if the user asks for "
"weather information. "
"If the request is already fulfilled, let the user "
"know."
),
chat_ctx=chat_ctx,
)
async def on_enter(self):
await self.session.generate_reply(instructions="Greet the user by saying 'Hi, how can I help you?'")
@function_tool()
async def to_weather_skill(self,
context: RunContext_T,
user_request: str):
"""Called when user wants to search for weather information.
This function handles transitioning to a weather skill agent task
that will help the user query weather information.
Args:
context: RunContext,
user_request: A short summary of user's request.
"""
# AgentTask handoff
self.session.userdata.prev_agent = self.session.current_agent
self.session.userdata.user_request = user_request
return WeatherSkill(chat_ctx=self.chat_ctx)
@function_tool()
async def hangup(self) -> None:
"""Use this when the user request is done."""
await self.session.generate_reply(
instructions="Inform the user that you are will end the call."
)
self.session.shutdown()
async def entrypoint(ctx: agents.JobContext):
userdata = UserData()
userdata.agents.update(
{
"EntrypointAgent": EntrypointAgent(),
}
)
llm_model="gpt-5.1"
stt = elevenlabs.STT(
api_key=os.environ.get("ELEVEN_API_KEY"),
use_realtime=True
)
if not stt.capabilities.streaming:
raise ValueError("Streaming is required for this agent.")
else:
print(f"STT model: {stt.model}")
session = AgentSession[UserData](
userdata=userdata,
llm=openai.LLM(
api_key=os.environ.get("OPENAI_API_KEY"),
model=llm_model,
),
stt=stt,
tts=elevenlabs.TTS(
api_key=os.environ.get("ELEVEN_API_KEY"),
model="eleven_multilingual_v2",
),
)
@session.on("conversation_item_added")
def on_conversation_item_added(ev: ConversationItemAddedEvent):
print(f"\n {session.current_agent.__class__} ====== ConversationItemAddedEvent:", ev)
@session.on("function_tools_executed")
def on_function_tools_executed(ev: FunctionToolsExecutedEvent):
ev = ev.zipped()
print(f"\n {session.current_agent.__class__} ====== FunctionToolsExecutedEvent:", ev)
await session.start(
room=ctx.room,
agent=userdata.agents["EntrypointAgent"], # agent's on_enter is called here immediately
room_input_options=RoomInputOptions(
text_enabled=True,
audio_enabled=True
),
room_output_options=RoomOutputOptions(
# transcription_enabled=True,
# audio_enabled=False,
)
)
await ctx.connect()
if __name__ == "__main__":
agents.cli.run_app(
agents.WorkerOptions(
entrypoint_fnc=entrypoint,
)
)
The steps to reproduce:
- Run the tiny agent:
python tiny_agent_with_function_tool.py start - Start a conversation with LiveKit playground
- When agent is talking, hang up the call (click "Disconnect" button)
- You may need to repeat step 2 and 3 many times, then you will see
ElevenLabs STT connection closed unexpectedlyerror in console - Agent will keep talking and repeat the same information. (It looks like agent goes to a bad state and enters a infinity loop)
I tried the latest version, 1.3.12, I also see the similar issue. Here is the error logs I see in the test for 1.3.12:
{"message": "Error in _llm_inference_task
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 101, in map_httpcore_exceptions
yield
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 271, in __aiter__
async for part in self._httpcore_stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/connection_pool.py\", line 407, in __aiter__
raise exc from None
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/connection_pool.py\", line 403, in __aiter__
async for part in self._stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 342, in __aiter__
raise exc
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 334, in __aiter__
async for chunk in self._connection._receive_response_body(**kwargs):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 203, in _receive_response_body
event = await self._receive_event(timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 217, in _receive_event
data = await self._network_stream.read(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_backends/anyio.py\", line 32, in read
with map_exceptions(exc_map):
File \"/Users/tony/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py\", line 155, in __exit__
self.gen.throw(typ, value, traceback)
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_exceptions.py\", line 14, in map_exceptions
raise to_exc(exc) from exc
httpcore.ReadTimeout
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 311, in _run
async for chunk in stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 148, in __aiter__
async for item in self._iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 162, in __stream__
async for sse in iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 152, in _iter_events
async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 304, in aiter_bytes
async for chunk in self._aiter_chunks(iterator):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 315, in _aiter_chunks
async for chunk in iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_models.py\", line 997, in aiter_bytes
async for raw_bytes in self.aiter_raw():
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_models.py\", line 1055, in aiter_raw
async for raw_stream_bytes in self.stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_client.py\", line 176, in __aiter__
async for chunk in self._stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 270, in __aiter__
with map_httpcore_exceptions():
File \"/Users/tony/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py\", line 155, in __exit__
self.gen.throw(typ, value, traceback)
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 118, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ReadTimeout
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 131, in _llm_inference_task
async for chunk in llm_node:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 418, in llm_node
async for chunk in stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 354, in __anext__
raise exc # noqa: B904
^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 181, in _traceable_main_task
await self._main_task()
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 200, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 344, in _run
raise APIConnectionError(retryable=retryable) from e
livekit.agents._exceptions.APIConnectionError: Connection error. (body=None, retryable=False)", "level": "ERROR", "name": "livekit.agents", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 101, in map_httpcore_exceptions
yield
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 271, in __aiter__
async for part in self._httpcore_stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/connection_pool.py\", line 407, in __aiter__
raise exc from None
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/connection_pool.py\", line 403, in __aiter__
async for part in self._stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 342, in __aiter__
raise exc
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 334, in __aiter__
async for chunk in self._connection._receive_response_body(**kwargs):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 203, in _receive_response_body
event = await self._receive_event(timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_async/http11.py\", line 217, in _receive_event
data = await self._network_stream.read(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_backends/anyio.py\", line 32, in read
with map_exceptions(exc_map):
File \"/Users/tony/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py\", line 155, in __exit__
self.gen.throw(typ, value, traceback)
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpcore/_exceptions.py\", line 14, in map_exceptions
raise to_exc(exc) from exc
httpcore.ReadTimeout
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 311, in _run
async for chunk in stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 148, in __aiter__
async for item in self._iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 162, in __stream__
async for sse in iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 152, in _iter_events
async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 304, in aiter_bytes
async for chunk in self._aiter_chunks(iterator):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/openai/_streaming.py\", line 315, in _aiter_chunks
async for chunk in iterator:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_models.py\", line 997, in aiter_bytes
async for raw_bytes in self.aiter_raw():
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_models.py\", line 1055, in aiter_raw
async for raw_stream_bytes in self.stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_client.py\", line 176, in __aiter__
async for chunk in self._stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 270, in __aiter__
with map_httpcore_exceptions():
File \"/Users/tony/.pyenv/versions/3.11.2/lib/python3.11/contextlib.py\", line 155, in __exit__
self.gen.throw(typ, value, traceback)
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/httpx/_transports/default.py\", line 118, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ReadTimeout
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 131, in _llm_inference_task
async for chunk in llm_node:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 418, in llm_node
async for chunk in stream:
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 354, in __anext__
raise exc # noqa: B904
^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 181, in _traceable_main_task
await self._main_task()
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 200, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 344, in _run
raise APIConnectionError(retryable=retryable) from e
livekit.agents._exceptions.APIConnectionError: Connection error. (body=None, retryable=False)", "pid": 46897, "job_id": "AJ_3zUbjow42m7v", "room_id": "RM_msAJze4BjVyp", "timestamp": "2026-01-29T02:59:32.952051+00:00"}
{"message": "Error in recv_task
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 385, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "level": "ERROR", "name": "livekit.plugins.elevenlabs", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 385, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "pid": 46896, "job_id": "AJ_EhBuqxzzLPLy", "room_id": "RM_dmSMYF3fcaEW", "timestamp": "2026-01-29T02:59:33.389114+00:00"}
{"message": "failed to recognize speech, retrying in 0.1s
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 317, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 418, in _run
task.result()
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 385, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "level": "WARNING", "name": "livekit.agents", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/stt/stt.py\", line 317, in _main_task
return await self._run()
^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 418, in _run
task.result()
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 385, in recv_task
raise APIStatusError(message=\"ElevenLabs STT connection closed unexpectedly\")
livekit.agents._exceptions.APIStatusError: ElevenLabs STT connection closed unexpectedly (status_code=-1, request_id=None, body=None, retryable=True)", "tts": "livekit.plugins.elevenlabs.stt.STT", "attempt": 0, "streamed": true, "pid": 46896, "job_id": "AJ_EhBuqxzzLPLy", "room_id": "RM_dmSMYF3fcaEW", "timestamp": "2026-01-29T02:59:33.392258+00:00"}
Could you please help me analysis why?
I'm also seeing this error
Hi everyone, is there any update for this issue? Is there anything that I can help?
Thanks for sharing the details. I will try to reproduce this.
Meanwhile, we've updated our codebase to log the error in more detail. Could you try the latest version with >=1.4.1 to see if there is any additional data from the ElevenLabs STT connection closed unexpectedly error?
You may need to repeat step 2 and 3 many times, then you will see ElevenLabs STT connection closed unexpectedly error in console
I tried disconnecting multiple times and couldn't reproduce it. I think you might have just hit 11labs concurrency limits if you were using both STT and TTS at the same time and repeatedly reconnecting.
We’re also seeing related behavior on livekit-agents 1.4.4 / livekit-plugins-elevenlabs 1.4.4 with elevenlabs.STT(model_id="scribe_v2_realtime").
Our setup is slightly different from the original report:
AgentSession(turn_detection="manual")- push-to-talk style RPCs
start_turnenables input audioend_turndisables input audio and callscommit_user_turn(...)
What we’re observing:
- The lesson/session can work normally for a turn.
- While the session is idle / waiting for the next user turn, ElevenLabs STT starts failing with:
ElevenLabs STT connection closed unexpectedlyfailed to recognize speech: ElevenLabs STT connection closed unexpectedly, retrying in ...
- After enough retries, the
AgentSessionis no longer running. - At that point subsequent
start_turn/end_turnRPCs fail with:AgentSession isn't running
So in our case, the practical user-facing issue is:
- STT websocket closes during idle/manual-turn listening periods
- retries happen
- eventually the session dies
- then the next user utterance is not captured because the session is already dead
We also observed a separate behavior that may or may not be related:
- ElevenLabs can emit the same
FINAL_TRANSCRIPTtwice within a single speech segment - without dedupe, LiveKit aggregated that into duplicated user text
- example:
FINAL_TRANSCRIPT text='Good morning, how are you?'FINAL_TRANSCRIPT text='Good morning, how are you?'- completed user turn became
'Good morning, how are you? Good morning, how are you?'
We added temporary raw STT event logging and confirmed the duplicate final transcript was coming from the ElevenLabs STT event stream before app/UI handling.
If useful, I can share a minimal repro pattern for the manual-turn / idle-close case:
- create session with
scribe_v2_realtime - keep one long-lived realtime STT stream open
- disable input audio between turns
- wait idle for ~15-20s between turns
- eventually the websocket closes unexpectedly and repeated retries can kill the session
Hi @chenghao-mou , I got time to revisit this issue today. I upgraded the livekit to version 1.4.5, I still able to see the "connection closed unexpectedly" error, here are the logs which I see in my console:
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.44776491704396904, "audio_duration": 25.94, "pid": 6888, "job_id": "AJ_hFvDNX22piS7", "room_id": "RM_FzZ4Eb5nnoFf", "timestamp": "2026-03-12T00:58:24.882628+00:00"}
{"message": "Error in recv_task
Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 17, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 421, in recv_task
raise APIStatusError(
livekit.agents._exceptions.APIStatusError: message='ElevenLabs STT connection closed unexpectedly', status_code=1000, retryable=True, body=msg.data=1000 msg.extra=''", "level": "ERROR", "name": "livekit.plugins.elevenlabs", "exc_info": "Traceback (most recent call last):
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 17, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/plugins/elevenlabs/stt.py\", line 421, in recv_task
raise APIStatusError(
livekit.agents._exceptions.APIStatusError: message='ElevenLabs STT connection closed unexpectedly', status_code=1000, retryable=True, body=msg.data=1000 msg.extra=''", "pid": 6888, "job_id": "AJ_hFvDNX22piS7", "room_id": "RM_FzZ4Eb5nnoFf", "timestamp": "2026-03-12T00:58:35.564399+00:00"}
This time, I didn't disconnect call multiple times, and I waited for 30 minutes for each test in order to avoid hitting any concurrency limits.
Moreover, it looks like there is a new bug: the new livekit always repeat the STT transcript twice:
Here are the livekit and plugins versions which I used for testing:
livekit>=1.1.2
livekit-agents==1.4.5
livekit-api>=1.1.0
livekit-blingfire>=1.1.0
livekit-plugins-elevenlabs==1.4.5
livekit-plugins-openai==1.4.5
livekit-plugins-turn_detector==1.4.5
livekit-protocol>=1.1.2
Here is the new toy agent for testing:
import os
import logging
from dataclasses import dataclass, field
from typing import Any, Optional
from dotenv import load_dotenv
from livekit import agents
from livekit.agents import (
AgentSession,
Agent,
AgentServer,
ChatContext,
ConversationItemAddedEvent,
FunctionToolsExecutedEvent,
ModelSettings,
room_io,
RunContext,
function_tool,
FunctionTool,
MetricsCollectedEvent,
metrics,
)
from livekit.plugins import (
openai, elevenlabs
)
from livekit.plugins.turn_detector.multilingual import MultilingualModel
logger = logging.getLogger("basic-agent")
# By default, it won't override the system environment variables
# with the variables from the `.env` file.
load_dotenv()
@dataclass
class UserData:
agents: dict[str, Agent] = field(default_factory=dict)
prev_agent: Optional[Agent] = None
# user_request is a short summary of the current user request
user_request: Optional[str] = None
RunContext_T = RunContext[UserData]
class WeatherSkill(Agent):
"""This AgentTask is a Skill AgentTask that runs a skill."""
def __init__(self, chat_ctx: Optional[ChatContext] = None) -> None:
self._greeting = ("You are a helpful voice AI assistant that can help "
"user with weather information request. "
"If the user did not provide a location, ask them "
"which location they would like to know the weather "
"about. Only reply in English. You must call the "
"function tool lookup_weather on each user input that "
"contains a request that seeks your help. "
"If the request is fulfilled, let the user "
"know and call the function tool skill_finished_successfully."
)
super().__init__(
instructions=self._greeting,
chat_ctx=chat_ctx,
)
async def on_enter(self):
"""Handler called when the agent enters a session.
Generates an initial reply using the greeting message when the agent
is added to the session.
"""
print("WeatherSkill: on_enter")
userdata: UserData = self.session.userdata
chat_ctx = self.chat_ctx.copy()
# add the previous agent's chat history to the current agent
if isinstance(userdata.prev_agent, Agent):
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
exclude_instructions=True,
exclude_function_call=False
).truncate(max_items=50)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if
item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
await self.update_chat_ctx(chat_ctx)
await self.session.generate_reply(
instructions="Repeat user's request from the context word by word "
"and ask the user whether it is accurate.",
allow_interruptions=False,
)
@function_tool()
async def lookup_weather(
self,
context: RunContext,
location: str,
) -> dict[str, Any]:
"""Use this function when the user wants to look up
weather information for a given location.
Args:
context: RunContext
location: The location to look up weather information for.
"""
return {"location": location, "weather": "sunny", "temperature_f": 70}
@function_tool()
async def skill_finished_successfully(self) -> None:
"""Use this when the user request is fulfilled successfully."""
await self.session.generate_reply(
instructions="Ask the user if they have anything else that needs help."
)
self.session.userdata.prev_agent = self.session.current_agent
return EntrypointAgent(chat_ctx=self.chat_ctx)
@function_tool()
async def skill_finished_incorrectly(self) -> None:
"""Use this when the user request cannot be done."""
await self.session.generate_reply(
instructions="Inform the user that you are unable to proceed and will end the call."
)
self.session.shutdown()
class EntrypointAgent(Agent):
def __init__(self, chat_ctx: Optional[ChatContext] = None) -> None:
super().__init__(
instructions=("You are a helpful voice AI assistant. "
"Only reply in English. You can call the "
"function tool to_weather_skill if the user asks for "
"weather information. "
"If the request is already fulfilled, let the user "
"know. keep your sentence short."
),
chat_ctx=chat_ctx,
)
async def on_enter(self):
await self.session.generate_reply(instructions="Greet the user by saying 'Hi, how can I help you?'")
@function_tool()
async def to_weather_skill(self,
context: RunContext_T,
user_request: str):
"""Called when user wants to search for weather information.
This function handles transitioning to a weather skill agent task
that will help the user query weather information.
Args:
context: RunContext,
user_request: A short summary of user's request.
"""
# AgentTask handoff
self.session.userdata.prev_agent = self.session.current_agent
self.session.userdata.user_request = user_request
return WeatherSkill(chat_ctx=self.chat_ctx)
@function_tool()
async def hangup(self) -> None:
"""Use this when the user request is done."""
await self.session.generate_reply(
instructions="Inform the user that you are will end the call."
)
self.session.shutdown()
async def entrypoint(ctx: agents.JobContext):
userdata = UserData()
userdata.agents.update(
{
"EntrypointAgent": EntrypointAgent(),
}
)
stt = elevenlabs.STT(
api_key=os.getenv("ELEVEN_API_KEY"),
model_id='scribe_v2_realtime',
)
llm = openai.LLM(
api_key=os.getenv("OPENAI_API_KEY"),
model="gpt-5",
)
tts = elevenlabs.TTS(
api_key=os.getenv("ELEVEN_API_KEY"),
model="eleven_multilingual_v2",
voice_id="hpp4J3VqNfWAUOO0d1Us"
)
if not stt.capabilities.streaming:
raise ValueError("Streaming is required for this agent.")
print(f"STT model: {stt.model}, TTS model: {tts.model}, LLM model: {llm.model}")
session = AgentSession[UserData](
userdata=userdata,
llm=llm,
stt=stt,
tts=tts,
# turn_detection=MultilingualModel(),
)
@session.on("conversation_item_added")
def on_conversation_item_added(ev: ConversationItemAddedEvent):
print(f"\n {session.current_agent.__class__} ====== ConversationItemAddedEvent:", ev)
@session.on("function_tools_executed")
def on_function_tools_executed(ev: FunctionToolsExecutedEvent):
ev = ev.zipped()
print(f"\n {session.current_agent.__class__} ====== FunctionToolsExecutedEvent:", ev)
# log metrics as they are emitted, and total usage after session is over
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
logger.info(f"Usage: {summary}")
# shutdown callbacks are triggered when the session is over
ctx.add_shutdown_callback(log_usage)
await session.start(
agent=EntrypointAgent(),
room=ctx.room,
room_options=room_io.RoomOptions(
audio_input=room_io.AudioInputOptions(
# uncomment to enable the Krisp BVC noise cancellation
# noise_cancellation=noise_cancellation.BVC(),
),
),
)
if __name__ == "__main__":
agents.cli.run_app(
agents.WorkerOptions(
entrypoint_fnc=entrypoint,
)
)
for this bug:
Moreover, it looks like there is a new bug: the new livekit always repeat the STT transcript twice:
After I replace
stt = elevenlabs.STT(
api_key=os.getenv("ELEVEN_API_KEY"),
model_id='scribe_v2_realtime',
)
with
inference.STT("elevenlabs/scribe_v2_realtime")
The repeat issue is fixed, so this is a low priority bug to investigate (you can ignore it in this ticket). Please help me investigate timeout issue first.
Hi @chenghao-mou , for the ElevenLabs STT connection closed unexpectedly Error
Status code 1000 is a normal WebSocket close — not a concurrency limit. Looking at logs, these errors occur after the agent has been speaking for a long time (no user audio being sent). This is most likely an idle timeout on ElevenLabs' side. The WebSocket closes cleanly (1000), the retry mechanism reconnects, and things continue. I am not sure whether we still need patch fix https://github.com/livekit/agents/pull/4614 or not, according logs in my side, I see the STT was reconnected in new liverkit (1.4.5), so is reconnection issue fixed by other pull request?
I also got time to investigate the "duplicate transcription" issue today.
The bug is in _process_stream_event (see: livekit/plugins/elevenlabs/stt.py:520-623) in the ElevenLabs STT plugin:
# 11labs sends both when include_timestamps is True
elif (
message_type == "committed_transcript" and not self._opts.include_timestamps
) or message_type == "committed_transcript_with_timestamps":
# Final committed transcripts - these are sent to the LLM/TTS layer in LiveKit agents
# and trigger agent responses (unlike partial transcripts which are UI-only)
if text:
# Send START_OF_SPEECH if we're not already speaking
if not self._speaking:
self._event_ch.send_nowait(
stt.SpeechEvent(type=SpeechEventType.START_OF_SPEECH)
)
self._speaking = True
# Send FINAL_TRANSCRIPT but keep speaking=True
# Multiple commits can occur within the same speech segment
final_event = stt.SpeechEvent(
type=SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[speech_data],
)
self._event_ch.send_nowait(final_event)
else:
# Empty commit signals end of speech segment (similar to Cartesia's is_final flag)
# This groups multiple committed transcripts into one speech segment
if self._speaking:
self._event_ch.send_nowait(stt.SpeechEvent(type=SpeechEventType.END_OF_SPEECH))
self._speaking = False
elif message_type == "committed_transcript":
# if timestamps are included, these will be ignored above since we are handling committed_transcript_with_timestamps
pass
The comment on line 568 itself documents the issue: "11labs sends both when include_timestamps is True". ElevenLabs sends both committed_transcript AND committed_transcript_with_timestamps for the same speech segment.
The condition on lines 569-571 is:
(message_type == "committed_transcript" and not self._opts.include_timestamps)
or message_type == "committed_transcript_with_timestamps"
When include_timestamps=True, the code correctly handles this — committed_transcript falls through to the elif at line 596 and is skipped (pass), while only committed_transcript_with_timestamps is processed.
But the bug occurs when include_timestamps=False (in my case, the default). If scribe_v2_realtime sends both message types regardless of the include_timestamps parameter (or if its default includes timestamps), then:
committed_transcript→ first condition isTrue→ FINAL_TRANSCRIPT emittedcommitted_transcript_with_timestamps→ second condition is alwaysTrue→ FINAL_TRANSCRIPT emitted again (duplicate!)
Each FINAL_TRANSCRIPT is accumulated via append in livekit/agents/voice/audio_recognition.py:
self._audio_transcript += f" {transcript}"
self._audio_transcript = self._audio_transcript.lstrip()
This is why I see exact duplication: "Hello Hello", "I want to check the weather I want to check the weather", etc.
Why inference.STT doesn't have this problem?
The inference.STT wrapper goes through LiveKit's gateway, which normalizes the transcript events into just two clean types:
elif msg_type == "interim_transcript":
self._process_transcript(data, is_final=False)
elif msg_type == "final_transcript":
self._process_transcript(data, is_final=True)
No possibility of double-processing — one message type, one event.
As temporary work around, I can set include_timestamps=True in STT constructor:
stt = elevenlabs.STT(
api_key=os.getenv("ELEVEN_API_KEY"),
model_id='scribe_v2_realtime',
include_timestamps=True, # test: should fix duplication
)
this will stop the duplication because committed_transcript would be ignored and only committed_transcript_with_timestamps would be processed.
For the proper fix, we should fix the ElevenLabs plugin, and the line 569-571 should be:
elif (
message_type == "committed_transcript" and not self._opts.include_timestamps
) or (message_type == "committed_transcript_with_timestamps" and self._opts.include_timestamps):
inference.LLM issue
I am trying to replacing all my current code with new inference interface (inference.LLM and inference.STT). After I use inference.LLM, I notice that agent becomes super slow, and the log shows some LLM requests get timeout:
/Users/tony/Documents/DAART/test/agents/venv/bin/python -X pycache_prefix=/Users/tony/Library/Caches/JetBrains/PyCharm2025.3/cpython-cache /Applications/PyCharm.app/Contents/plugins/python-ce/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 61098 --file /Users/tony/Documents/DAART/test/agents/basic_agent.py start
import sys; print('Python %s on %s' % (sys.version, sys.platform))
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61099), raddr=('127.0.0.1', 61098)>.
Connected to pydev debugger (build 253.31033.139)
{"message": "starting worker", "level": "INFO", "name": "livekit.agents", "version": "1.4.5", "rtc-version": "1.1.2", "timestamp": "2026-03-17T00:14:31.608251+00:00"}
{"message": "starting inference executor", "level": "INFO", "name": "livekit.agents", "timestamp": "2026-03-17T00:14:31.608495+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46896, "inference": true, "timestamp": "2026-03-17T00:14:31.636876+00:00"}
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61105), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61106), raddr=('127.0.0.1', 61098)>.
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46896, "inference": true, "elapsed_time": 9.26, "timestamp": "2026-03-17T00:14:40.900213+00:00"}
{"message": "HTTP server listening on :8081", "level": "INFO", "name": "livekit.agents", "timestamp": "2026-03-17T00:14:40.908572+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46924, "timestamp": "2026-03-17T00:14:40.925251+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46925, "timestamp": "2026-03-17T00:14:40.925634+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46926, "timestamp": "2026-03-17T00:14:40.925812+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46927, "timestamp": "2026-03-17T00:14:40.926719+00:00"}
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61117), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61118), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61119), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61120), raddr=('127.0.0.1', 61098)>.
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46926, "elapsed_time": 2.38, "timestamp": "2026-03-17T00:14:43.301478+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46925, "elapsed_time": 2.38, "timestamp": "2026-03-17T00:14:43.304063+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46924, "elapsed_time": 2.39, "timestamp": "2026-03-17T00:14:43.311940+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46927, "elapsed_time": 2.39, "timestamp": "2026-03-17T00:14:43.313730+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46929, "timestamp": "2026-03-17T00:14:43.317508+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46930, "timestamp": "2026-03-17T00:14:43.326255+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46931, "timestamp": "2026-03-17T00:14:43.333246+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46932, "timestamp": "2026-03-17T00:14:43.333843+00:00"}
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61139), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61140), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61141), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61142), raddr=('127.0.0.1', 61098)>.
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46929, "elapsed_time": 2.48, "timestamp": "2026-03-17T00:14:45.793745+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46931, "elapsed_time": 2.46, "timestamp": "2026-03-17T00:14:45.794683+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46930, "elapsed_time": 2.49, "timestamp": "2026-03-17T00:14:45.821237+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46932, "elapsed_time": 2.5, "timestamp": "2026-03-17T00:14:45.830039+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46945, "timestamp": "2026-03-17T00:14:45.834680+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46946, "timestamp": "2026-03-17T00:14:45.836665+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46947, "timestamp": "2026-03-17T00:14:45.840820+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46948, "timestamp": "2026-03-17T00:14:45.843018+00:00"}
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61221), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61222), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61223), raddr=('127.0.0.1', 61098)>.
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61224), raddr=('127.0.0.1', 61098)>.
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46947, "elapsed_time": 2.34, "timestamp": "2026-03-17T00:14:48.181556+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46948, "elapsed_time": 2.35, "timestamp": "2026-03-17T00:14:48.188557+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46945, "elapsed_time": 2.35, "timestamp": "2026-03-17T00:14:48.188785+00:00"}
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46946, "elapsed_time": 2.35, "timestamp": "2026-03-17T00:14:48.190506+00:00"}
{"message": "registered worker", "level": "INFO", "name": "livekit.agents", "agent_name": "", "id": "AW_ZNrFd8xmr2X9", "url": "wss://test-ydug3m18.livekit.cloud", "region": "US West B", "protocol": 16, "timestamp": "2026-03-17T00:14:48.440515+00:00"}
{"message": "received job request", "level": "INFO", "name": "livekit.agents", "job_id": "AJ_c3PNLBgtJH3h", "dispatch_id": "AD_mUFf3ZNvAUNf", "room": "room-IXL2-xSVY", "room_id": "RM_pxZnUsKdD6Wy", "agent_name": "", "resuming": false, "enable_recording": false, "timestamp": "2026-03-17T00:14:48.500903+00:00"}
{"message": "initializing process", "level": "INFO", "name": "livekit.agents", "pid": 46951, "timestamp": "2026-03-17T00:14:48.606536+00:00"}
{"message": "STT model: elevenlabs/scribe_v2_realtime, TTS model: eleven_multilingual_v2, LLM model: openai/gpt-5", "level": "INFO", "name": "basic-agent", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:14:48.687411+00:00"}
Connected to: <socket.socket fd=3, family=2, type=1, proto=0, laddr=('127.0.0.1', 61234), raddr=('127.0.0.1', 61098)>.
{"message": "process initialized", "level": "INFO", "name": "livekit.agents", "pid": 46951, "elapsed_time": 4.24, "timestamp": "2026-03-17T00:14:52.842090+00:00"}
{"message": "Looking up weather for San Francisco, CA", "level": "INFO", "name": "basic-agent", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:14:57.056321+00:00"}
{"message": "Looking up weather for Santa Clara, CA", "level": "INFO", "name": "basic-agent", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:14:57.066475+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 8.22, "prompt_tokens": 269, "prompt_cached_tokens": 0, "completion_tokens": 409, "tokens_per_second": 49.65, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:14:57.067969+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 12.6, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:02.366701+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 1.5, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:03.857257+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 0.0, "transcription_delay": 0.0, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:03.910198+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 2.85, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:09.735758+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 5.25, "transcription_delay": 5.18, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:09.803905+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 1.85, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:11.592817+00:00"}
{"message": "Turn detector does not support language sk", "level": "INFO", "name": "livekit.agents", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:11.597877+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 0.0, "transcription_delay": 0.0, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:12.102473+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 1.6, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:13.199680+00:00"}
{"message": "Turn detector does not support language sk", "level": "INFO", "name": "livekit.agents", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:13.203637+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 0.0, "transcription_delay": 0.0, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:13.705856+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 31.32, "prompt_tokens": 534, "prompt_cached_tokens": 0, "completion_tokens": 563, "tokens_per_second": 17.72, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:45.488447+00:00"}
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.4725689578335732, "audio_duration": 9.85, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:46.521976+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 45.85, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:59.050449+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 1.95, "transcription_delay": 1.85, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:15:59.160176+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 4.2, "prompt_tokens": 588, "prompt_cached_tokens": 0, "completion_tokens": 214, "tokens_per_second": 49.33, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:03.404761+00:00"}
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.4019055829849094, "audio_duration": 2.32, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:03.866630+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 6.3, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:05.321862+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 2.06, "transcription_delay": 1.96, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:05.416095+00:00"}
{"message": "Looking up weather for New York, NY", "level": "INFO", "name": "basic-agent", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:09.741960+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 4.32, "prompt_tokens": 602, "prompt_cached_tokens": 0, "completion_tokens": 425, "tokens_per_second": 98.24, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:09.744807+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 1.37, "prompt_tokens": 658, "prompt_cached_tokens": 0, "completion_tokens": 31, "tokens_per_second": 18.2, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:11.518591+00:00"}
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.4378928339574486, "audio_duration": 6.3, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:12.263707+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 23.2, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:28.537034+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 2.17, "transcription_delay": 2.08, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:28.624210+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 17.64, "prompt_tokens": 708, "prompt_cached_tokens": 0, "completion_tokens": 1137, "tokens_per_second": 63.69, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:46.402560+00:00"}
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.41166379186324775, "audio_duration": 8.75, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:16:47.382669+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 36.4, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:04.917115+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 1.85, "transcription_delay": 1.76, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:05.007184+00:00"}
{"message": "Looking up weather for Toronto, ON", "level": "INFO", "name": "basic-agent", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:11.645465+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 6.71, "prompt_tokens": 767, "prompt_cached_tokens": 0, "completion_tokens": 360, "tokens_per_second": 53.6, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:11.647246+00:00"}
{"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "openai/gpt-5", "model_provider": "livekit", "ttft": 0.98, "prompt_tokens": 822, "prompt_cached_tokens": 0, "completion_tokens": 44, "tokens_per_second": 19.71, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:13.946074+00:00"}
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "eleven_multilingual_v2", "model_provider": "ElevenLabs", "ttfb": 0.4720774160232395, "audio_duration": 9.46, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:14.631116+00:00"}
{"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "elevenlabs/scribe_v2_realtime", "model_provider": "livekit", "audio_duration": 24.15, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:29.093121+00:00"}
{"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "model_name": "multilingual", "model_provider": "livekit", "end_of_utterance_delay": 1.99, "transcription_delay": 1.89, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:17:29.201950+00:00"}
{"message": "failed to generate LLM completion: Request timed out., retrying in 0.1s", "level": "WARNING", "name": "livekit.agents", "llm": "livekit.agents.inference.llm.LLM", "attempt": 1, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:18:00.793760+00:00"}
{"message": "failed to generate LLM completion: Request timed out., retrying in 2.0s", "level": "WARNING", "name": "livekit.agents", "llm": "livekit.agents.inference.llm.LLM", "attempt": 2, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:18:32.735680+00:00"}
{"message": "failed to generate LLM completion: Request timed out., retrying in 2.0s", "level": "WARNING", "name": "livekit.agents", "llm": "livekit.agents.inference.llm.LLM", "attempt": 3, "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:19:06.394813+00:00"}
{"message": "Error in _llm_inference_task\nTraceback (most recent call last):\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 213, in _main_task\n return await self._run()\n ^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 380, in _run\n raise APITimeoutError(retryable=retryable) from None\nlivekit.agents._exceptions.APITimeoutError: Request timed out.\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 17, in async_fn_logs\n return await fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 138, in _llm_inference_task\n async for chunk in llm_node:\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 424, in llm_node\n async for chunk in stream:\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 372, in __anext__\n raise exc # noqa: B904\n ^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 188, in _traceable_main_task\n await self._main_task()\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 229, in _main_task\n raise APIConnectionError(\nlivekit.agents._exceptions.APIConnectionError: failed to generate LLM completion after 4 attempts", "level": "ERROR", "name": "livekit.agents", "exc_info": "Traceback (most recent call last):\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 213, in _main_task\n return await self._run()\n ^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/inference/llm.py\", line 380, in _run\n raise APITimeoutError(retryable=retryable) from None\nlivekit.agents._exceptions.APITimeoutError: Request timed out.\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 17, in async_fn_logs\n return await fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 138, in _llm_inference_task\n async for chunk in llm_node:\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 424, in llm_node\n async for chunk in stream:\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 372, in __anext__\n raise exc # noqa: B904\n ^^^^^^^^^\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 188, in _traceable_main_task\n await self._main_task()\n File \"/Users/tony/Documents/DAART/test/agents/venv/lib/python3.11/site-packages/livekit/agents/llm/llm.py\", line 229, in _main_task\n raise APIConnectionError(\nlivekit.agents._exceptions.APIConnectionError: failed to generate LLM completion after 4 attempts", "room": "room-IXL2-xSVY", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:19:40.040485+00:00"}
{"message": "closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`)", "level": "INFO", "name": "livekit.agents", "room": "room-IXL2-xSVY", "participant": "identity-qUcK", "reason": "CLIENT_INITIATED", "pid": 46926, "job_id": "AJ_c3PNLBgtJH3h", "room_id": "RM_pxZnUsKdD6Wy", "timestamp": "2026-03-17T00:19:56.406354+00:00"}
Here is the code for testing, I only modified a few lines of code in basic agent.
import os
import logging
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentServer,
AgentSession,
JobContext,
JobProcess,
MetricsCollectedEvent,
RunContext,
cli,
inference,
metrics,
room_io,
)
from livekit.agents.llm import function_tool
from livekit.plugins import silero, openai, elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel
# uncomment to enable Krisp background voice/noise cancellation
# from livekit.plugins import noise_cancellation
logger = logging.getLogger("basic-agent")
load_dotenv()
class MyAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="Your name is Kelly. You would interact with users via voice."
"with that in mind keep your responses concise and to the point."
"do not use emojis, asterisks, markdown, or other special characters in your responses."
"You are curious and friendly, and have a sense of humor."
"you will speak english to the user",
)
async def on_enter(self):
# when the agent is added to the session, it'll generate a reply
# according to its instructions
self.session.generate_reply()
# all functions annotated with @function_tool will be passed to the LLM when this
# agent is active
@function_tool
async def lookup_weather(
self, context: RunContext, location: str, latitude: str, longitude: str
):
"""Called when the user asks for weather related information.
Ensure the user's location (city or region) is provided.
When given a location, please estimate the latitude and longitude of the location and
do not ask the user for them.
Args:
location: The location they are asking for
latitude: The latitude of the location, do not ask user for it
longitude: The longitude of the location, do not ask user for it
"""
logger.info(f"Looking up weather for {location}")
return "sunny with a temperature of 70 degrees."
server = AgentServer()
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
server.setup_fnc = prewarm
@server.rtc_session()
async def entrypoint(ctx: JobContext):
# each log entry will include these fields
ctx.log_context_fields = {
"room": ctx.room.name,
}
stt = inference.STT(
model="elevenlabs/scribe_v2_realtime",
# api_key=os.getenv("ELEVEN_API_KEY"),
)
# inference.LLM is super slow
llm = inference.LLM(
model="openai/gpt-5",
# api_key=os.getenv("OPENAI_API_KEY"),
)
# openai.LLM works fine
# llm = openai.LLM(
# api_key=os.getenv("OPENAI_API_KEY"),
# model="gpt-5",
# )
tts = elevenlabs.TTS(
api_key=os.getenv("ELEVEN_API_KEY"),
model="eleven_multilingual_v2",
voice_id="hpp4J3VqNfWAUOO0d1Us"
)
if not stt.capabilities.streaming:
raise ValueError("Streaming is required for this agent.")
logger.info(f"STT model: {stt.model}, TTS model: {tts.model}, LLM model: {llm.model}")
session = AgentSession(
# Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
# See all available models at https://docs.livekit.io/agents/models/stt/
stt=stt,
# A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
# See all available models at https://docs.livekit.io/agents/models/llm/
llm=llm,
# Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
# See all available models as well as voice selections at https://docs.livekit.io/agents/models/tts/
tts=tts,
# VAD and turn detection are used to determine when the user is speaking and when the agent should respond
# See more at https://docs.livekit.io/agents/build/turns
turn_detection=MultilingualModel(),
vad=ctx.proc.userdata["vad"],
# allow the LLM to generate a response while waiting for the end of turn
# See more at https://docs.livekit.io/agents/build/audio/#preemptive-generation
preemptive_generation=True,
# sometimes background noise could interrupt the agent session, these are considered false positive interruptions
# when it's detected, you may resume the agent's speech
resume_false_interruption=True,
false_interruption_timeout=1.0,
# blocks interruptions for a few seconds after the agent starts speaking to allow client to calibrate AEC
aec_warmup_duration=3.0,
)
# log metrics as they are emitted, and total usage after session is over
usage_collector = metrics.UsageCollector()
@session.on("metrics_collected")
def _on_metrics_collected(ev: MetricsCollectedEvent):
metrics.log_metrics(ev.metrics)
usage_collector.collect(ev.metrics)
async def log_usage():
summary = usage_collector.get_summary()
logger.info(f"Usage: {summary}")
# shutdown callbacks are triggered when the session is over
ctx.add_shutdown_callback(log_usage)
await session.start(
agent=MyAgent(),
room=ctx.room,
room_options=room_io.RoomOptions(
audio_input=room_io.AudioInputOptions(
# uncomment to enable the Krisp BVC noise cancellation
# noise_cancellation=noise_cancellation.BVC(),
),
),
)
if __name__ == "__main__":
cli.run_app(server)
Do you think that is a new issue? Should I create a new ticket?
@tonydialpad Thanks for looking into it and sharing those details. I will look into the first two.
As for the slow gpt-5, I don't see immediately any code issues. My hypothesis is around reasoning. Will double check with the team.
For GPT-5 models (5, nano, and mini) we do observe spikey latencies from our end. But later generations (5.1/2/3/4) are much more steady in comparison. I would suggest switching to other newer models if possible.