"When we recreate an AgentSession while keeping au...
# ask-ai
s
"When we recreate an AgentSession while keeping audio subscriptions active (keep_audio_subscriptions=True), are we inadvertently creating duplicate audio processing pipelines? Our flow: 1. Home session active with audio subscription 2. User clicks 'Start Lesson' 3. We keep audio subscription but create new AgentSession 4. CPU spikes with duplicate AudioStream._run tasks Is this expected behavior?"
t
Thanks for reaching out, MBMBMB. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thank you for bringing this up! The behavior of recreating an AgentSession with
keep_audio_subscriptions=True
isn’t clearly documented, so I completely understand why this might be a bit confusing. Could you please share if you’re using any custom implementation or a specific SDK version? Also, are you noticing duplicate audio streams in the logs, or is it mainly just the CPU spikes that stand out? I’m here to help you figure this out!
s
Here are the details: SDK Version: - livekit-agents==0.10.0 - livekit==0.18.3 Our Implementation: We have a custom session recreation manager that handles context switches. When users move from "home" to a "lesson room", we: 1. Close the old AgentSession: - agent._model.aclose() - session.aclose() - Cancel responsiveness tasks - Garbage collection 2. Create new AgentSession with keep_audio_subscriptions=True What We're Seeing in Logs: BEFORE transition (home): - Tasks: 28 total - Audio tasks: minimal - CPU: ~50% baseline AFTER transition (room): - Tasks: 26 total (but different composition) - NEW audio tasks appear: * AudioStream._run: 0 → 1 * _ParticipantAudioInputStream._forward_task: 0 → 1 - CPU: Spikes and stays elevated The Suspicious Part: Even though task count is similar, the TYPES of tasks change. The appearance of AudioStream._run suggests a new audio pipeline was created, but we suspect the old one wasn't fully cleaned up. Our Monitoring Code:
Copy code
python
all_tasks = asyncio.all_tasks()
audio_tasks = [t for t in all_tasks if 'AudioStream._run' in t.get_name()]
logger.info(f"Audio tasks: {len(audio_tasks)}")
Question: When keep_audio_subscriptions=True, does LiveKit create a new AudioStream for the existing subscription? If so, how do we ensure the old AudioStream is properly disposed? We're essentially asking: Is there a hidden audio processing pipeline that survives session.aclose() when subscriptions are kept?
t
Thank you for your question! I understand that the behavior of
keep_audio_subscriptions=True
during
AgentSession
recreation isn't clearly documented, so let's explore this together. Here are some insights and friendly recommendations based on related functionality that might help: • AudioStream Lifecycle: It's important to properly close an
AudioStream
by calling its
aclose()
method. This helps unsubscribe the stream from the FFI queue and prevents any resource leaks, keeping things tidy. • RoomIO Management: The
RoomIO
class thoughtfully manages subscriptions for you. When a participant changes, it closes old streams via
_close_stream()
, which internally calls
self._stream.aclose()
. This automatic cleanup is really handy! • AgentSession Recreation: When an
AgentSession
restarts, new audio tasks like
_forward_audio_atask
are created, which means streams get reinitialized. It’s key to properly clean up old tasks and streams to avoid any duplication or conflicts. Here are some recommendations to keep things running smoothly: 1. Make sure to explicitly close any
AudioStream
with
await stream.aclose()
when you’re done with it. 2. Confirm that
RoomIO
or any custom stream managers you use are cleaning up streams properly during disconnections or session restarts. 3. Keep an eye out for any lingering references or tasks by using tools like
asyncio.all_tasks()
, which can help you spot potential leaks early on. If you’d be willing to share a bit more about where
keep_audio_subscriptions
is defined or what you expect it to do, I’d be more than happy to dive deeper and help analyze its impact with you. Sources: livekit-rtc/livekit/rtc/_proto/audio_frame_pb2.pyi | livekit-agents/livekit/agents/voice/agent_session.py | agents/src/voice/room_io/room_io.ts
s
Thank you! This confirms our suspicion. A few specific follow-ups: 1. Where is the AudioStream reference? We're using the standard AgentSession pattern:
Copy code
python
   session = await JobProcess.create_session(ctx, agent)
   await session.start(agent, room)
We never directly access AudioStream. How can we get a reference to close it explicitly? 2. The keep_audio_subscriptions flag This is our custom flag in session recreation. We thought it would reuse existing audio streams, but you're saying new ones are always created? Should we: a) Remove this flag and always unsubscribe/resubscribe? b) Find the AudioStream instances and close them manually? 3. The RoomIO cleanup You mentioned RoomIO._close_stream(). Is this exposed in the Python SDK? We see: - Room object - AgentSession object - But no direct access to RoomIO 4. Proposed Solution Would this work?
Copy code
python
   # Before creating new session
   for task in asyncio.all_tasks():
       if 'AudioStream._run' in task.get_name():
           task.cancel()

   # Or is there a cleaner way?
5. Architecture Question Given that new audio tasks are always created, would it be better to: - Use a single persistent AgentSession and never recreate? - Accept the overhead and ensure proper cleanup? We're trying to avoid the CPU accumulation from these orphaned AudioStreams during context switches.
t
Thank you for your follow-up questions! Here are some answers and recommendations that I hope will help you navigate these issues smoothly: 1. Accessing and Closing AudioStream: Usually,
AudioStream
instances are handled behind the scenes. But if you find yourself needing to close them explicitly, you can create an
AudioStream
from the track and then call
await stream.aclose()
once you're done. If you’re not directly managing these streams, just make sure to properly await
AgentSession.aclose()
, which takes care of cleaning up related resources, including audio streams. 2. Custom keep_audio_subscriptions Flag: If you notice that this flag is causing new audio streams to be created without cleaning up the old ones, it might be best to remove it and simply unsubscribe and resubscribe as needed. Alternatively, you can keep track of your
AudioStream
instances manually and close them with
await stream.aclose()
to keep things tidy. 3. RoomIO Cleanup: The method
RoomIO._close_stream()
isn’t available in the Python SDK since it’s meant for internal use to manage stream lifecycles. Instead, rely on
AgentSession.aclose()
to handle the cleanup of
RoomIO
and all its associated streams. 4. Proposed Solution: Your idea of canceling tasks with
asyncio.all_tasks()
works, but there’s a cleaner approach. I recommend explicitly closing streams using
await stream.aclose()
or ensuring that you await
AgentSession.aclose()
, which will take care of all the cleanup gracefully. 5. Architecture Recommendation: Keeping a single persistent
AgentSession
can really help reduce overhead and prevent orphaned streams from piling up. If you do need to recreate sessions, just be sure to await
aclose()
on the session and any streams you manage manually to keep everything running smoothly. Please don’t hesitate to reach out if you’d like me to clarify anything further or assist you with putting these recommendations into practice. I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_session.py | examples/multiple_connections.py | Inside a session | LiveKit Docs | Docs::Agents
s
but the issue is when we dont recreate session agent is poluted by the previous dialogue and context
t
It sounds like you're encountering a situation where the agent retains context from the previous dialogue when the session isn’t recreated. No worries! You can handle this by explicitly resetting the agent’s state without having to recreate the entire session. Here are a few friendly approaches you might find helpful: 1. Reset Agent State: If the agent’s state is managed within the session, try looking for methods or APIs that let you reset its context. This might involve clearing the dialogue history or resetting some internal variables. 2. Selective Cleanup: Instead of recreating the whole session, you could pinpoint specific parts—like dialogue history or context variables—that need resetting, and clear those programmatically. 3. Session Recreation with Cleanup: If you do need to recreate the session, just make sure to properly clean up the previous one by calling
await session.aclose()
and closing any related resources, such as
AudioStream
instances. If you’d like, I’m here to help guide you through implementing any of these steps or to assist further with your setup. Just let me know!
s
how can i reset agent state ?
t
To help you reset the agent state, here are some friendly options you can try: 1. Full Reset via Session Recreation: The most reliable way to completely reset the agent state is to close and recreate the
AgentSession
. This will refresh all internal states like
_agentState
,
_chatCtx
, and error counters. Simply use
await session.aclose()
before starting a new session. 2. Partial Reset Without Recreation: If you'd prefer not to recreate the session, you can mimic a reset by: ◦ Using
update_agent()
to refresh the agent's internal activity. This will close the current activity and start a fresh one. ◦ Manually clearing application-level state, such as resetting
ChatContext
or any custom session variables you have in
UserData
. 1. Backend Refresh: If the issue seems related to backend services like LLM or TTS, you can restart the agent worker pool using this CLI command:
lk agent restart --id CA_MyAgentId
This will reinitialize backend services without affecting active sessions, though it won’t reset per-session attributes like
agentState
. If you’d like, I’m here to help you implement any of these options or even design a custom reset approach tailored to your agent’s needs. Just let me know! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Web and mobile frontends | LiveKit Docs | plugins/google/src/beta/realtime/realtime_api.ts | Agent deployment CLI reference | LiveKit Docs | Docs::Agents
s
Full Reset via Session Recreation: The most reliable way to completely reset the agent state is to close and recreate the
AgentSession
. This will refresh all internal states like
_agentState
,
_chatCtx
, and error counters. Simply use
await session.aclose()
before starting a new session. but this is causing us cpu stackup...
t
I understand how frustrating it can be when recreating the
AgentSession
leads to CPU stack-up. It usually means some resources or tasks from the previous session aren’t being fully cleaned up. Let’s walk through some steps that can help you resolve this: 1. Ensure Proper Cleanup: Before you recreate the session, it’s important to explicitly close all related resources. For example:
Copy code
await session.aclose()
for task in asyncio.all_tasks():
    if 'AudioStream' in task.get_name():
        task.cancel()
This helps make sure any lingering tasks, like audio streams, are properly stopped. 2. Monitor for Orphaned Tasks: You can use
asyncio.all_tasks()
to spot any tasks still running after the session closes. Logging these tasks can help confirm they’re being canceled as expected. 3. Optimize Session Recreation: If you do need to recreate the session, try to reduce the overhead by reusing parts where possible. For instance, keep shared resources like audio subscriptions and only reset the parts of the session that really need it. 4. Consider Persistent Sessions: If the CPU stacking issue continues, a good approach might be to use one persistent
AgentSession
and just reset the agent’s state (like clearing
ChatContext
or resetting custom variables) instead of recreating the whole session. Please feel free to reach out if you’d like help implementing these suggestions or if you want to dive deeper into debugging the CPU stack-up. I’m here to support you!
s
can we get a very fresh agent bhavior without session recreation ?
t
I completely understand wanting to refresh your agent’s behavior without the hassle of recreating the
AgentSession
. Let me walk you through some friendly and effective ways to do this: 1. Reset Chat Context: If your agent’s behavior depends on the conversation history, a great way to start fresh is by clearing the
ChatContext
programmatically. For instance:
session.chat_context.clear()
2. Reset Custom Variables: Are you using custom session variables in
UserData
? You can create a reset method to clear or reinitialize them, like this:
session.user_data.reset()
3. Refresh Agent Activity: Another handy approach is to use
update_agent()
. This will drain and close the current activity, then start a new one, resetting the agent’s internal logic and streaming context without needing to recreate the session. 4. Restart Backend Services: If the challenge is coming from backend services such as LLM or TTS, you can restart the agent worker pool using the CLI:
lk agent restart --id CA_MyAgentId
This will reinitialize the backend services smoothly without interrupting your session. I hope these options help you refresh your agent’s behavior while keeping your session intact. If you’d like, I’m here to guide you through implementing any of these solutions—just let me know!