i want to shutdown my voice agent session in the c...
# ask-ai
f
i want to shutdown my voice agent session in the code after 10 seconds of silence, currently i am testing using python main.py console but the session doesn't end on its own.
t
Thanks for reaching out, Viren. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to end your voice agent session automatically after 10 seconds of silence while running
python 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):
Copy code
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 docs
f
how to close livekit terminal and worker ?
t
Do you mean the local LiveKit server terminal, the agent worker process you run during development, or agents deployed in LiveKit Cloud? Which of these are you trying to close? Sources: Job lifecycle | LiveKit docs | Agent server options | LiveKit docs | Running LiveKit locally | LiveKit docs | Agent server | LiveKit docs | Deploying to production | LiveKit Docs
f
I want to close both: Do you mean the local LiveKit server terminal, the agent worker process you run during development
t
You're asking how to close both the local LiveKit server terminal and the local agent worker process used during development. Below are concise, safe ways to stop each and ensure graceful shutdown. Local LiveKit server terminal • If running in a terminal (e.g.,
livekit-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?
f
i want to run it programatically not manually
t
You're asking how to programmatically stop both the local agent worker and the LiveKit server during development. Here are concise options you can use depending on how you run them. Agent worker (programmatic, recommended) • Call
await ctx.shutdown("reason")
from your entrypoint or from a monitoring coroutine to gracefully stop the worker. • Example pattern (Python):
Copy code
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:
Copy code
proc = subprocess.Popen(["livekit-server", "--dev"])
# later...
proc.terminate()   # sends SIGTERM (graceful)
proc.wait()
• For Docker:
Copy code
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:
Copy code
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 docs
f
want to close the terminal on its own after call is disconnected.
t
You're looking to automatically close the terminal when a call disconnects. Do this by detecting the room/call end, gracefully shutting down the agent, then exiting the process (which closes the terminal when run in foreground). Below are concise, runnable patterns — pick the one matching your setup. Python (agent process + close terminal)
Copy code
import 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)
Copy code
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)
Copy code
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 docs
f
i keep getting the logs: 2025-11-30 175608,259 - DEBUG livekit.agents - http_session(): closing the httpclient ctx
t
You're seeing the debug line because the agents framework is closing an internal HTTP client context during shutdown/cleanup. That message is informational — it means the agent code is tearing down HTTP resources (expected when you call
session.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:
Copy code
import logging
logging.getLogger("livekit.agents").setLevel(logging.INFO)
Or configure basic logging at startup:
Copy code
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.
f
terminal doesnt kill
t
Thanks — let’s fix the terminal not exiting. The terminal stays open because the process isn’t actually exiting even after shutdown. Do these three things: 1) Ensure you shut down once (guard) • Add a boolean guard so shutdown runs only once (prevents repeated calls keeping tasks alive).
Copy code
_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.
Copy code
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.
Copy code
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.
f
yes i would like the following: Would you like a combined example that starts the server subprocess, runs the agent, monitors the call, and then shuts both down automatically?
t
Below is a concise, complete Python example that: • Starts a local LiveKit server subprocess, • Runs an agent entrypoint that starts a session, • Monitors for call end (last participant leaves OR 10s silence), • Gracefully shuts down the agent and the server subprocess, • Exits the process to close the terminal. Save as run_agent_with_server.py and adapt the placeholders (agent config, server binary path, room name).
Copy code
import 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)?
f
my agent doesnt shutdown instead i keep getting logs: DEBUG livekit.agents - http_session(): closing the httpclient ctx
t
Thanks — let's pinpoint why your agent doesn't exit. The repeated "DEBUG livekit.agents - http_session(): closing the httpclient ctx" log shows the agent is running shutdown/cleanup code, but the process is still alive. That usually means one of these is still running: background tasks, un-cancelled listeners, the server subprocess, or repeated shutdown calls without an exit. Do the following minimal changes in your entrypoint to guarantee exit and remove noisy debug logs. If you paste your current entrypoint I will adapt this precisely. 1) Add a single-run shutdown guard, cancel tasks, and then exit
Copy code
import 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)
Copy code
# 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
Copy code
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)
Copy code
# 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
Copy code
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.