s\livekit\agents\cli\cli.py", line 1223, in _async...
# ask-ai
n
s\livekit\agents\cli\cli.py", line 1223, in _async_main await self._server.run(devmode=True, unregistered=True) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\worker.py", line 603, in run raise ValueError("ws_url is required, or add LIVEKIT_URL in your environment") ValueError: ws_url is required, or add LIVEKIT_URL in your environment
t
Thanks for reaching out, Mubbashir. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're seeing this error because the agent needs a LiveKit WebSocket URL but none was provided. To fix it, set the LIVEKIT_URL environment variable (or pass
ws_url
directly). Also ensure your API credentials are set. Options: 1) Set environment variables (recommended) • Create a
.env
file or set in your shell:
Copy code
LIVEKIT_URL=wss://your-project.livekit.cloud   # or ws://localhost:7880 for local server
  LIVEKIT_API_KEY=your-api-key
  LIVEKIT_API_SECRET=your-api-secret
• If using a
.env
file, load it in Python with:
Copy code
from dotenv import load_dotenv
  load_dotenv()
2) Pass
ws_url
directly when starting the server (if supported by your CLI call), e.g.: • start command or code that accepts
ws_url="wss://your-project.livekit.cloud"
After setting
LIVEKIT_URL
(and
LIVEKIT_API_KEY
/
LIVEKIT_API_SECRET
), re-run the CLI command. Would you like help verifying your current environment variables or the exact command to pass
ws_url
for your setup? Sources: examples/drive-thru | livekit/livekit_composite | DeepWiki | Voice AI quickstart | LiveKit docs
n
i have added these in my .env folder
t
Thanks — glad you added them. To help further, can you confirm a few quick things? 1. Is the
.env
file in the same working directory where you run the CLI? 2. Does it contain these exact keys (no extra spaces)? ◦
LIVEKIT_URL
◦
LIVEKIT_API_KEY
◦
LIVEKIT_API_SECRET
1. How are you launching the CLI? (command you run or the IDE/run configuration) 2. Do you call
load_dotenv()
in your script before the agent starts, or are you relying on your shell/IDE to load the
.env
? If you prefer, paste the command you run and the first few lines of your
.env
(redact secrets) and I’ll tell you the next step.
n
from dotenv import load_dotenv import logging from livekit import agents from livekit.agents import AgentSession, RoomInputOptions, ConversationItemAddedEvent from livekit.plugins import ( openai, noise_cancellation, elevenlabs, deepgram, silero ) from livekit.agents.llm import ImageContent, AudioContent import asyncio from lib.get_agent import get_agent from livekit.plugins.turn_detector.english import EnglishModel from classes.helpful_assistant import HelpfulAssistant from classes.conversation_persistor import ConversationPersistor load_dotenv(dotenv_path=".env.local") # Debugging: Verify Environment Variables import os print("--- ENVIRONMENT VARIABLE CHECK ---") print(f"LIVEKIT_URL: {os.getenv('LIVEKIT_URL')}") print(f"MONGODB_URI: {os.getenv('MONGODB_URI')}") print("----------------------------------") AGENT_NAME = None # Will be set after fetching the agent AGENT_SCRIPT = None # Will be set after fetching the agent AGENT_INSTRUCTIONS = None # Will be set after fetching the agent async def entrypoint(ctx: agents.JobContext): print("entrypoint") # Egress Service for recording the calls # Get GCP credentials from credentials.json file. file_contents = "" with open("./credentials.json", "r") as f: file_contents = f.read() # Set up recording (Egress) # req = api.RoomCompositeEgressRequest( # room_name=ctx.room.name, # layout="speaker", # audio_only=True, # file_outputs=[api.EncodedFileOutput( # filepath=f"{ctx.room.name}.mp3", # gcp=api.GCPUpload( # credentials=file_contents, # bucket="ai-calling-agent-livekit", # ), # )], # ) # lkapi = api.LiveKitAPI() # res = await lkapi.egress.start_room_composite_egress(req) # await lkapi.aclose() ### print(f"Room name: {ctx.room.name}") # Extract agent ID from room name (format: agentId_randomString) # or fallback to environment variable import os agent_id = None # Try to extract agent ID from room name first if "_" in ctx.room.name: potential_agent_id = ctx.room.name.split("_")[0] if len(potential_agent_id) == 24: # MongoDB ObjectId length agent_id = potential_agent_id print(f"Extracted agent ID from room name: {agent_id}") # Fallback to environment variable if not found in room name if not agent_id: agent_id = os.getenv("AGENT_ID") if agent_id: print(f"Using agent ID from environment variable: {agent_id}") if not agent_id: return print("ERROR: No agent ID found in room name or environment variables.") try: # Fetch the agent from the database agent_data = get_agent(agent_id) if not agent_data: return print(f"Agent with ID {agent_id} not found in database") # Set agent details global AGENT_NAME, AGENT_SCRIPT, AGENT_INSTRUCTIONS AGENT_NAME = agent_data["name"] AGENT_SCRIPT = agent_data["prompt"] AGENT_INSTRUCTIONS = agent_data["instructions"] print(f"Loaded agent: {AGENT_NAME}") # Initialize logger with agent name global logger logger = logging.getLogger(AGENT_NAME) logger.setLevel(logging.INFO) # Connect to the room await ctx.connect() except Exception as e: return print(f"Error fetching agent: {e}") # Configure STT with improved error handling and connection resilience stt_config = None try: stt_config = deepgram.STT( smart_format=True, numerals=True, interim_results=True, model="nova-2" # Use the latest Deepgram model ) except Exception as e: print(f"Warning: Failed to configure Deepgram STT: {e}") # Fallback to basic STT configuration stt_config = deepgram.STT( smart_format=True, numerals=True, interim_results=True ) # Configure TTS with fallback try: tts_config = openai.TTS( voice="alloy" ) except Exception as e: print(f"Warning: Failed to configure OpenAI TTS: {e}") # Fallback to Silero TTS tts_config = silero.TTS( voice="v3_en" # Use Silero TTS as fallback ) session = AgentSession( llm=openai.LLM( model="gpt-4o", temperature=0.3 ), tts=openai.TTS( voice="alloy", ), # Improved turn detection with longer silence threshold turn_detection=EnglishModel(), vad=silero.VAD.load( min_silence_duration=1.0, # Increased to reduce false triggers min_speech_duration=0.5 # Increased to reduce noise ), stt=stt_config, allow_interruptions=True, min_interruption_duration=1.0, min_endpointing_delay=1.3, max_endpointing_delay=1.6, ) # Initialize persistor as None first persistor = None # Add event handler for conversation items @session.on("conversation_item_added") def on_conversation_item_added(event: ConversationItemAddedEvent): nonlocal persistor print(f"Conversation item added from {event.item.role}: {event.item.text_content}. interrupted: {event.item.interrupted}") # Create an async task to handle the conversation item async def handle_conversation_item(): nonlocal persistor # Initialize the persistor on the first message if not already done if persistor is None and event.item.role != "assistant": # The first non-assistant message indicates we have a participant persistor = ConversationPersistor(ctx.room.name, event.item.role) # Start the persistor await persistor.start() # Rename the current task for identification current_task = asyncio.current_task() if current_task: current_task.set_name(f"ConversationPersistor-{ctx.room.name}") # Store the transcription if persistor is available if persistor and event.item.text_content: await persistor.add_transcription(event.item.text_content, event.item.role) # Create a task for the async operations asyncio.create_task(handle_conversation_item()) # to iterate over all types of content: for content in event.item.content: if isinstance(content, str): print(f" - text: {content}") elif isinstance(content, ImageContent): # image is either a rtc.VideoFrame or URL to the image print(f" - image: {content.image}") elif isinstance(content, AudioContent): # frame is a list[rtc.AudioFrame] print(f" - audio: {content.frame}, transcript: {content.transcript}") # Start with the HelpfulAssistant using instructions and script from database # Add current date context to instructions from datetime import datetime current_date = datetime.now().strftime("%A, %B %d, %Y") current_time = datetime.now().strftime("%I:%M %p") date_context = f"\n\nIMPORTANT: Today is {current_date}. Current time is {current_time}. Always use this as the reference date when scheduling appointments." # Combine instructions, script, and date context enhanced_instructions = AGENT_INSTRUCTIONS + date_context if AGENT_SCRIPT: enhanced_instructions += f"\n\nSCRIPT TO FOLLOW:\n{AGENT_SCRIPT}" agent = HelpfulAssistant(enhanced_instructions) # Start session with error handling try: await session.start( room=ctx.room, agent=agent, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) print("Agent session started successfully") except Exception as e: print(f"ERROR: Failed to start agent session: {e}") # Try to clean up any partial connections try: await session.aclose() except: pass return # Initialize background audio player AFTER session starts with error handling from livekit.agents import BackgroundAudioPlayer try: background_audio = BackgroundAudioPlayer() await background_audio.start(room=ctx.room, agent_session=session) # Pass the background audio player to the agent agent.set_background_audio_player(background_audio) print("Background audio player initialized successfully") except Exception as e: print(f"Warning: Failed to initialize background audio player: {e}") # Continue without background audio agent.set_background_audio_player(None) await session.say("Hello") if name == "__main__": agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc= entrypoint))
t
Thanks — I looked at your code and a few things stand out that will help us narrow this down. 1) You load
.env.local
not
.env
— confirm which file you added the LiveKit vars to. 2) Your debug prints will show whether the variables are actually loaded. What do these printouts show for
LIVEKIT_URL
? (Paste the printed value, redact secrets.) 3) Ensure
LIVEKIT_URL
includes the scheme (
wss://
or
ws://
). Example:
wss://your-project.livekit.cloud
or
ws://localhost:7880
. 4) How are you running the CLI? If you run the CLI from a different working directory or via a service/IDE, the
.env.local
file may not be loaded into that process. If the print shows an empty value, try one of these quick fixes: • Rename or copy your
.env
file to
.env.local
(or change
load_dotenv(dotenv_path=".env.local")
to the correct path). • Or set the variable in your shell before running: ◦ macOS/Linux:
export LIVEKIT_URL="wss://..."
◦ Windows (PowerShell):
$env:LIVEKIT_URL="wss://..."
If the print shows a value but the CLI still errors, paste the printed
LIVEKIT_URL
(redact host if needed) and the exact command you run to start the CLI so I can advise the next step.
n
--- ENVIRONMENT VARIABLE CHECK --- LIVEKIT_URL: None LIVEKIT_API_KEY': APIPN3ASmBGGj6i MONGODB_URI: mongodb+srv://agentcall111_db_user:R2IyUxqJYiaBbVa3@cluster0.nmejkyu.mongodb.net/ i have the in my .env.local folder but it is not proniting them
t
Thanks — I see
LIVEKIT_URL
is still None while
LIVEKIT_API_KEY
is printed (partially). Let’s focus on why
.env.local
isn’t loading
LIVEKIT_URL
. Quick checklist and steps to fix: 1. Confirm
.env.local
contents and syntax • Ensure a line exactly like this (no quotes, no extra spaces): LIVEKIT_URL=wss://your-project.livekit.cloud • No stray characters or Unicode hyphens. Show the LIVEKIT_URL line (redact host if needed). 1. Ensure you load the same file your variables are in • Your code calls
load_dotenv(dotenv_path=".env.local")
. Confirm the file is in the same working directory where you run the CLI. • Run this in the same terminal before running the CLI to test loading explicitly: ◦ Python quick test:
Copy code
from dotenv import load_dotenv
    import os
    load_dotenv(dotenv_path=".env.local", override=True)
    print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
• If that prints None, the file path or contents are wrong. 1. Check for duplicate/overriding env sources • If you also have a
.env
or environment variables set elsewhere,
override=True
in
load_dotenv
forces
.env.local
to overwrite. Try
load_dotenv(dotenv_path=".env.local", override=True)
. 1. Verify file encoding and line endings • Make sure
.env.local
is UTF-8 plain text and lines end normally. Recreate the file with a simple editor if unsure. 1. Confirm how you run the CLI • If you run via an IDE/run configuration or as a service, that process may not read the
.env.local
file. Either: ◦ Put the variables into the environment for that process (IDE Run Config or OS env), or ◦ Ensure your script that runs as entrypoint calls
load_dotenv(...)
before any imports that need env vars. 1. Temporary test: export the value in your shell and run • macOS/Linux: export LIVEKIT_URL="wss://your-project.livekit.cloud" • Windows PowerShell: $env:LIVEKIT_URL="wss://your-project.livekit.cloud" • Then run your CLI and see if the error disappears. Send me two things if it’s still failing: • The exact
LIVEKIT_URL=
line from
.env.local
(redact host if needed), and • The exact command you use to run the CLI (or how you start it in your IDE).
n
e "model_q8.onnx". 024511.241 INFO livekit.agents process initialized {"pid": 30344, "inference": true, "elapsed_time": 19.76} 024511.250 INFO livekit.agents HTTP server listening on :62273 024511.287 INFO livekit.agents initializing job runner {"tid": 10872} 024511.293 DEBUG asyncio Using proactor: IocpProactor 024511.298 INFO livekit.agents job runner initialized {"tid": 10872, "elapsed_time": 0.01} entrypoint Room name: mock_room Using agent ID from environment variable: 6877811c2bb3ecee79911a3c Connected to MongoDB database: test Loaded agent: Michael Dental Clincic 024517.069 ERROR livekit.…_detector Could not find file "languages.json". Make sure you have downloaded the model before running the agent. Use
Copy code
python3
                                           your_agent.py download-files
to download the model. 024517.077 ERROR livekit.agents unhandled exception while running the job task Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\opentelemetry\util\_de corator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\ipc\job _proc_lazy_main.py", line 286, in _traceable_entrypoint await self._job_entrypoint_fnc(job_ctx) File "C:\Users\Admin\AIAgentBackend\main.py", line 154, in entrypoint turn_detection=EnglishModel(), ~~~~~~~~~~~~^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\turn_d etector\english.py", line 29, in init super().__init__(model_type="en", unlikely_threshold=unlikely_threshold) ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\turn_d etector\base.py", line 216, in init config_fname = _download_from_hf_hub( HG_MODEL, ...<2 lines>... local_files_only=True, ) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\turn_d etector\base.py", line 40, in _download_from_hf_hub raise RuntimeError( ...<2 lines>... ) from None RuntimeError: livekit-plugins-turn-detector initialization failed. Could not find file "languages.json".
t
Thanks — you’re seeing two separate issues: the missing LIVEKIT_URL (still None) and the turn-detector missing files (
languages.json
). Let’s fix both quickly. 1) LIVEKIT_URL still None • You call
load_dotenv(dotenv_path=".env.local")
. Confirm the file name and location exactly match where you run the CLI. • Quick test to run in the same terminal/working dir:
Copy code
from dotenv import load_dotenv
  import os
  load_dotenv(dotenv_path=".env.local", override=True)
  print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
If that prints None, show the exact LIVEKIT_URL line from
.env.local
(redact secrets). • If the test prints a value but your agent process still shows None, how you start the CLI matters. If you run the worker from another process/IDE or as a service, that process may not load
.env.local
. Either: ◦ Put the vars into the process/IDE environment, or ◦ Change your start command so the Python that runs the agent executes the
load_dotenv(...)
line before the agent process starts. • Temporary check: set it in your shell and re-run the CLI: ◦ PowerShell:
$env:LIVEKIT_URL="wss://your-project.livekit.cloud"
2) turn-detector missing files (
languages.json
) • Run the downloader command from your agent script:
Copy code
python3 main.py download-files
(Replace
main.py
with your agent filename if different.) • After it finishes, re-run the agent. If you prefer programmatic download, you can call:
Copy code
from livekit.plugins.turn_detector.english import EnglishModel
  EnglishModel().download_files()
• If download fails, share the error output and confirm the environment has internet access. Next step for me: please run the dotenv quick test above and run
python3 main.py download-files
. Paste the dotenv test output and any download output (redact secrets) and I’ll guide the next fix.
n
PS C:\Users\Admin\AIAgentBackend> python3 main.py download-files Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Apps > Advanced app settings > App execution aliases.
t
Thanks — the Windows error shows your shell can't find the
python3
launcher. Let's get you past both blockers. 1) Run the downloader on Windows • Try these commands in PowerShell or CMD from your project folder: ◦ If Python 3 is on PATH: ▪︎ python main.py download-files ◦ If your Python is installed as `py`: ▪︎ py -3 main.py download-files • If those say Python not found, confirm Python is installed: ◦ Open PowerShell and run: python --version ◦ If not installed, install Python 3 and check "Add Python to PATH" during setup, or use the Microsoft Store version. 2) Quick programmatic alternative (if you can run any Python file) • Create a short script download_turn_models.py in your project:
Copy code
from livekit.plugins.turn_detector.english import EnglishModel
  EnglishModel().download_files()
Then run with
python download_turn_models.py
or
py -3 download_turn_models.py
. 3) LIVEKIT_URL still None • While in the same shell where you run the downloader/agent, test loading `.env.local`:
Copy code
from dotenv import load_dotenv
  import os
  load_dotenv(dotenv_path=".env.local", override=True)
  print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
• If that prints None, open
.env.local
and confirm a line exactly like: LIVEKIT_URL=wss://your-project.livekit.cloud • If the test prints a value but your agent still shows None, run the agent from the same shell (so the loaded env is visible) or set the env directly in PowerShell before running: $env:LIVEKIT_URL="wss://your-project.livekit.cloud" Then run your agent command. Tell me: • The output of
python --version
or
py -3 --version
• The result of the dotenv test print (copy output) • Which command you used to run the downloader and its output I’ll guide the next step based on those results.
n
Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 459, in _run raise e File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 134254.103 WARNI… livekit.…levenlabs websocket closed unexpectedly 134254.110 WARNI… livekit.agents failed to synthesize speech, retrying in 2.0s {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true} Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 459, in _run raise e File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 134257.297 WARNI… livekit.…levenlabs websocket closed unexpectedly 134257.308 WARNI… livekit.agents failed to synthesize speech, retrying in 2.0s {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true} Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 459, in _run raise e File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 134300.540 WARNI… livekit.…levenlabs websocket closed unexpectedly 134300.551 ERROR livekit.agents Error in _tts_inference_task Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\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 "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\voice\generation.py", line 288, in _tts_inference_task pushed_duration += await _tts_node_inference(input_segment, pushed_duration) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\voice\generation.py", line 246, in _tts_node_inference async for audio_frame in tts_node: ...<13 lines>... audio_duration += audio_frame.duration File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\voice\agent.py", line 447, in tts_node async for ev in stream: yield ev.frame File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 572, in anext raise exc # noqa: B904 ^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 362, in _traceable_main_task await self._main_task() File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\tts\tts.py", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 459, in _run raise e File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\elevenlabs\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) Conversation item added from assistant: Thank you for calling comcast Xfinity, this is Eric your personalised AI assistant,how can i help you today?. interrupted: False - text: Thank you for calling comcast Xfinity, this is Eric your personalised AI assistant,how can i help you today? 134301.307 WARNI… livekit.agents failed to recognize speech, retrying in 0.1s {"tts": "livekit.plugins.deepgram.stt.STT", "attempt": 0, "streamed": true} Traceback (most recent call last): File "C:\Python313\Lib\asyncio\tasks.py", line 507, in wait_for return await fut ^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\aiohttp\client.py", line 1048, in _ws_connect resp = await self.request( ^^^^^^^^^^^^^^^^^^^ ...<11 lines>... ) ^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\aiohttp\client.py", line 760, in _request resp = await handler(req) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\aiohttp\client.py", line 738, in _connect_and_send_request await resp.start(conn) File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\aiohttp\client_reqrep.py", line 512, in start message, payload = await protocol.read() # type: ignore[union-attr] ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\aiohttp\streams.py", line 672, in read await self._waiter asyncio.exceptions.CancelledError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\deepgram\stt.py", line 582, in _connect_ws ws = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ ...<5 lines>... ) ^ File "C:\Python313\Lib\asyncio\tasks.py", line 506, in wait_for async with timeouts.timeout(timeout): ~~~~~~~~~~~~~~~~^^^^^^^^^ File "C:\Python313\Lib\asyncio\timeouts.py", line 116, in aexit raise TimeoutError from exc_val TimeoutError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\agents\stt\stt.py", line 289, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\deepgram\stt.py", line 518, in _run ws = await self._connect_ws() ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Roaming\Python\Python313\site-packages\livekit\plugins\deepgram\stt.py", line 597, in _connect_ws raise APIConnectionError("failed to connect to deepgram") from e livekit.agents._exceptions.APIConnectionError: failed to connect to deepgram (body=None, retryable=True)
t
Thanks — you’ve hit three runtime issues: ElevenLabs TTS websocket closed, Deepgram STT connection timed out, and LIVEKIT_URL still not loaded. Let’s tackle these step‑by‑step. 1) Confirm env vars in the process • From the same shell you run the agent, run:
Copy code
from dotenv import load_dotenv
  import os
  load_dotenv(dotenv_path=".env.local", override=True)
  print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
  print("ELEVENLABS_API_KEY:", bool(os.getenv("ELEVENLABS_API_KEY")))
  print("DEEPGRAM_API_KEY:", bool(os.getenv("DEEPGRAM_API_KEY")))
• Paste that output (redact keys). If any come back False/None, fix the
.env.local
lines: LIVEKIT_URL=wss://your-project.livekit.cloud ELEVENLABS_API_KEY=your-key DEEPGRAM_API_KEY=your-key 2) Download turn-detector model files (Windows) • From your project folder run either: ◦ python main.py download-files ◦ OR py -3 main.py download-files • If those fail because Python isn’t on PATH, run
python --version
and tell me the output or install Python and check “Add Python to PATH.” 3) Troubleshoot ElevenLabs TTS websocket errors • Ensure
ELEVENLABS_API_KEY
is set in the same environment the agent runs in. • Verify network access / firewall allows outbound websocket/HTTPS to ElevenLabs. • If ElevenLabs remains unstable, switch to your fallback TTS (Silero) by removing/overriding
tts=openai.TTS(...)
/ ElevenLabs config in your session to test. 4) Troubleshoot Deepgram STT connection timeouts • Ensure
DEEPGRAM_API_KEY
is set and valid in the running process. • Confirm the host has internet access and outbound websockets are allowed. • If your network blocks websockets, test connectivity with a simple WS client or try a different network. 5) Short tests to run now (from the same shell you will run the agent) • Env check (step 1). • Try the downloader command (step 2) and paste its output. • If downloader succeeds, restart the agent from that same shell. Send me: • Output of the env check script above. • Result of
python --version
or
py -3 --version
. • Output from running
python main.py download-files
(or the failure message). I’ll use those results to give the exact next commands or edits.
n
ELEVEN_API_KEY { "detail": { "status": "missing_permissions", "message": "The API key you used is missing the permission user_read" } }
t
Thanks — that error shows your ElevenLabs API key is valid but missing the required permission
user_read
. To get TTS working, do the following: 1. Create a new ElevenLabs API key that includes the
user_read
permission (enable it during key creation on the ElevenLabs dashboard). 2. Update your
.env.local
with the new key: ELEVEN_API_KEY=your-new-key 1. Restart the agent from the same shell where you verified env vars. While you’re here, please also paste the output of this quick env check (redact actual keys but keep True/False or None):
Copy code
from dotenv import load_dotenv
import os
load_dotenv(dotenv_path=".env.local", override=True)
print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
print("ELEVEN_API_KEY set:", bool(os.getenv("ELEVEN_API_KEY")))
print("DEEPGRAM_API_KEY set:", bool(os.getenv("DEEPGRAM_API_KEY")))
I’ll confirm the next steps after you share that output. Sources: ElevenLabs STT plugin guide | LiveKit docs
n
Traceback (most recent call last): File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 459, in _run raise e File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 222101.479 WARNI… livekit.…levenlabs websocket closed unexpectedly 222101.485 WARNI… livekit.agents failed to synthesize speech, retrying in 2.0s {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 2, "streamed": true} Traceback (most recent call last): File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 459, in _run raise e File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 222104.675 WARNI… livekit.…levenlabs websocket closed unexpectedly 222104.681 WARNI… livekit.agents failed to synthesize speech, retrying in 2.0s {"tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true} Traceback (most recent call last): File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 459, in _run raise e File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True) 222104.764 DEBUG livekit.….deepgram Established new Deepgram STT WebSocket connection: {"headers": {"dg-project-id": "05a53a01-c7a2-4bed-ac3e-c6e7511b3627", "dg-request-id": "a6c747eb-d494-42ae-85a3-d36c6fe6f6f4", "Date": "Tue, 16 Dec 2025 172103 GMT"}} 222107.858 WARNI… livekit.…levenlabs websocket closed unexpectedly 222107.865 ERROR livekit.agents Error in _tts_inference_task Traceback (most recent call last): File "C:\Users\Admin\AIAgentBackend\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 "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\utils\log. py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\voice\gene ration.py", line 288, in _tts_inference_task pushed_duration += await _tts_node_inference(input_segment, pushed_duration) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\opentelemetry\util\_decor ator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\voice\gene ration.py", line 246, in _tts_node_inference async for audio_frame in tts_node: File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\voice\agen t.py", line 447, in tts_node async for ev in stream: File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 572, in anext raise exc # noqa: B904 ^^^^^^^^^ File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 362, in _traceable_main_task await self._main_task() File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\agents\tts\tts.py ", line 396, in _main_task await self._run(output_emitter) File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 459, in _run raise e File "C:\Users\Admin\AIAgentBackend\venv\Lib\site-packages\livekit\plugins\elevenlab s\tts.py", line 454, in _run await waiter livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True)
t
Thanks — you're very close. The ElevenLabs websocket closures are caused by the ElevenLabs key or network; Deepgram timeouts point to STT connectivity or key issues. Let's take focused steps to confirm and fix each: 1) Confirm env vars in the same process Run this from the same PowerShell/CMD where you start the agent:
Copy code
from dotenv import load_dotenv
import os
load_dotenv(dotenv_path=".env.local", override=True)
print("LIVEKIT_URL:", os.getenv("LIVEKIT_URL"))
print("ELEVEN_API_KEY set:", bool(os.getenv("ELEVEN_API_KEY")))
print("DEEPGRAM_API_KEY set:", bool(os.getenv("DEEPGRAM_API_KEY")))
Paste that output (True/False/None is fine; redact keys). 2) ElevenLabs TTS — permission & network • Create a new ElevenLabs API key that includes the user_read permission and put it in
.env.local
as
ELEVEN_API_KEY=your-new-key
. • If the key is correct but errors persist, confirm network allows outbound websockets/HTTPS to ElevenLabs (try from PowerShell): ◦ curl https://api.elevenlabs.io/v1 / or use a simple websocket client. • To isolate, switch to the Silero fallback by temporarily replacing ElevenLabs in your
AgentSession
TTS config and restart. If Silero works, the issue is ElevenLabs-specific. 3) Deepgram STT — key & connectivity • Ensure
DEEPGRAM_API_KEY
is set (step 1). • Confirm outbound websocket access to Deepgram. A successful connection log line you saw earlier indicates it sometimes connects; intermittent network issues or rate limits can cause timeouts. 4) Turn-detector model files If you haven't run downloads yet on Windows, run from project folder: • python main.py download-files or • py -3 main.py download-files If Python isn't found, run
python --version
or
py -3 --version
and tell me the output. 5) Restart from same shell After updating
.env.local
, always restart the agent from the same shell where you verified environment variables so the process sees them. Send me: • Output of the env check snippet. • The command you use to start the agent. • The result of
python --version
(if downloader still failed). • Whether you want to try Silero fallback now (I can show the exact code change).