brainy-pizza-19487
12/10/2025, 3:37 PMtall-airline-16756
12/10/2025, 3:37 PMtall-airline-16756
12/10/2025, 3:38 PMbrainy-pizza-19487
12/10/2025, 3:38 PMtall-airline-16756
12/10/2025, 3:39 PMawait room.localParticipant.sendText('Hello from client', { topic: 'lk.chat' });
1. Server/agent:
room.registerTextStreamHandler('lk.chat', (reader, participantInfo) => {
reader.readAll().then(text => {
console.log(`Received from ${participantInfo.identity}: ${text}`);
});
});
• Data packets (lower-level, packet-based, choose reliable/lossy)
await room.localParticipant.publishData(
new TextEncoder().encode('Hello server'),
{ reliable: true, topic: 'chat' }
);
The server listens for the data_received event to handle packets.
Would you like a sample for your SDK (JS/TS, iOS, or Android) or help wiring this into your server logic?
Sources: Sending text | LiveKit docs | Text and transcriptions | LiveKit docs | Data packets | LiveKit docsbrainy-pizza-19487
12/10/2025, 3:45 PMtall-airline-16756
12/10/2025, 3:45 PM// send string ID
await room.localParticipant.publishData(
new TextEncoder().encode('my-id-123'),
{ reliable: true, topic: 'client.id' }
);
Android (Kotlin) — publish a data packet:
val idBytes = "my-id-123".toByteArray(Charsets.UTF_8)
localParticipant.publishData(idBytes, LivekitModels.DataPacket_Kind.RELIABLE, "client.id")
Web (TS) — send as text stream (alternative):
await room.localParticipant.sendText('my-id-123', { topic: 'client.id' });
Python server — handle data packets (room data_received event) and text streams:
# Pseudo-code showing both handlers
def on_data_received(participant, payload, kind, topic):
id_str = payload.decode('utf-8')
print("Data packet from", participant.identity, "topic:", topic, "id:", id_str)
def on_text_stream(room, reader, participant_info):
text = reader.read_all() # reads full text stream
print("Text stream from", participant_info.identity, "text:", text)
# Register handlers on your Room object:
room.on("data_received", on_data_received)
room.register_text_stream_handler("client.id", on_text_stream)
Notes:
• Use a clear topic (e.g., client.id) so the server can filter messages.
• Encode strings as UTF-8 when sending; decode on the server.
• Use reliable: true for guaranteed delivery, or lossy for non-critical IDs.
Do you want a complete runnable example for one method (web→Python or Android→Python)?brainy-pizza-19487
12/11/2025, 5:51 AMtall-airline-16756
12/11/2025, 5:51 AMimport os
import asyncio
from livekit import api
async def entrypoint(ctx):
# wait desired timeout (seconds)
await asyncio.sleep(30)
api_client = api.LiveKitAPI(
os.getenv("LIVEKIT_URL"),
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
await api_client.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
Node.js example (agent / worker)
import { RoomServiceClient } from 'livekit-server-sdk';
export default defineAgent({
entry: async (ctx: JobContext) => {
await new Promise(r => setTimeout(r, 30000));
const roomService = new RoomServiceClient(
process.env.LIVEKIT_URL,
process.env.LIVEKIT_API_KEY,
process.env.LIVEKIT_API_SECRET,
);
await roomService.deleteRoom(ctx.room.name);
},
});
Alternatives
• If you only want the agent to stop (not delete the room), call the agent shutdown API/method (e.g., session.shutdown() / ctx.shutdown()).
• To enforce inactivity-based timeouts, run a timer that resets on activity and call delete_room when it elapses.
Would you like a complete Android/web client + Python agent example, or help wiring this into your existing agent code?
Sources: Job lifecycle | LiveKit docs | server-sdk-js | livekit/livekit_composite | DeepWiki | Managing rooms | LiveKit docsbrainy-pizza-19487
12/11/2025, 5:53 AMtall-airline-16756
12/11/2025, 5:54 AMimport os
import asyncio
from datetime import datetime, timedelta
from livekit import api
from livekit.models import Room, ParticipantInfo # adjust imports per SDK
INACTIVITY_SECONDS = 300 # timeout after 5 minutes
class RoomMonitor:
def __init__(self, room_name):
self.room_name = room_name
self.last_activity = datetime.utcnow()
self._task = None
self._stop = False
self.api_client = api.LiveKitAPI(
os.getenv("LIVEKIT_URL"),
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
def record_activity(self):
self.last_activity = datetime.utcnow()
async def start(self):
# start background monitor
self._task = asyncio.create_task(self._monitor_loop())
async def stop(self):
self._stop = True
if self._task:
await self._task
async def _monitor_loop(self):
while not self._stop:
now = datetime.utcnow()
elapsed = (now - self.last_activity).total_seconds()
remaining = INACTIVITY_SECONDS - elapsed
if remaining <= 0:
await self._handle_timeout()
return
# sleep a short interval to allow reset
await asyncio.sleep(min(remaining, 5))
async def _handle_timeout(self):
# delete the room (disconnects all participants)
try:
await self.api_client.room.delete_room(api.DeleteRoomRequest(room=self.room_name))
print(f"Deleted room {self.room_name} due to inactivity")
except Exception as e:
print("Failed to delete room:", e)
# Example integration with an agent job context
async def entrypoint(ctx): # ctx.room.name expected
monitor = RoomMonitor(ctx.room.name)
# Hook events: update monitor.record_activity() on relevant events
# Example: participant joins/leaves, data_received, track_published, text stream, etc.
# Pseudo-handler registration - replace with your actual event binding
def on_participant_update(participant: ParticipantInfo, event_type: str):
monitor.record_activity()
def on_data_received(participant, payload, kind, topic):
monitor.record_activity()
# Register your actual event handlers on the room/session object here.
# For demonstration, assume ctx.room provides `on` and `register_text_stream_handler`.
ctx.room.on("participant_joined", lambda p: monitor.record_activity())
ctx.room.on("participant_left", lambda p: monitor.record_activity())
ctx.room.on("data_received", lambda p, payload, kind, topic: monitor.record_activity())
ctx.room.register_text_stream_handler("client.id", lambda reader, pinfo: monitor.record_activity())
await monitor.start()
# Keep the agent alive while the room is active. This example waits until monitor stops (deletes room)
# or the agent is explicitly shut down.
try:
while True:
await asyncio.sleep(60)
except asyncio.CancelledError:
# graceful shutdown requested
await monitor.stop()
Notes and best practices
• Events to treat as activity: participant join/leave, track publish/unpublish, data messages, text streams, or custom application events.
• Use a short sleep (e.g., 1–5s) in the loop so activity resets quickly.
• Ensure the API credentials used by the agent have room-management permissions.
• If you prefer the agent to leave but not delete the room, call ctx.shutdown() or your session shutdown method instead of delete_room.
• Consider persisting last-activity for redundancy if multiple workers can monitor the same room.
Want this adapted to your exact room event API (show me your room object or agent framework) or a version that only disconnects the agent instead of deleting the room?brainy-pizza-19487
12/11/2025, 9:21 AMtall-airline-16756
12/11/2025, 9:21 AMasync def entrypoint(ctx: JobContext), registers room event handlers (participant joins/leaves, data_received, text streams, VAD events), resets an inactivity timer on activity, and on timeout both disconnects the agent and calls the server API to delete the room.
Before I produce the code: which LiveKit Python packages and agent framework are you using in your project? (options: livekit + livekit.agents from the Agents SDK, or a custom wrapper). Also confirm your preferred activity signals to reset the timer (choose any combination):
• participant join/leave
• data messages / text streams
• track published/unpublished
• VAD events (user_started_speaking/user_stopped_speaking)
Once you confirm, I will give the adapted, runnable example.
Sources: Job lifecycle | LiveKit docs | Managing participants | LiveKit docs | examples/voice_agents | livekit/livekit_composite | DeepWiki | Agents Framework | livekit/livekit_composite | DeepWiki | How to detect and handle silence during callsbrainy-pizza-19487
12/11/2025, 9:23 AMtall-airline-16756
12/11/2025, 9:23 AMasync def entrypoint(ctx: JobContext) as the agent entrypoint.
• Resets an inactivity timer on participant join/leave and on user_speech_committed / agent_speech_committed events.
• On timeout: disconnects the agent and calls the server API to delete the room.
• Assumes environment variables: LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET.
Copy and adapt the values and imports as needed for your environment.
import os
import asyncio
import time
import logging
from livekit import api
from livekit.agents import JobContext
from livekit.agents import cli # or your agent CLI entrypoint module
# Configuration
INACTIVITY_SECONDS = 300 # e.g., 5 minutes
CHECK_INTERVAL = 1 # seconds between inactivity checks
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("inactivity-agent")
async def _delete_room_via_api(room_name: str):
lkapi = api.LiveKitAPI(
os.getenv("LIVEKIT_URL"),
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
try:
await lkapi.room.delete_room(api.DeleteRoomRequest(room=room_name))
logger.info(f"Deleted room {room_name} via API")
finally:
await lkapi.aclose()
@cli.entrypoint
async def entrypoint(ctx: JobContext):
"""
Agent entrypoint that monitors participant join/leave and speech-committed events.
On inactivity, disconnects agent and deletes the room.
"""
room_name = ctx.room.name
logger.info(f"Agent starting for room: {room_name}")
last_activity = time.time()
monitor_task = None
# Helper to update activity timestamp
def record_activity():
nonlocal last_activity
last_activity = time.time()
logger.debug("Activity recorded, timer reset")
# Participant join/leave handlers
def on_participant_joined(participant):
logger.info(f"Participant joined: {participant.identity}")
record_activity()
def on_participant_left(participant):
logger.info(f"Participant left: {participant.identity}")
record_activity()
# Speech-committed handlers (these events are emitted by your agent/session code)
# Bind to ctx.room events or whichever event emitter you have that posts these strings.
def on_user_speech_committed(evt):
logger.info("user_speech_committed")
record_activity()
def on_agent_speech_committed(evt):
logger.info("agent_speech_committed")
record_activity()
# Register room event handlers
# ctx.room provides `.on(event_name, callback)` in the agent framework.
# If your framework uses a different registration API, adapt these lines.
ctx.room.on("participant_joined", on_participant_joined)
ctx.room.on("participant_left", on_participant_left)
# Bind your speech-committed events. If these are emitted from a session or LLM component,
# register on that component. This example assumes the room emits them.
ctx.room.on("user_speech_committed", on_user_speech_committed)
ctx.room.on("agent_speech_committed", on_agent_speech_committed)
# Background monitor task
async def inactivity_monitor():
try:
while True:
await asyncio.sleep(CHECK_INTERVAL)
elapsed = time.time() - last_activity
if elapsed >= INACTIVITY_SECONDS:
logger.info(f"No activity for {elapsed:.0f}s (threshold {INACTIVITY_SECONDS}s). "
f"Disconnecting agent and deleting room {room_name}.")
# 1) Disconnect the agent from the room (local participant leaves)
try:
# ctx.room.disconnect() or ctx.shutdown() depending on API; handle both options
if hasattr(ctx.room, "disconnect"):
await ctx.room.disconnect()
logger.info("Agent disconnected from room")
elif hasattr(ctx, "shutdown"):
await ctx.shutdown()
logger.info("Agent shutdown called")
except Exception as e:
logger.error(f"Error disconnecting agent: {e}")
# 2) Delete the room via server API
try:
await _delete_room_via_api(room_name)
except Exception as e:
logger.error(f"Error deleting room via API: {e}")
break
except asyncio.CancelledError:
logger.info("Inactivity monitor cancelled")
raise
# Start monitor
monitor_task = asyncio.create_task(inactivity_monitor())
# Connect agent/session as usual (auto-subscribe options as needed)
# Keep the entrypoint alive while agent is connected and monitoring
try:
await ctx.connect() # keep or adapt to your connect call
logger.info("Agent connected; monitoring activity...")
# Wait until room disconnect or monitor triggers deletion
while ctx.room.connected:
await asyncio.sleep(1)
except asyncio.CancelledError:
logger.info("Entrypoint cancelled")
finally:
if monitor_task:
monitor_task.cancel()
try:
await monitor_task
except asyncio.CancelledError:
pass
logger.info("Agent entrypoint exiting")
Notes and adjustments:
• This example assumes ctx.room.on(event_name, cb) and ctx.connect() exist in your agent framework for v1.0.20. If your SDK uses slightly different handler names (for example on_participant_joined / on_participant_left) replace registration calls accordingly.
• If user_speech_committed and agent_speech_committed are emitted from your speech/session component rather than the room, register those handlers on that component (e.g., session.on("user_speech_committed", ...)) but keep record_activity() logic the same.
• Ensure the API key/secret used has permission to delete rooms.
• Adjust INACTIVITY_SECONDS to your desired timeout.
Would you like me to adapt the registration lines to a specific event API signature if you share the exact ctx.room methods or the session object where the speech-committed events are emitted?brainy-pizza-19487
12/11/2025, 9:29 AMuser_speech_committed and agent_speech_committed are emitted from your speech/session componenttall-airline-16756
12/11/2025, 9:29 AMasync def entrypoint(ctx: JobContext) as the agent entrypoint.
• Resets an inactivity timer on participant join/leave (room events) and on user_speech_committed / agent_speech_committed from the speech/session component.
• On timeout: disconnects the agent and deletes the room via the LiveKit server API.
• Assumes env vars: LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET.
Adjust imports if your environment places modules differently.
import os
import time
import asyncio
import logging
from livekit import api
from livekit.agents import JobContext, cli
from livekit.agents.voice import AgentContext # speech/session component
# Configuration
INACTIVITY_SECONDS = 300 # seconds before taking action
CHECK_INTERVAL = 1 # monitor check interval
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("inactivity-agent")
async def _delete_room_via_api(room_name: str):
lkapi = api.LiveKitAPI(
os.getenv("LIVEKIT_URL"),
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
try:
await lkapi.room.delete_room(api.DeleteRoomRequest(room=room_name))
logger.info(f"Deleted room {room_name} via API")
finally:
await lkapi.aclose()
@cli.entrypoint
async def entrypoint(ctx: JobContext):
room_name = ctx.room.name
logger.info(f"Agent entrypoint starting for room: {room_name}")
# Track last activity timestamp
last_activity = time.time()
def record_activity():
nonlocal last_activity
last_activity = time.time()
logger.debug("Activity recorded; timer reset")
# Room participant handlers
def on_participant_joined(participant):
logger.info(f"Participant joined: {participant.identity}")
record_activity()
def on_participant_left(participant):
logger.info(f"Participant left: {participant.identity}")
record_activity()
# Create/start your speech/session component (AgentContext is an example)
# Adapt instantiation to your real session setup (STT/TTS/LLM config as needed)
session = AgentContext() # adjust constructor with required args
# Speech/session handlers: these events are emitted by the session component
def on_user_speech_committed(evt):
logger.info("user_speech_committed")
record_activity()
def on_agent_speech_committed(evt):
logger.info("agent_speech_committed")
record_activity()
# Register handlers on the session component
session.on("user_speech_committed", on_user_speech_committed)
session.on("agent_speech_committed", on_agent_speech_committed)
# Register room event handlers
ctx.room.on("participant_joined", on_participant_joined)
ctx.room.on("participant_left", on_participant_left)
# Background monitor task
async def inactivity_monitor():
try:
while True:
await asyncio.sleep(CHECK_INTERVAL)
elapsed = time.time() - last_activity
if elapsed >= INACTIVITY_SECONDS:
logger.info(f"Inactivity {elapsed:.0f}s >= {INACTIVITY_SECONDS}s for room {room_name}. "
"Disconnecting agent and deleting room.")
# 1) Disconnect agent/session
try:
# If session has close/aclose methods
if hasattr(session, "aclose"):
await session.aclose()
logger.info("Session aclosed")
elif hasattr(session, "stop"):
await session.stop()
logger.info("Session stopped")
# Also attempt ctx.room.disconnect or ctx.shutdown if available
if hasattr(ctx.room, "disconnect"):
await ctx.room.disconnect()
logger.info("ctx.room.disconnect() called")
elif hasattr(ctx, "shutdown"):
await ctx.shutdown()
logger.info("ctx.shutdown() called")
except Exception as e:
logger.error(f"Error disconnecting agent/session: {e}")
# 2) Delete the room using server API
try:
await _delete_room_via_api(room_name)
except Exception as e:
logger.error(f"Error deleting room via API: {e}")
break
except asyncio.CancelledError:
logger.info("Inactivity monitor cancelled")
raise
monitor_task = asyncio.create_task(inactivity_monitor())
# Connect agent to the room (adapt options as needed)
try:
await ctx.connect()
logger.info("Agent connected to room; starting session")
# Start session bound to the room (adjust to your session API)
await session.start(ctx.room)
# Keep running until room disconnect or monitor triggers deletion
while getattr(ctx.room, "connected", True):
await asyncio.sleep(1)
except asyncio.CancelledError:
logger.info("Entrypoint cancelled")
except Exception as e:
logger.error(f"Entrypoint error: {e}")
finally:
monitor_task.cancel()
try:
await monitor_task
except asyncio.CancelledError:
pass
# Ensure session closed
try:
if hasattr(session, "aclose"):
await session.aclose()
except Exception:
pass
logger.info("Agent entrypoint exiting")
Notes:
• Replace AgentContext() and its lifecycle (start, aclose) with your actual speech/session class methods if different.
• If user_speech_committed / agent_speech_committed are emitted by a different object, register the handlers on that object instead of session.
• Ensure the API key/secret has room-delete permissions.
• Tune INACTIVITY_SECONDS as desired.
Would you like this adapted to include logging of which participant caused the last activity or to persist last-activity across restarts?brainy-pizza-19487
12/11/2025, 10:34 AMtall-airline-16756
12/11/2025, 10:34 AMsession.shutdown() cleanly stops the agent session: it disconnects the agent from the room, stops any running session tasks (e.g., VAD/LLM/TTS loops), and releases session resources so the agent can exit gracefully.
Key points:
• It disconnects the local agent participant but does not delete the room for all participants.
• It ensures ongoing background work (streams, handlers, timers) is stopped so cleanup is orderly.
• Use session.shutdown() when you want the agent to leave and clean up without calling the server API to delete the room; use delete_room (server API) when you need to close the room for everyone.brainy-pizza-19487
12/11/2025, 10:37 AMtall-airline-16756
12/11/2025, 10:37 AMdelete_room_on_close=True on the AgentSession, the room will be deleted when the agent session closes (for example when you call session.aclose() or session.shutdown()).
Key points:
• The room is deleted only when the agent session is explicitly closed by the agent; other causes of session end won’t automatically trigger this.
• It disconnects all participants because it calls the server-side delete_room.
• Use it for convenience in short-lived sessions; if you need tighter control (e.g., ensure recordings/egress finish), call the server API delete_room yourself after cleanup.
Would you like a short code snippet showing AgentSession(..., delete_room_on_close=True) and a graceful shutdown sequence?
Sources: Agent session | LiveKit docs | Job lifecycle | LiveKit docsbrainy-pizza-19487
12/11/2025, 10:38 AMtall-airline-16756
12/11/2025, 10:38 AMdelete_room_on_close=True, how to start it, record activity, and then gracefully close the session so the room is deleted. It uses session.shutdown() (or await session.aclose()), both of which trigger deletion when that flag is set.
import asyncio
from livekit.agents.voice import AgentSession # adjust import if different
from livekit.agents import JobContext, cli
# create session with auto-delete enabled
session = AgentSession(
stt="assemblyai/universal-streaming:en",
llm="openai/gpt-4o",
tts=None,
delete_room_on_close=True, # <-- room will be deleted when session closes
)
@cli.entrypoint
async def entrypoint(ctx: JobContext):
# start the session (binds to ctx.room inside)
await session.start(ctx.room)
# example: record activity (reset your inactivity timer elsewhere)
def on_user_speech_committed(evt):
# update last-activity timestamp
pass
session.on("user_speech_committed", on_user_speech_committed)
session.on("agent_speech_committed", lambda evt: None)
# ... your logic, monitoring, etc.
# When you want to close and delete the room:
# Option A: graceful shutdown (synchronous-style)
await session.shutdown() # triggers room deletion because delete_room_on_close=True
# Or Option B: explicit async close
# await session.aclose() # also triggers deletion
Notes:
• Calling session.shutdown() or await session.aclose() will close the session and, with delete_room_on_close=True, will call the server delete_room API to remove the room and disconnect all participants.
• Use this when you want the agent to both clean up and terminate the room. If you need to perform extra cleanup (save egress, recordings, logs), do that before calling shutdown/aclose.brainy-pizza-19487
12/11/2025, 10:46 AMtall-airline-16756
12/11/2025, 10:46 AMdelete_room_on_close=True), the server forcibly disconnects all participants. Clients receive the Room disconnected event with reason ROOM_DELETED.
• If the agent only shuts down its session (e.g., session.shutdown() or agent leaves) but does not delete the room, clients see the agent as a participant leaving (participant_left or participant disconnect event) but the room remains active.
• Clients should listen on the Room object for disconnected to handle room deletion, and on participant events to detect individual participants leaving.
Example (JavaScript):
room.on('disconnected', (reason) => {
console.log('Room disconnected:', reason); // reason === 'ROOM_DELETED' for room deletion
// cleanup UI, navigate away, show message, etc.
});
room.on('participantDisconnected', (participant) => {
console.log('Participant left:', participant.identity);
});
Watch for platform-specific event names in your SDK (iOS/Android use equivalent Room disconnect and participant events). Would you like short examples for Android or iOS?
Sources: Connecting to LiveKit | LiveKit docs | Handling events | LiveKit docs | Job lifecycle | LiveKit docs