some-breakfast-27057
09/30/2025, 12:27 PMpython
# 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.tall-airline-16756
09/30/2025, 12:27 PMtall-airline-16756
09/30/2025, 12:28 PMRealtimeSession 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.tssome-breakfast-27057
10/07/2025, 7:53 PMtall-airline-16756
10/07/2025, 7:54 PMpip 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:
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 Docssome-breakfast-27057
10/07/2025, 7:55 PMtall-airline-16756
10/07/2025, 7:55 PMlk.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