aloof-scooter-47164
09/05/2025, 4:03 AMtall-airline-16756
09/05/2025, 4:03 AMtall-airline-16756
09/05/2025, 4:04 AMAgentSession class with the user_away_timeout option. This will automatically spot when a user is inactive and mark them as "away" after the timeout you set (the default is 15 seconds).
2. Handle State Changes: Keep an eye on the user_state_changed event. When a user goes "away," you can start a timer, and if they come back, just cancel that timer—easy!
3. Disconnect Everyone: When the timer finishes without any user activity, call the LiveKit Server API's delete_room() method to close the room and disconnect all participants.
Here’s a simple example to get you started:
import asyncio
from livekit.agents import AgentSession, JobContext, UserStateChangedEvent, cli
async def entrypoint(ctx: JobContext):
session = AgentSession(user_away_timeout=12.5) # Set custom timeout
inactivity_task = None
async def user_presence_task():
await asyncio.sleep(10) # Wait before disconnecting
await ctx.api_client.room.delete_room(room=ctx.job.room.name)
@session.on("user_state_changed")
def on_user_state_changed(ev: UserStateChangedEvent):
nonlocal inactivity_task
if ev.new_state == "away":
inactivity_task = asyncio.create_task(user_presence_task())
elif inactivity_task:
inactivity_task.cancel()
await session.start(agent=None, room=ctx.room)
if __name__ == "__main__":
cli.run_app(entrypoint)
This example sets up a timer to delete the room if the user stays inactive, but if they come back, the timer gets canceled—pretty handy!
If you want me to help tweak this for your specific needs or have any questions, just let me know. I'm here to help!
Sources: Inside a session | LiveKit Docs | Job lifecycle | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | Example Applications | livekit/livekit_composite | DeepWiki | Inside a session | LiveKit Docsaloof-scooter-47164
09/05/2025, 4:13 AMtall-airline-16756
09/05/2025, 4:13 AMinactivity_task.cancel() does the trick, like in the example. This is pretty standard for non-critical background tasks, such as keeping an eye on user presence.
That said, if your task is handling something more critical, like cleanup, or if your code really depends on the task being completely finished, then you’d want to use await utils.aio.cancel_and_wait(task) to make sure everything wraps up properly. But for the example you’re working with, you’re good without waiting.
Feel free to ask if anything’s still unclear—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Voice Assistants | livekit/livekit_composite | DeepWiki | Example Applications | livekit/livekit_composite | DeepWiki | agents/src/voice/agent_activity.ts