some-breakfast-27057
09/28/2025, 9:34 AMtall-airline-16756
09/28/2025, 9:34 AMtall-airline-16756
09/28/2025, 9:34 AMkeep_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!some-breakfast-27057
09/28/2025, 9:35 AMpython
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?tall-airline-16756
09/28/2025, 9:36 AMkeep_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.tssome-breakfast-27057
09/28/2025, 9:38 AMpython
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?
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.tall-airline-16756
09/28/2025, 9:39 AMAudioStream 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::Agentssome-breakfast-27057
09/28/2025, 9:43 AMtall-airline-16756
09/28/2025, 9:43 AMawait 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!some-breakfast-27057
09/28/2025, 9:44 AMtall-airline-16756
09/28/2025, 9:44 AMAgentSession. 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::Agentssome-breakfast-27057
09/28/2025, 9:46 AMAgentSession. 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...tall-airline-16756
09/28/2025, 9:46 AMAgentSession 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:
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!some-breakfast-27057
09/28/2025, 9:48 AMtall-airline-16756
09/28/2025, 9:48 AMAgentSession. 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!