fast-hairdresser-13908
11/30/2025, 11:08 AMtall-airline-16756
11/30/2025, 11:08 AMtall-airline-16756
11/30/2025, 11:08 AMpython main.py console. You can do this by detecting when the user stops speaking, tracking the timestamp, and shutting down the session from a background task when silence exceeds 10 seconds.
Try this pattern in your agent entrypoint (concise example):
import asyncio
import time
from livekit.agents import JobContext, AgentSession
async def entrypoint(ctx: JobContext):
session = AgentSession(...) # your config
await session.start(room=ctx.room, agent=your_agent)
last_spoke = time.time()
SILENCE_THRESHOLD = 10
@session.on("user_state_changed")
def on_user_state_changed(state):
nonlocal last_spoke
if state.new_state == "speaking":
last_spoke = time.time()
async def monitor_silence():
while True:
if time.time() - last_spoke > SILENCE_THRESHOLD:
print("10s silence detected — shutting down session")
await session.shutdown(drain=False)
return
await asyncio.sleep(1)
monitor = asyncio.create_task(monitor_silence())
def _cleanup():
if not monitor.done():
monitor.cancel()
ctx.add_shutdown_callback(_cleanup)
await asyncio.Future() # keep running until shutdown
Notes:
• Use the user_state_changed event to update last_spoke.
• The monitor task checks silence every second and calls session.shutdown(drain=False) when threshold is reached.
• ctx.add_shutdown_callback ensures the monitor is cleaned up on shutdown.
Would you like a version adjusted for your exact session/agent setup (show your AgentSession config or relevant snippet)?
Sources: Turn detection and interruptions | LiveKit Docs | How to detect and handle silence during calls | Job lifecycle | LiveKit docsfast-hairdresser-13908
11/30/2025, 11:54 AMtall-airline-16756
11/30/2025, 11:54 AMfast-hairdresser-13908
11/30/2025, 11:55 AMtall-airline-16756
11/30/2025, 11:55 AMlivekit-server --dev), press Ctrl+C. This sends SIGINT and triggers graceful shutdown.
• If you started it as a background process, run kill <pid> to send SIGTERM (preferred) or kill -9 <pid> to force-stop (interrupts active sessions).
Local agent worker process (development)
• If running via the CLI/dev command (e.g., uv run agent.py dev, pnpm run agent.ts dev, or python main.py console), press Ctrl+C in that terminal. The agent framework will enter draining mode and allow active jobs to finish before exiting.
• Programmatic: call await ctx.shutdown() (Python) or ctx.shutdown(reason) (Node) inside your entrypoint to stop the worker from code when you want to end it.
• If you used a background process, send SIGTERM with kill <pid> to allow a graceful drain; use kill -9 <pid> only if necessary.
Tips
• Prefer SIGTERM/Ctrl+C to allow draining; use SIGKILL only as last resort.
• If you want automatic shutdown after inactivity, implement a silence monitor in your agent that calls session.shutdown() or ctx.shutdown() when appropriate.
Would you like the exact command examples for your setup (macOS/Linux vs Windows) or the code snippet to call ctx.shutdown() from your entrypoint?fast-hairdresser-13908
11/30/2025, 11:56 AMtall-airline-16756
11/30/2025, 11:56 AMawait ctx.shutdown("reason") from your entrypoint or from a monitoring coroutine to gracefully stop the worker.
• Example pattern (Python):
async def entrypoint(ctx: JobContext):
# ... start session, etc.
# when you decide to stop:
await ctx.shutdown("stopping after inactivity")
• Or shut down an individual AgentSession with await session.shutdown(drain=False) to end that session immediately.
LiveKit server (self-hosted)
• There is no in-process API to tell the livekit-server binary to exit; use external process control:
◦ If you started the server as a subprocess in Python, terminate it programmatically:
proc = subprocess.Popen(["livekit-server", "--dev"])
# later...
proc.terminate() # sends SIGTERM (graceful)
proc.wait()
• For Docker:
docker stop <container>
• For systemd/K8s, use the appropriate service/container stop command.
Alternative: close rooms instead of server
• To disconnect participants without killing the server, delete rooms via the server API:
from livekit.api import LiveKitAPI, DeleteRoomRequest
await api_client.room.delete_room(DeleteRoomRequest(room="my-room"))
Automation tips
• Run the server as a subprocess in your test/dev script so your script can start/stop it.
• Use a background monitor (silence/inactivity timer or test lifecycle) to call ctx.shutdown() for workers and proc.terminate() for the server.
• Prefer SIGTERM/`terminate()` or Ctrl+C equivalents to allow draining; use force-kill only if necessary.
Do you want a ready-to-run example that starts the server subprocess, runs the agent, watches for 10s silence, then shuts both down?
Sources: Job lifecycle | LiveKit docs | Observability data hooks | LiveKit docs | Distributed Setup | LiveKit docsfast-hairdresser-13908
11/30/2025, 12:21 PMtall-airline-16756
11/30/2025, 12:22 PMimport asyncio
import os
from livekit import agents
async def entrypoint(ctx: agents.JobContext):
session = agents.voice.AgentSession(...) # your config
await session.start(room=ctx.room)
async def shutdown_and_exit():
print("Call ended — shutting down agent...")
await session.shutdown() # graceful cleanup
await asyncio.sleep(0.5) # allow logs to flush
os._exit(0) # close terminal
# Trigger when room disconnects or last participant leaves
ctx.room.once("disconnected", lambda: asyncio.create_task(shutdown_and_exit()))
ctx.room.on("participant_disconnected", lambda p: (
asyncio.create_task(shutdown_and_exit())
if len(ctx.room.remote_participants) == 0 else None
))
await asyncio.Future() # keep worker alive until exit
Node.js (same idea)
import process from "process";
export default defineAgent({
entry: async (ctx) => {
const session = new voice.AgentSession(...);
await session.start({ room: ctx.room });
const shutdownAndExit = async () => {
console.log("Call ended — shutting down agent...");
await ctx.shutdown();
setTimeout(() => process.exit(0), 500);
};
ctx.room.once("disconnected", shutdownAndExit);
ctx.room.on("participantDisconnected", () => {
if (ctx.room.remoteParticipants.size === 0) shutdownAndExit();
});
await new Promise(() => {}); // keep process alive
},
});
If you also run the LiveKit server as a subprocess and want to stop it too, start it from your script and terminate it when shutting down:
Python subprocess example (start + stop server)
import subprocess
proc = subprocess.Popen(["livekit-server", "--dev"])
# ... later after call ends:
proc.terminate() # sends SIGTERM for graceful stop
proc.wait()
Key points
• Use room events (disconnected or detect last participant) to know when the call ended.
• Call session.shutdown() or ctx.shutdown() first to clean up.
• Use os._exit(0) / process.exit(0) to close the terminal when running in foreground.
• If you want the server stopped too, launch it as a subprocess and call proc.terminate().
Would you like a combined example that starts the server subprocess, runs the agent, monitors the call, and then shuts both down automatically?
Sources: Job lifecycle | LiveKit docs | Connecting to LiveKit | LiveKit docsfast-hairdresser-13908
11/30/2025, 12:27 PMtall-airline-16756
11/30/2025, 12:27 PMsession.shutdown() / ctx.shutdown() or when the worker exits).
What it means
• The runtime is closing an HTTP client used by the agent (normal cleanup).
• It appears when logging level includes DEBUG for the livekit.agents logger.
If you want to stop or reduce these messages
• Lower the logger level for livekit.agents to INFO or WARNING.
Python example to change logging level:
import logging
logging.getLogger("livekit.agents").setLevel(logging.INFO)
Or configure basic logging at startup:
import logging
logging.basicConfig(level=logging.INFO)
If you still see unexpected repeated shutdown logs (not just a single cleanup message), check:
• You are not calling session.shutdown() / ctx.shutdown() repeatedly.
• Your shutdown task isn't being retriggered by multiple events (wrap with a guard flag).
• Background monitor tasks are cancelled properly when shutting down.
If you'd like, paste the small section of your entrypoint that handles shutdown and I’ll point out where to add a guard or adjust logging so the message appears only once.fast-hairdresser-13908
11/30/2025, 12:28 PMtall-airline-16756
11/30/2025, 12:28 PM_shutdown_started = False
async def shutdown_and_exit():
nonlocal _shutdown_started
if _shutdown_started:
return
_shutdown_started = True
await session.shutdown()
await asyncio.sleep(0.3)
os._exit(0)
2) Cancel background tasks and avoid blocking awaits
• Cancel any monitor tasks (silence monitor, timers) before exiting so they don’t keep the event loop alive.
if monitor_task and not monitor_task.done():
monitor_task.cancel()
try:
await monitor_task
except asyncio.CancelledError:
pass
3) Trigger exit after detecting call end
• Use room events (last participant left or disconnected) to call your guarded shutdown function.
ctx.room.once("disconnected", lambda: asyncio.create_task(shutdown_and_exit()))
ctx.room.on("participant_disconnected", lambda p: (
asyncio.create_task(shutdown_and_exit())
if len(ctx.room.remote_participants) == 0 else None
))
Extra troubleshooting if it still doesn’t close
• Lower logging to INFO to avoid noisy shutdown logs: logging.getLogger("livekit.agents").setLevel(logging.INFO)
• If you started the server as a subprocess, ensure you terminate that subprocess (proc.terminate(); proc.wait()) before exiting.
• Run your script directly in a terminal (foreground). If launched by a supervisor that restarts processes, the terminal will reopen.
If you paste your entrypoint (the shutdown + monitor parts), I’ll point out exactly where to add the guard/cancellation so the terminal actually exits.fast-hairdresser-13908
11/30/2025, 12:28 PMtall-airline-16756
11/30/2025, 12:29 PMimport asyncio
import subprocess
import time
import os
import logging
from livekit import agents
from livekit.agents import JobContext, AgentSession
logging.basicConfig(level=logging.INFO)
logging.getLogger("livekit.agents").setLevel(logging.INFO) # reduce noisy debug
LIVEKIT_SERVER_CMD = ["livekit-server", "--dev"] # adjust if needed
SILENCE_THRESHOLD = 10 # seconds of silence to trigger shutdown
SERVER_START_WAIT = 2 # seconds to wait after starting server
# -------------------------
# Start/stop server helpers
# -------------------------
def start_server():
proc = subprocess.Popen(LIVEKIT_SERVER_CMD, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
logging.info("Started livekit-server (pid=%s)", proc.pid)
time.sleep(SERVER_START_WAIT)
return proc
def stop_server(proc: subprocess.Popen):
if proc and proc.poll() is None:
logging.info("Stopping livekit-server (pid=%s)...", proc.pid)
proc.terminate() # SIGTERM
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
logging.warning("Server did not exit, killing...")
proc.kill()
proc.wait()
else:
logging.info("Server already stopped.")
# -------------------------
# Agent entrypoint
# -------------------------
async def entrypoint(ctx: JobContext):
# Replace with your actual AgentSession setup (STT/LLM/TTS config etc.)
session = AgentSession(...) # <-- fill in your agent configuration
await session.start(room=ctx.room)
logging.info("Agent session started for room=%s", ctx.room.name)
last_spoke = time.time()
monitor_task = None
shutdown_started = False
# Guarded shutdown routine: runs once
async def shutdown_and_exit():
nonlocal shutdown_started
if shutdown_started:
return
shutdown_started = True
logging.info("Shutting down agent session...")
# Cancel monitor task first
if monitor_task and not monitor_task.done():
monitor_task.cancel()
try:
await monitor_task
except asyncio.CancelledError:
pass
# Gracefully shutdown session/ctx
try:
await session.shutdown()
except Exception as e:
logging.warning("session.shutdown() raised: %s", e)
await asyncio.sleep(0.3) # allow logs to flush
# Signal to main process that we want to exit (actual exit handled by runner)
os._exit(0)
# Update last_spoke when user speaks
@session.on("user_state_changed")
def on_user_state_changed(state):
nonlocal last_spoke
if getattr(state, "new_state", None) == "speaking":
last_spoke = time.time()
# If the room emits disconnected, shut down
ctx.room.once("disconnected", lambda: asyncio.create_task(shutdown_and_exit()))
# If last participant leaves, trigger shutdown
def on_participant_disconnected(participant):
if len(ctx.room.remote_participants) == 0:
asyncio.create_task(shutdown_and_exit())
ctx.room.on("participant_disconnected", on_participant_disconnected)
# Background silence monitor
async def monitor_silence():
while True:
try:
if time.time() - last_spoke > SILENCE_THRESHOLD:
logging.info("Silence threshold reached. Initiating shutdown.")
await shutdown_and_exit()
return
await asyncio.sleep(1)
except asyncio.CancelledError:
return
monitor_task = asyncio.create_task(monitor_silence())
# Keep entrypoint alive until shutdown triggers exit
try:
await asyncio.Future()
except asyncio.CancelledError:
pass
# -------------------------
# Runner: start server, run worker
# -------------------------
async def main():
server_proc = start_server()
# Create WorkerFactory to run our entrypoint locally (development style)
workers = agents.WorkerFactory(entrypoint_fnc=entrypoint)
# Hook to stop server when workers shutdown callback runs
async def on_workers_shutdown():
logging.info("Workers shutdown callback triggered; stopping server subprocess.")
stop_server(server_proc)
# small delay then exit
await asyncio.sleep(0.1)
os._exit(0)
workers.on_shutdown(lambda: asyncio.create_task(on_workers_shutdown()))
# Run the agent worker loop (this call blocks until worker stops)
try:
agents.cli.run_app(workers)
finally:
# Ensure server stopped on unexpected exit
stop_server(server_proc)
if __name__ == "__main__":
asyncio.run(main())
Notes and adjustments:
• Replace AgentSession(...) with your real session/agent config.
• If you start the LiveKit server differently (Docker, systemd), adapt start/stop to `docker run`/`docker stop` or service commands.
• Using os._exit(0) ensures the process exits and the terminal closes when run in foreground. The guard shutdown_started prevents multiple shutdown attempts.
• The runner uses agents.WorkerFactory + agents.cli.run_app(workers) for local development. If you start workers differently, adapt the runner accordingly.
• Keep logging level at INFO to avoid noisy DEBUG messages during shutdown.
Want me to adapt this to your actual entrypoint code (paste your AgentSession config and how you currently start the worker)?fast-hairdresser-13908
11/30/2025, 12:57 PMtall-airline-16756
11/30/2025, 12:57 PMimport asyncio, os, logging
shutdown_started = False
async def shutdown_and_exit(session, monitor_task=None):
global shutdown_started
if shutdown_started:
return
shutdown_started = True
# stop monitor task
if monitor_task and not monitor_task.done():
monitor_task.cancel()
try:
await monitor_task
except asyncio.CancelledError:
pass
# graceful session shutdown
try:
await session.shutdown()
except Exception:
logging.exception("session.shutdown() error")
# give time to flush logs, then force exit to close terminal
await asyncio.sleep(0.2)
os._exit(0)
2) Ensure event handlers trigger the guarded shutdown (last participant OR room disconnected OR silence)
# example hooks inside entrypoint
ctx.room.once("disconnected", lambda: asyncio.create_task(shutdown_and_exit(session, monitor_task)))
ctx.room.on("participant_disconnected", lambda p: (
asyncio.create_task(shutdown_and_exit(session, monitor_task))
if len(ctx.room.remote_participants) == 0 else None
))
3) Make your silence monitor cancelable and call the guarded shutdown
async def monitor_silence():
try:
while True:
if time.time() - last_spoke > SILENCE_THRESHOLD:
await shutdown_and_exit(session, monitor_task)
return
await asyncio.sleep(1)
except asyncio.CancelledError:
return
monitor_task = asyncio.create_task(monitor_silence())
4) If you start a server subprocess, terminate it before exiting (or start it from a wrapper)
# keep proc object accessible; call this before os._exit()
def stop_server(proc):
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
5) Reduce noisy debug logs
import logging
logging.getLogger("livekit.agents").setLevel(logging.INFO)
Checklist to verify
• Only one shutdown path runs (guard prevents duplicates).
• All background tasks are cancelled before exit.
• Any server subprocess is terminated.
• No other supervisors (systemd, PM2, etc.) are immediately restarting the process.
If you share:
• your entrypoint code (shutdown + monitor parts),
• how you start the server (subprocess/docker/other),
I will modify your exact script to ensure the terminal closes automatically.