livekit.agents._exceptions.APIStatusError: connect...
# ask-ai
f
livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) when using Elevenlabs plugin
t
Thanks for reaching out, sdghfdxg. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for sharing the error — I’m responding to the APIStatusError: "connection closed (status_code=-1...)" you saw when using the ElevenLabs plugin. This error means the network connection to ElevenLabs was terminated (status_code = -1 indicates a network-level failure). Here are focused steps to diagnose and mitigate it: 1. Quick checks • Can you reproduce the error consistently or is it intermittent? • Do other external API calls from the same server succeed right now? 1. Network & connectivity • From the agent server, test connectivity to ElevenLabs (e.g., resolve and curl/telnet to api.elevenlabs.io on port 443). • If you're behind a proxy or corporate firewall, ensure it allows outbound HTTPS and streaming/WebSocket traffic. 1. Request size / timeouts • If you send long text or large audio jobs, try splitting the input into smaller chunks. • Verify any
streaming_latency
or timeout settings in your ElevenLabs TTS config. 1. Server health • Check CPU, memory, and network usage on the agent host during failures — resource pressure can drop connections. 1. Retries & fallback • The error is flagged
retryable=True
. Confirm your agent is retrying, or add a
FallbackAdapter
with a secondary TTS provider so TTS continues if ElevenLabs drops:
Copy code
from livekit.agents import tts
from livekit.plugins import elevenlabs, cartesia

session = AgentSession(
    tts=tts.FallbackAdapter([elevenlabs.TTS(), cartesia.TTS()])
)
1. Versions & logs • Ensure
livekit
,
livekit-agents
, and
livekit-plugins-elevenlabs
are up to date. • Enable debug logging on the agent and attach the request trace/timestamps around the failure — that will show whether it’s a network timeout, protocol error, or something else. If you want, share these details and I’ll help narrow it down: • Whether the error is intermittent or reproducible and a sample input that triggers it. • Agent host environment (cloud/on-prem, behind proxy?), and whether other outbound HTTPS calls succeed. • Agent and plugin package versions and any debug log snippets around the error. Sources: AI Service Plugin Ecosystem | livekit/livekit_composite | DeepWiki | ElevenLabs TTS plugin guide | LiveKit Docs | Troubleshooting Guide | livekit/livekit_composite | DeepWiki | Events and error handling | LiveKit docs | How to Get Help from LiveKit
f
it starts with
Copy code
11:39:09 DEBUG  asyncio          Using proactor: IocpProactor  
             DEV    livekit.agents   Watching d:\Dev\helix  
    11:39:10 DEBUG  asyncio          Using proactor: IocpProactor  
             INFO   livekit.agents   starting worker {"version": "1.3.3", "rtc-version": "1.0.19"}
             INFO   livekit.agents   starting inference executor  
             INFO   livekit.agents   initializing process {"pid": 40072, "inference": true}
    11:39:27 INFO   livekit.agents   process initialized {"pid": 40072, "inference": true, "elapsed_time": 16.66}
             INFO   livekit.agents   registered worker {"agent_name": "", "id": "AW_3FouQfDMGcsX", "url": "wss://poly-8eydzhg0.livekit.cloud", "region": "US East B", "protocol":  
                                                       16}                                                                                                                         
    11:40:11 INFO   livekit.agents   received job request {"job_id": "AJ_fLsKbnNXSmVT", "dispatch_id": "AD_7PjYQzYK9nce", "room": "playground-zDfc-2GSH", "room_id":               
                                                          "RM_wsVcyFkisLbs", "agent_name": "", "resuming": false, "enable_recording": false}                                       
             DEBUG  livekit.agents   received assignment {"agent_name": "", "room_id": "RM_wsVcyFkisLbs", "room": "playground-zDfc-2GSH", "job_id": "AJ_fLsKbnNXSmVT",             
                                                         "dispatch_id": "AD_7PjYQzYK9nce", "enable_recording": false}                                                              
             INFO   livekit.agents   initializing job runner {"tid": 37420}
             DEBUG  asyncio          Using proactor: IocpProactor  
             INFO   livekit.agents   job runner initialized {"tid": 37420, "elapsed_time": 0.0}
    11:40:12 DEBUG  livekit.agents   input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]}
             DEBUG  livekit.agents   http_session(): creating a new httpclient ctx  
             DEBUG  livekit.agents   using audio io: `RoomIO` -> `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO`  
             DEBUG  livekit.agents   using transcript io: `AgentSession` -> `TranscriptSynchronizer` -> `RoomIO`
t
Thanks — I’m responding to the log snippet you shared at the start of the job that leads into the ElevenLabs error. Please run or share the following so I can pinpoint the failure: 1. Does the error occur immediately after the lines you posted, or later? If later, paste the next 30–50 log lines (include DEBUG/TRACE entries). 2. Reproduce once with debug logging and capture the full stack trace for the APIStatusError (the exception lines that show where it fails). 3. Environment details: • Agent host OS and whether it’s behind a proxy or corporate firewall. • Can you curl/telnet to api.elevenlabs.io:443 from the same host? Example command output is fine. • Are other outbound HTTPS requests from this host succeeding at the same time? 1. Versions: •
livekit
,
livekit-agents
, and
livekit-plugins-elevenlabs
package versions. 1. Request characteristics: • A sample (or redacted) TTS input that triggers the error and whether inputs are large or streamed. • Your ElevenLabs TTS config (values for
streaming_latency
, timeouts, or similar). 1. Resource checks: • CPU, memory, and network usage on the host around the failure (a short snapshot or top/Task Manager output). If you’d like, paste the next log block and the stack trace and I’ll identify whether this is network-level drops, a timeout, proxy/firewall interference, or something in the plugin.
f
Then it errors
Copy code
11:40:14 WARNI… livekit.plugins… websocket closed unexpectedly  
             WARNI… livekit.agents   failed to synthesize speech, retrying in 0.1s                          {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed":
                                     Traceback (most recent call last):                                     true}                                                                  
                                       File                                                                                                                                        
                                     "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line                                                                        
                                     396, in _main_task                                                                                                                            
                                         await self._run(output_emitter)                                                                                                           
                                       File                                                                                                                                        
                                     "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.p                                                                        
                                     y", line 440, in _run                                                                                                                         
                                         raise e                                                                                                                                   
                                       File                                                                                                                                        
                                     "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.p                                                                        
                                     y", line 435, in _run                                                                                                                         
                                         await waiter                                                                                                                              
                                     livekit.agents._exceptions.APIStatusError: connection closed                                                                                  
                                     (status_code=-1, request_id=None, body=None, retryable=True)
like 5 times
then
Copy code
ERROR  livekit.agents   Error in _tts_inference_task                                                                                               
                                     Traceback (most recent call last):                                                                                         
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line 569, in __anext__                            
                                         val = await self._event_aiter.__anext__()                                                                              
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                                              
                                     StopAsyncIteration                                                                                                         
                                                                                                                                                                
                                     During handling of the above exception, another exception occurred:                                                        
                                                                                                                                                                
                                     Traceback (most recent call last):                                                                                         
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs                       
                                         return await fn(*args, **kwargs)                                                                                       
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^                                                                                       
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\voice\generation.py", line 288, in _tts_inference_task         
                                         pushed_duration += await _tts_node_inference(input_segment, pushed_duration)                                           
                                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                           
                                       File "D:\Dev\helix\.venv\Lib\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper                  
                                         return await func(*args, **kwargs)  # type: ignore                                                                     
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                                                     
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\voice\generation.py", line 246, in _tts_node_inference         
                                         async for audio_frame in tts_node:                                                                                     
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\voice\agent.py", line 446, in tts_node                         
                                         async for ev in stream:                                                                                                
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line 572, in __anext__                            
                                         raise exc  # noqa: B904                                                                                                
                                         ^^^^^^^^^                                                                                                              
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line 362, in _traceable_main_task                 
                                         await self._main_task()                                                                                                
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task                           
                                         await self._run(output_emitter)                                                                                        
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.py", line 440, in _run                         
                                         raise e                                                                                                                
                                       File "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.py", line 435, in _run                         
                                         await waiter                                                                                                           
                                     livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True)  
    11:40:44 INFO   livekit.agents   shutting down worker {"id": "AW_3FouQfDMGcsX"}
             DEBUG  livekit.agents   input stream detached {"participant": "identity-CXmG", "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]}
             DEBUG  livekit.agents   session closed {"reason": "user_initiated", "error": null}
             DEBUG  livekit.agents   shutting down job task {"reason": "", "user_initiated": false}
             DEBUG  livekit.agents   job exiting {"reason": "", "tid": 37420, "job_id": "AJ_fLsKbnNXSmVT", "room_id": "RM_wsVcyFkisLbs"}
             DEBUG  livekit.agents   http_session(): closing the httpclient ctx  
             INFO   livekit.agents   process exiting {"reason": "", "pid": 40072, "inference": true}
t
Thanks — I’m responding to the repeated "connection closed (status_code=-1)" retries you’re seeing. This looks like the ElevenLabs websocket/stream is being dropped and the SDK is retrying (retryable=True). To narrow the root cause quickly, please provide or try the following: 1. Paste the full stack trace for one failure (the lines after the traceback you posted). 2. From the agent host, run: ◦ DNS + TLS check: ▪︎
nslookup api.elevenlabs.io
▪︎
curl -v https://api.elevenlabs.io/health
(or any simple ElevenLabs endpoint) ◦ WebSocket test (if you have
websocat
or similar): attempt a connection to their streaming endpoint and share the result. 1. Confirm environment details: ◦ Host OS (you showed Windows with Proactor), behind proxy/firewall? corporate network or home/cloud? ◦ Are other outbound HTTPS/websocket calls stable from this host at the same times? 1. Versions: ◦
livekit
,
livekit-agents
,
livekit-plugins-elevenlabs
package versions. 1. TTS usage pattern: ◦ Are you streaming audio or sending full text requests? Typical input length that triggers the failure. ◦ Your ElevenLabs TTS config values, especially
streaming_latency
or timeout settings. 1. Resource snapshot when it fails: ◦ A short Task Manager/`top` snapshot showing CPU, memory, and network usage around the error. Quick mitigations you can try immediately: • Retry with a small delay/backoff (you’re already seeing retries — increase backoff to reduce rapid repeat attempts). • Temporarily switch to a FallbackAdapter with a second TTS provider to avoid repeated failures:
Copy code
from livekit.agents import tts
from livekit.plugins import elevenlabs, cartesia

session = AgentSession(
    tts=tts.FallbackAdapter([elevenlabs.TTS(), cartesia.TTS()])
)
• If behind a proxy/firewall, allow streaming/WebSocket traffic and TLS passthrough for
api.elevenlabs.io
. Send the full traceback, the connectivity test outputs, and the package versions and I’ll identify whether this is network/proxy/timeouts or a plugin issue and give the next precise step.
Thanks — I’m responding to the full traceback and shutdown logs you just shared. What this shows: • The ElevenLabs TTS streaming websocket is closing repeatedly, causing the TTS generator to raise
APIStatusError(status_code=-1, retryable=True)
, retries occur, then the job exits and the worker shuts down. Actionable next steps — please provide or try these so I can pinpoint root cause: 1) Quick connectivity checks from the agent host (paste the outputs) •
nslookup api.elevenlabs.io
•
curl -v https://api.elevenlabs.io/health
(or any ElevenLabs endpoint) • If available, a websocket connect test (e.g.,
websocat
or equivalent) to the ElevenLabs streaming endpoint. 2) Environment details • Host OS (you appear to be on Windows with Proactor), network context (home/cloud/corporate), and whether a proxy/firewall sits between the host and the internet. 3) Versions • Exact package versions for:
livekit
,
livekit-agents
,
livekit-plugins-elevenlabs
. 4) TTS usage details • Are you sending long/large TTS inputs or streaming text? Example length that triggers failures. • Your ElevenLabs TTS config (notably
streaming_latency
and any timeout values). 5) Resource snapshot when failure occurs • Short Task Manager /
top
output showing CPU/memory usage around the time of failure. Immediate mitigations you can try now • Increase retry backoff so retries are not so rapid. • Use a
FallbackAdapter
with a secondary TTS provider to avoid repeated failures:
Copy code
from livekit.agents import tts
from livekit.plugins import elevenlabs, cartesia

session = AgentSession(
    tts=tts.FallbackAdapter([elevenlabs.TTS(), cartesia.TTS()])
)
• If behind a proxy/firewall, allow outbound TLS and streaming/WebSocket traffic to
api.elevenlabs.io
. Send the connectivity outputs, versions, and a short resource snapshot/log block around the failure and I’ll identify whether it’s network/proxy/timeouts or a plugin issue and give the precise next step.
f
I cant send the full trace because it would be too big a message for slack, but i can give info personal windows 11 pc (i dont think i have a firewall that would block JUST elevenlabs) my uv dependencies = [ "livekit-agents[elevenlabs,openai,silero,turn-detector]>=1.3.3", "livekit-plugins-noise-cancellation>=0.2.5", "python-dotenv>=1.2.1", ]
t
Thanks — I’m responding to your environment and dependency info. Next focused steps to narrow this down. Please do the first three and paste results (small outputs only): 1) Package versions • Run and paste outputs: ◦
pip show livekit-agents
◦
pip show livekit
◦
pip show livekit-plugins-elevenlabs
2) Quick connectivity checks from your Windows PC • Run in PowerShell or CMD and paste results: ◦
nslookup api.elevenlabs.io
◦
curl -v https://api.elevenlabs.io/health
◦ If curl is unavailable,
powershell -Command "Invoke-WebRequest -Uri https://api.elevenlabs.io/health -UseBasicParsing -Verbose"
3) Reproduce once with a compact log capture • Reproduce the error and capture only the log lines from the first websocket warning through the first complete traceback (you don’t need the entire trace). That block usually starts with the websocket closed warning and ends at the raised
APIStatusError
. Paste that block. If you can also answer these briefly it will help: • Are you sending long TTS inputs (> ~4000 chars) or streaming text? • Do other external HTTPS calls from this PC work reliably while the failure occurs? • Any VPN/proxy active? If you prefer, paste the small outputs and I’ll analyze them and give the exact next steps (network test adjustments, config tweaks, or a plugin workaround).
f
uv pip show livekit Name: livekit Version: 1.0.19 Location: D:\Dev\helix\.venv\Lib\site-packages Requires: aiofiles, numpy, protobuf, types-protobuf Required-by: livekit-agents, livekit-plugins-noise-cancellation (helix) PS D:\Dev\helix> uv pip show livekit-agents Name: livekit-agents Version: 1.3.3 Location: D:\Dev\helix\.venv\Lib\site-packages Requires: aiofiles, aiohttp, av, certifi, click, colorama, docstring-parser, eval-type-backport, livekit, livekit-api, livekit-blingfire, livekit-protocol, nest-asyncio, numpy, openai, opentelemetry-api, opentelemetry-exporter-otlp, opentelemetry-sdk, prometheus-client, protobuf, psutil, pydantic, pyjwt, sounddevice, typer, types-protobuf, typing-extensions, watchfiles Required-by: livekit-plugins-elevenlabs, livekit-plugins-openai, livekit-plugins-silero, livekit-plugins-turn-detector (helix) PS D:\Dev\helix> uv pip show livekit-plugins-elevenlabs Name: livekit-plugins-elevenlabs Version: 1.3.3 Location: D:\Dev\helix\.venv\Lib\site-packages Requires: livekit-agents Required-by: the curl and the nslookup seem to be fine WARNI… livekit.plugins… websocket closed unexpectedly WARNI… livekit.agents failed to synthesize speech, retrying in 0.1s {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 1, "streamed": Traceback (most recent call last): true} File "D:\Dev\helix\.venv\Lib\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task await self._run(output_emitter) File "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.p y", line 440, in _run raise e File "D:\Dev\helix\.venv\Lib\site-packages\livekit\plugins\elevenlabs\tts.p y", line 435, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) if you want i can send my code
t
Thanks — I’m responding to the versions, connectivity check, and logs you provided. Summary: your packages are current (all at 1.3.3 / livekit 1.0.19), DNS/TLS checks appear fine, and logs show ElevenLabs’ streaming websocket is closing repeatedly which triggers retryable APIStatusError and eventually job shutdown. Next helpful items I need (or you can paste the small snippets requested): 1. The ElevenLabs TTS initialization and AgentSession code you’re using (the few lines where you create the TTS plugin and session). This will let me check config like
streaming_latency
, timeouts, or any custom adapter usage. 2. A typical TTS input size (character count) you send when this happens. 3. A short resource snapshot when reproducing (Task Manager showing CPU and memory) if possible. Immediate mitigations you can try now: • Add a modest backoff between retries (increase from 0.1s to 0.5–1s) so the plugin doesn’t hammer the endpoint. • Use a
FallbackAdapter
with a secondary TTS provider to avoid job failure while we debug:
Copy code
from livekit.agents import tts
from livekit.plugins import elevenlabs, cartesia

session = AgentSession(
    tts=tts.FallbackAdapter([elevenlabs.TTS(), cartesia.TTS()])
)
• If you run any VPN/proxy briefly disable it for a quick test to rule out interference. If you paste the TTS/session code and the input size, I’ll review it and suggest the exact config changes (streaming_latency, timeouts, retry backoff) or confirm whether this looks like a network/proxy issue.
f
Copy code
from dotenv import load_dotenv
import os

from livekit import agents, rtc
from livekit.agents import AgentServer,AgentSession, Agent, room_io
from livekit.plugins import noise_cancellation, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

load_dotenv(".env")



if os.getenv("LOCAL_MODE") == "false":
    stt = os.getenv("CLOUD_STT")
    llm = os.getenv("CLOUD_LLM")
    tts = os.getenv("CLOUD_TTS")
    
    os.environ["LIVEKIT_API_KEY"] = os.getenv("CLOUD_API_KEY")
    os.environ["LIVEKIT_API_SECRET"] = os.getenv("CLOUD_API_SECRET")
    os.environ["LIVEKIT_URL"] = os.getenv("CLOUD_URL")
    
    if tts.startswith('elevenlabs'):
        from livekit.plugins import elevenlabs
        
        tts = elevenlabs.TTS(
            voice_id=os.getenv("ELEVEN_VOICE_ID"),
            model=tts.split('/')[1]
        )

class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant.
            You eagerly assist users with their questions by providing information from your extensive knowledge.
            Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
            You are curious, friendly, and have a sense of humor.""",
        )

server = AgentServer()

@server.rtc_session()
async def my_agent(ctx: agents.JobContext):
    session = AgentSession(
        stt=stt,
        llm=llm,
        tts=tts,
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )

    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_options=room_io.RoomOptions(
            audio_input=room_io.AudioInputOptions(
                noise_cancellation=lambda params: noise_cancellation.BVCTelephony() if params.participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP else noise_cancellation.BVC(),
            ),
        ),
    )

    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )


if __name__ == "__main__":
    agents.cli.run_app(server)
t
Thanks — I’m responding to your code + logs and the repeated websocket closures. What to change now (small, focused fixes you can try immediately) • Set an explicit
streaming_latency
when constructing the ElevenLabs TTS to reduce sensitivity to network jitter:
Copy code
tts = elevenlabs.TTS(
    voice_id=os.getenv("ELEVEN_VOICE_ID"),
    model=tts.split('/')[1],
    streaming_latency=3
)
• Increase retry backoff so retries aren’t hammering the endpoint (raise from 0.1s to 0.5–1s). If you can’t change internal retry, wrap calls with a small backoff loop. • Use a FallbackAdapter so a secondary TTS can take over when ElevenLabs fails:
Copy code
from livekit.agents import tts
from livekit.plugins import elevenlabs, cartesia

tts = tts.FallbackAdapter([elevenlabs.TTS(...), cartesia.TTS(...)])
Quick diagnostics that will confirm whether this is a network/transport issue • Reproduce once and capture only the log lines from the first "websocket closed unexpectedly" warning through the raised
APIStatusError
(the block that ends with that exception). Paste that block here. • While reproducing, run these from your PC and paste short outputs: ◦ nslookup api.elevenlabs.io ◦ curl -v https://api.elevenlabs.io/health • Tell me: ◦ Typical TTS input size (characters) you send when failures occur. ◦ Whether failures happen on the first TTS request or after several successful requests. ◦ Any VPN/proxy active. If you’d like, paste your updated TTS instantiation (with the streaming_latency change) and I’ll confirm it’s correct and suggest exact retry/backoff code to add.
f
Still doesnt work after the streaming latency thing, nslookup api.elevenlabs.io Server: UnKnown Address: 10.0.0.1 Non-authoritative answer: Name: api.elevenlabs.io Address: 34.8.184.191 (helix) PS D:\Dev\helix> curl -v https://api.elevenlabs.io/health VERBOSE: GET with 0-byte payload VERBOSE: received 15-byte response of content type application/json StatusCode : 200 StatusDescription : OK Content : {"status":"ok"} RawContent : HTTP/1.1 200 OK access-control-allow-origin: * access-control-allow-headers: * access-control-allow-methods: POST, PATCH, OPTIONS, DELETE, GET, PUT access-control-max-age: 600 strict-transport-se... Forms : {} Headers : {[access-control-allow-origin, *], [access-control-allow-headers, *], [access-control-allow-methods, POST, PATCH, OPTIONS, DELETE, GET, PUT], [access-control-max-age, 600]...} Images : {} InputFields : {} Links : {} ParsedHtml : System.__ComObject RawContentLength : 15 I already sent you that code block
t
Thanks — I’m responding to your latest tests and that streaming_latency didn’t fix it. Next targeted steps (quick to try, in order): 1) Test a non-streaming TTS call (short text) to see if streaming is the issue: • Instantiate ElevenLabs TTS with streaming disabled (or send a very short text like "hello") and run once. Does it succeed? 2) Switch Windows event loop policy (known to affect some websocket libs on Windows): • At top of your script add:
Copy code
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
Then reproduce the error. 3) Increase retry/backoff and add a small overall delay before each retry (avoid 0.1s). Example minimal pattern around your generate call:
Copy code
import asyncio

for attempt in range(4):
    try:
        await session.generate_reply(...)
        break
    except Exception:
        await asyncio.sleep(0.8 * (attempt + 1))
4) Try a fallback provider so jobs don’t fail while debugging: • Wrap your
tts
with
tts.FallbackAdapter([elevenlabs.TTS(...), cartesia.TTS(...)])
. 5) Capture one compact debug trace (only lines around websocket open/close and the raised exception). If Slack truncates, paste into a gist/snippet or attach as a file. Please try steps 1 and 2 first and tell me: • Whether a non-streaming short request succeeds. • Whether switching to the Selector event loop changes behavior. I’ll use those results to recommend the exact next change (debug flags, code patch, or config).
f
I dont know how to make it non streaming, and switching the loop doesnt do anything
t
Thanks — I’m responding to your last tests and the fact streaming_latency didn’t help. Do this exact change to disable streaming (avoids WebSocket use): 1) Replace your ElevenLabs TTS instantiation with:
Copy code
from livekit.plugins import elevenlabs

tts = elevenlabs.TTS(
    voice_id=os.getenv("ELEVEN_VOICE_ID"),
    model=os.getenv("CLOUD_TTS").split('/')[1],
    streaming=False
)
2) Restart and reproduce the job. Send the small log block if it still errors (the lines from the first warning through the raised exception). If
streaming=False
raises an error (unknown arg), run: • pip install --upgrade livekit-plugins-elevenlabs then retry the code above. If disabling streaming fixes it, we can then: • Add a short synth timeout/backoff so long requests don’t hang, or • Add a FallbackAdapter to keep service available. Tell me the result (success or the short error block) and I’ll give the exact next step. Sources: ElevenLabs TTS | LiveKit Docs | ElevenLabs TTS plugin guide | LiveKit Docs | Example Applications & Templates | livekit/livekit_composite | DeepWiki