Subject: RealtimeSession._main_task and WebSocket ...
# ask-ai
s
Subject: RealtimeSession._main_task and WebSocket tasks not terminating after model.aclose(), causing memory leak We're experiencing a critical memory leak in our LiveKit Agents application using OpenAI Realtime. SYMPTOMS: - RealtimeSession._main_task and RealtimeSession._run_ws tasks remain alive for 5+ seconds after calling await model.aclose() - This causes duplicate sessions (count=2) when recreating agents for context switching - Memory grows +10-12 MB per agent recreation and never drops - Baseline memory: 121 MB → 131 MB → 133 MB → 144 MB over 3 session recreations WHAT WE'VE TRIED: 1. Manually cancelling session._main_task before aclose() - tasks still timeout 2. Calling await session._ws.close() before model.aclose() - no effect 3. Waiting up to 5 seconds for tasks to die - they timeout every time 4. Clearing all global references before closing - doesn't help CODE SNIPPET:
Copy code
python
# Cancel the main task
session = old_agent._model.session()
session._main_task.cancel()

# Close the model
await old_agent._model.aclose()

# Wait for tasks to die
for i in range(10):  # Wait up to 5 seconds
    realtime_tasks = [t for t in asyncio.all_tasks()
                      if "RealtimeSession" in str(t.get_coro())]
    if not realtime_tasks:
        break
    await asyncio.sleep(0.5)

# Result: TIMEOUT every time - 3-6 zombie tasks remain!
Line 890: ⏳ Waiting for 6 old RealtimeSession tasks to terminate... Line 891-899: (repeats for 5 seconds) Line 900: ⚠️ Timeout waiting for old tasks, proceeding anyway Line 907: Top task types: {'RealtimeSession._main_task': 2, ← DUPLICATES!_ 'RealtimeSession._run_ws._send_task': 2,_ 'RealtimeSession._run_ws._recv_task': 2}_ QUESTIONS: 1. What is the correct way to ensure RealtimeSession tasks fully terminate before creating a new RealtimeModel? 2. Is there a model.close() method that properly closes WebSocket connections synchronously? 3. Should we be using a different cleanup pattern for frequent context switching (every 2-3 minutes)? 4. Is this a known issue with the OpenAI Realtime integration in LiveKit Agents? Our use case requires frequent agent recreation for a language learning app where users progress through lessons. The current behavior makes this impossible due to memory accumulation.
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.
I'm here to help you address the memory leak and make sure
RealtimeSession
tasks in LiveKit Agents are properly terminated. Let’s walk through some important steps and tips together: 1. Task Lifecycle Management: LiveKit Agents use structured cancellation patterns to manage task lifecycles. It’s really important to call
RealtimeSession.aclose()
, which takes care of canceling the
_main_task
and closing active sessions. This step helps release resources effectively. 2. WebSocket Cleanup: Before calling
aclose()
, try explicitly closing WebSocket connections with
await session._ws.close()
. This helps make sure all network resources are properly freed. 3. Pending Futures: Don’t forget to cancel any pending futures like
pendingGenerationFut
to avoid stalled operations. You can use
asyncio.gather(*tasks, return_exceptions=True)
during your cleanup to handle this smoothly. 4. Finally Blocks: Using
finally
blocks in your cleanup logic is a great practice—it ensures resources get released even if something goes wrong during task execution. 5. Session Tracking: LiveKit keeps track of active sessions using a weak reference set. Make sure your application isn’t holding onto unnecessary references to sessions, since that can block proper cleanup. If you’re switching contexts frequently, it might help to create a centralized cleanup routine that makes sure all tasks and sessions are closed before starting new ones. And if you still run into issues, don’t worry—we can dig deeper into your specific setup or look into updates for the LiveKit integration together. Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | plugins/google/src/beta/realtime/realtime_api.ts
s
how easy it is to switch from open ai realtime to gemini flash audio
t
Switching from OpenAI Realtime to Gemini Flash Audio in LiveKit Agents is quite simple, and I’m here to help you through it step-by-step. Here’s how you can do it: 1. Install the Google Plugin: - For Python:
pip install livekit-plugins-google
- For Node.js:
npm install @livekit/agents-plugin-google
2. Authenticate with Google: - Use a Google AI Studio API Key or Vertex AI credentials. - Set the API key via environment variable:
export GOOGLE_API_KEY=your_gemini_api_key
. 3. Replace OpenAI Realtime with Gemini Flash Audio: - Update your code to use
google.beta.realtime.RealtimeModel
. - Here’s an example for Python:
Copy code
from livekit.plugins import google
session = AgentSession(
    llm=google.beta.realtime.RealtimeModel(
        model="gemini-2.5-flash-preview-native-audio-dialog",
        voice="Puck",
        api_key=os.getenv("GOOGLE_API_KEY"),
        modalities=["AUDIO"],
    )
)
4. Supported Models: You can use models like
gemini-2.5-flash-preview-native-audio-dialog
for native audio support. 5. Optional Configurations: Feel free to customize parameters such as
temperature
,
maxOutputTokens
, and
enableAffectiveDialog
to best suit your needs. This integration will help you enjoy low-latency, expressive voice conversations smoothly. If you have any questions or need a hand with any part of this, just let me know—I’m here to support you! Sources: plugins/google/src/beta/realtime/api_proto.ts | livekit-plugins/livekit-plugins-google/livekit/plugins/google/beta/realtime... | Realtime model plugins | LiveKit Docs | Large language models (LLM) | LiveKit Docs | Gemini Live API plugin | LiveKit Docs
s
and the text will stream and so on ?
t
Hi there! I wanted to share some helpful info about Gemini Flash Audio in LiveKit Agents. Currently, it doesn’t support true text streaming because the Gemini TTS plugin disables streaming functionality. But don’t worry—LiveKit has some great alternatives for handling text and transcription that might work perfectly for you: 1. Transcription Streaming: LiveKit Agents can publish transcriptions in real-time to the frontend using the
lk.transcription
text stream topic. This means you’ll see the text appear word-by-word as the agent speaks, keeping everything nicely synchronized. 2. TTS-Aligned Transcriptions: If you enable this, transcription output is synchronized with speech timing. For Gemini, this alignment happens at the sentence level, which helps keep things clear and organized. 3. Text-Only Sessions: If you prefer, agents can respond with text instead of audio by disabling audio output in
RoomOutputOptions
. These text responses are sent without speech synchronization, offering a straightforward way to handle text communication. 4. Agent Session Events: You can also listen to the
conversation_item_added
event to keep track of text input or output as it gets added to the chat history. If you’d like, I’m here to help you implement any of these options or answer any questions you have. Just let me know! Sources: Text and transcriptions | LiveKit Docs | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | Gemini Live API plugin | LiveKit Docs | agents/src/voice/io.ts | livekit-agents/livekit/agents/voice/agent.py