{"message": "Task exception was never retrieved\nf...
# ask-ai
l
{"message": "Task exception was never retrieved\nfuture: <Task finished name='Task-717' coro=<entrypoint.<locals>.switch_language() done, defined at /app/main.py:650> exception=RuntimeError(\"AgentSession isn't running\")>", "level": "ERROR", "name": "asyncio", "exc_info": "Traceback (most recent call last):\n File \"/app/main.py\", line 655, in switch_language\n session.interrupt()\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/voice/agent_session.py\", line 842, in interrupt\n raise RuntimeError(\"AgentSession isn't running\")\nRuntimeError: AgentSession isn't running", "timestamp": "2025-12-10T092713.550745+00:00"}
t
Thanks for reaching out, Pavan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're seeing a RuntimeError when
switch_language
calls
session.interrupt()
because the AgentSession isn't running. I can help diagnose and fix this. To narrow it down, please tell me: 1. Do you call
await session.start(...)
before
switch_language
? 2. Has the session been closed earlier (e.g.,
session.aclose()
), or did any prior errors occur in the logs before this traceback? 3. Is
switch_language
triggered while the session is idle, or during active audio/agent activity (what user action triggers it)? 4. Which LiveKit Agents SDK version are you running and which runtime (Python 3.11 shown) or deployment environment? While you gather that, try these quick checks: • Confirm
session.start()
completed successfully before calling
interrupt()
. • Wrap
session.interrupt()
in a try/except to handle the RuntimeError and log session state. • If you need to change language mid-run, stop and recreate the AgentSession with new language settings instead of calling
interrupt()
when the session may be stopped. Tell me the answers to the questions above and any additional log lines around this error and I’ll provide specific code examples or next steps. Sources: Events and error handling | LiveKit docs | Agent speech and audio | LiveKit docs | Building a Moviefone-style Theater Assistant | LiveKit docs | Models | LiveKit Docs
r
some times working with real time model this error was retuned
t
Thanks — I understand this happens intermittently with the real-time model. I can help pinpoint the cause; a few targeted details will get us there faster. Please share: 1. The snippet around how you create/start the
AgentSession
and where
switch_language
is called. 2. Whether
switch_language
can be invoked by multiple concurrent triggers (user actions, timeouts, or other tasks). 3. Any earlier log lines showing session start, disconnects, or
aclose()
calls before the error. 4. Which real-time model and LiveKit Agents SDK version you’re using. 5. Whether this happens more when network conditions are poor or when many users are connected. If you prefer a quick mitigation while we debug, add a guarded call around `interrupt()`:
Copy code
try:
    session.interrupt()
except RuntimeError:
    # session not running — recreate or restart session here
    ...
Send the code/log snippets and answers above and I’ll propose a precise fix or a session-restart pattern that fits your flow.
r
try: session = AgentSession( # llm=openai.realtime.RealtimeModel(model="gpt-4o-mini-realtime-preview",modalities=["text"]), llm=openai.realtime.RealtimeModel( model="gpt-4o-realtime-preview-2024-12-17", modalities=["text"], api_key=os.getenv("OPENAI_API_KEY"), temperature=0.9, # Higher temperature for more creative, expressive responses ), # ElevenLabs TTS with emotional voice cloning # tts=elevenlabs.TTS( # voice_id="KU7fyKrDK75F9nWiORJr", # # voice_id=os.getenv("ELEVENLABS_VOICE_ID", "TX3LPaxmHKxFdv7VOQHJ"), # model="eleven_multilingual_v2", # api_key=os.getenv("ELEVENLABS_API_KEY"), # ), # tts=groq.TTS( # model="playai-tts", # voice="Calum-PlayAI", # ), # tts=deepgram.TTS( # model="aura-2-aries-en", # ), # tts=openai.TTS( # model="tts-1", # voice="alloy", # ), # stt = openai.STT( # model="whisper-1", # api_key=os.getenv("OPENAI_API_KEY"), # ), # stt = deepgram.STT( # model="nova-3", # language="en", # ), # llm = openai.LLM( # model="gpt-4o", # api_key=os.getenv("OPENAI_API_KEY"), # max_completion_tokens=500, # # temperature=0.6, # # top_p=0.9, # ), # llm=openai.realtime.RealtimeModel( # # model="gpt-4o-realtime-preview-2025-06-03", # model="gpt-realtime", # modalities=["text"], # api_key=os.getenv("OPENAI_API_KEY"), # temperature=0.6, # ), tts=openai.TTS( model="tts-1", voice="ash", ), # turn_detection=EnglishModel(), # vad=silero.VAD.load(), # tts=elevenlabs.TTS( # voice_id="KU7fyKrDK75F9nWiORJr", # model="eleven_multilingual_v2", # api_key=os.getenv("ELEVENLABS_API_KEY"), # ), # turn_detection=Eng/lishModel(), # vad=ctx.proc.userdata["vad"], ) logger.info("Using OpenAI Realtime Model with ElevenLabs TTS for expressive speech") except Exception as e: logger.warning(f"Failed to initialize Realtime API, falling back to standard LLM: {e}") # error_audio_path = os.path.join(pathlib.Path(file).parent.absolute(), "sounds/started.wav") # start_audio_path = os.path.join(pathlib.Path(file).parent.absolute(), "sounds/started.wav") # # Initialize background sound player # background_sound_player = BackgroundSoundPlayer(start_audio_path) # Track speaking state to prevent self-interruption is_speaking = False @session.on("error") def on_error(ev: ErrorEvent): if ev.error.recoverable: logger.info(f"Recoverable error occurred: {ev.error}") # For API connection errors, try to maintain the session if "APIConnectionError" in str(ev.error) or "connection" in str(ev.error).lower(): logger.info("API connection issue detected, session will retry automatically") return logger.error(f"Unrecoverable error occurred: {ev.error}") # Stop background sound on unrecoverable error # background_sound_player.stop_playing() # Play custom error sound try: # session.say( # "Sorry, I'm experiencing a technical issue. Please try speaking again.", # audio=audio_frames_from_file(error_audio_path), # allow_interruptions=False, # ) # json_object = json.load(open('current_state.json','r',encoding='utf-8')) # json_object["error_occurred"] = True # json.dump(json_object, open('current_state.json', 'w', encoding='utf-8')) pass except Exception as e: logger.error(f"Failed to play error message: {e}") # @session.on("agent_started_thinking") # def on_agent_thinking(): # logger.debug("Agent started processing input") # @session.on("agent_stopped_thinking") # def on_agent_stopped_thinking(): # logger.debug("Agent finished processing input") # @session.on("agent_started_speaking") # def on_ready(): # logger.info("Agent is now speaking - session is active!") # background_sound_player_started.start_playing() # assistant = Assistant() # Create agent with MCP tools integration agent = await MCPToolsIntegration.create_agent_with_tools( agent_class=Assistant, mcp_servers=[mcp_server], room_context=room_context ) # Start background sound BEFORE LiveKit initialization # background_sound_player.start_playing() logger.info("Playing initialization sound while LiveKit starts...") await session.start( room=ctx.room, agent=agent, room_input_options=RoomInputOptions( # Enhanced noise cancellation and echo suppression for Raspberry Pi setup noise_cancellation=noise_cancellation.BVCTelephony(), ), ) # Stop background sound - LiveKit is now fully initialized # background_sound_player.stop_playing() logger.info("LiveKit fully initialized!") mic_off() play_sound_sync('sounds/first_start_voice.wav') mic_on() # session_time_stamp = { # "session_loading": False, # "current_time": time.strftime("%Y-%m-%d %H:%M:%S"), # "session_started":True # } current_state = json.load(open('current_state.json','r',encoding='utf-8')) current_state["session_started"] = True current_state["session_loading"] = False json.dump(current_state, open('current_state.json', 'w', encoding='utf-8')) @session.on("agent_state_changed") def on_agent_state_changed(ev: AgentStateChangedEvent): print(f"Agent state changed: {ev.new_state}") if ev.new_state == "speaking": current_time=time.strftime("%Y-%m-%d %H:%M:%S") print(f"Agent started speaking at {current_time}") # json_object = json.load(open('current_state.json','r',encoding='utf-8')) # json_object["latest_agent_speaking_time"] = current_time # json.dump(json_object, open('current_state.json', 'w', encoding='utf-8')) elif ev.new_state == "listening": print("Agent is now listening") current_time=time.strftime("%Y-%m-%d %H:%M:%S") print(f"Agent is now listening at {current_time}") # play audio asynchronously from pyaudio # Use session.say() for the greeting instead of generate_reply() # await session.say( # "Hello! I'm kkkk. How can I help you today?", # allow_interruptions=True # ) if name == "__main__": agents.cli.run_app(agents.WorkerOptions( entrypoint_fnc=entrypoint, port=1100, initialize_process_timeout=1300 # 5 minutes )) this is my current code
t
Thanks — this is helpful. I reviewed your code and the intermittent RuntimeError ("AgentSession isn't running") is caused by calls like
session.interrupt()
or other session methods running when the session has already closed or hasn't finished starting. What to change (short, actionable): 1. Guard session calls with
session.is_running
• Before any
session.interrupt()
,
session.say()
, or similar, check:
Copy code
if session.is_running:
    session.interrupt()
1. Register event handlers safely • Register or at least guard event handlers so they don't call session methods after close. Either: ◦ Register handlers after
await session.start(...)
, or ◦ In handlers, check
session.is_running
before calling session methods. 1. Wrap critical calls in try/except • Catch RuntimeError to avoid uncaught tasks:
Copy code
try:
    session.interrupt()
except RuntimeError:
    logger.warning("Session not running; skipping interrupt")
1. Do not reuse a closed AgentSession • If you need to change language or fully reinitialize, create a new AgentSession instance and
await session.start(...)
again. Do not call start/restart on a session that has closed. 1. Add a close listener and set a local flag • On
"close"
event set a flag (or update your
current_state.json
) so other tasks know the session is no longer valid and won’t attempt actions. Quick places to apply these in your code: • In your
@session.on("error")
handler: check
session.is_running
before
session.say()
/
session.interrupt()
. • Wherever
switch_language
runs: check
session.is_running
or catch RuntimeError and recreate the session with new language settings. • Surround
await session.start(...)
with try/except and log startup success before any other session usage. If you want, paste your
switch_language
function or the exact spot where you call
session.interrupt()
and I’ll give a minimal patched snippet that fits your flow. Sources: Agent session | LiveKit docs | Voice AI quickstart | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Events and error handling | LiveKit docs | Job lifecycle | LiveKit docs