b
hi
t
Thanks for reaching out, Yashpratap. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — how can I help you today? What are you trying to do with LiveKit (setup, SDKs, rooms, auth, quality issues, billing, or something else)? If you can share your platform (web/iOS/Android/other), room or project ID, and a brief description of the problem or goal, I’ll help you next.
b
While running a python agent worker in local setup, what is the correct way to shutdown the worker?
t
Regarding shutting down a Python agent worker in your local setup — send a SIGINT (Ctrl+C) or SIGTERM to the process. The Agents framework will enter a draining state: it stops accepting new jobs and allows active sessions to complete before exiting. Notes: • Default drain timeout is 30 minutes; the process will terminate after that even if sessions remain. • Example: if you started the agent with
uv run agent.py start
, press Ctrl+C in the terminal to initiate graceful shutdown. Would you like steps to change the drain timeout or to force immediate shutdown? Sources: Agent server options | LiveKit docs
b
How to change the drain timeout and force immediate shutdown?
t
You're asking how to change the drain timeout and how to force an immediate shutdown for a local Python agent worker — here’s how to do both. Change drain timeout 1. Set
drain_timeout
on the
AgentServer
when you create it. Value is in seconds:
Copy code
from livekit.agents import AgentServer

server = AgentServer(
    drain_timeout=10.0  # wait up to 10 seconds for active sessions on shutdown
)
Force near-immediate shutdown • Set a very short
drain_timeout
(for example,
0.1
) to make shutdown almost immediate. • In your agent logic, call
await session.aclose()
to close individual sessions right away. • For quick testing, press Ctrl+C twice in the terminal to force quit the process (bypasses graceful draining). If you want, I can show an example combining a short
drain_timeout
with session cleanup code. Would you like that? Sources: Agent server options | LiveKit docs | Job lifecycle | LiveKit docs
b
what's the significance of drain-timeout?
t
You're asking about the significance of
drain_timeout
for a Python agent worker — here’s a concise explanation. What it does •
drain_timeout
is the maximum time (in seconds) the agent waits after receiving SIGINT/SIGTERM for active sessions/jobs to finish before the process exits. • During that time the agent stops accepting new jobs (enters draining) but continues running existing sessions to allow graceful completion. Why it matters • Prevents abrupt interruption of in-progress work and avoids leaving sessions in an inconsistent state. • Balances user experience vs. shutdown speed: longer time favors graceful completion; shorter time favors quicker restart/termination. • Ensures cleanup routines and resource releases have time to run (saving state, closing connections). Practical guidance • Use a longer timeout in production so user sessions can finish cleanly. • Use a short timeout (or call
await session.aclose()
per session) for tests or rapid restarts. • If you truly need immediate termination, forcing a hard kill (e.g., double Ctrl+C) will bypass draining but may leave sessions abruptly closed. Would you like an example showing recommended timeout values for dev vs. production?
b
yes
t
Below are recommended
drain_timeout
values and why you'd pick each. This answers your request for dev vs production examples and the impact of each choice. Recommended values • Development / local testing: 0.1–5 seconds ◦ Fast restarts, minimal wait for sessions. Use short timeout or double Ctrl+C when you need immediate stop. • Staging / QA: 10–60 seconds ◦ Allows short user interactions or background tasks to finish without long waits. • Production: 300–1800 seconds (5–30 minutes) ◦ Gives ample time for longer sessions and cleanup (state saving, resource release). Reduces risk of abrupt interruption. Impact summary • Short timeout: faster restarts but higher risk of abruptly terminated sessions and incomplete cleanup. • Long timeout: graceful shutdown and safer cleanup, but longer downtime during deploys or restarts. • Complementary options: call
await session.aclose()
in your agent logic to actively close sessions immediately, or set minimal
drain_timeout
for near-immediate shutdown behavior. Would you like a small code snippet that sets different
drain_timeout
values based on an environment variable?
b
what's recommended for local testing, sessino.aclose() or a short drain-timeout?
t
For local testing, prefer using
await session.aclose()
in your agent logic when you want deterministic, immediate cleanup of specific sessions, and use a short
drain_timeout
as a safety net. Why •
session.aclose()
— predictable, graceful end for each session (closes resources, runs cleanup). Best for tests that need a clean state after each run. • Short
drain_timeout
— ensures the whole process won’t hang if a session doesn’t close; useful as a fallback during quick restarts. Recommended pattern for local testing 1. Actively close sessions in your test teardown with
await session.aclose()
. 2. Run the agent with a short
drain_timeout
(e.g., 0.1–5 seconds) so shutdown completes fast if something is left open. 3. For manual quick stops, double Ctrl+C to force immediate exit if needed. If you want, I can provide a tiny code snippet showing test teardown calling
session.aclose()
and setting
drain_timeout
from an environment variable. Would you like that?
b
yes
t
Below is a minimal example showing: • setting
drain_timeout
from an environment variable • using
await session.aclose()
in test teardown • recommended local values 1) Agent server with env-based drain timeout
Copy code
import os
from livekit.agents import AgentServer

# Read env var (seconds). Default to 1s for fast local testing.
drain_timeout = float(os.getenv("AGENT_DRAIN_TIMEOUT", "1.0"))

server = AgentServer(
    drain_timeout=drain_timeout
)

if __name__ == "__main__":
    server.run()  # or whatever start/run call your agent uses
2) Example test teardown that closes sessions deterministically
Copy code
import pytest
# assume `session` is provided by your test fixture or created during the test

@pytest.fixture
async def session_fixture():
    session = await create_test_session()  # your helper
    yield session
    # deterministic cleanup for local tests
    await session.aclose()
Recommended local settings • Use
await session.aclose()
in test teardown for deterministic cleanup. • Set
AGENT_DRAIN_TIMEOUT
to a small value (0.1–5 seconds). Default in example: 1.0s. • Keep the short drain timeout as a safety net in case a session fails to close. Would you like this adapted to your existing test framework or a fuller example showing session creation?
b
give me the drain-timeout snippet for AgentSession() api
t
You should set
drain_timeout
on
AgentServer
—
AgentSession
has no
drain_timeout
parameter. Below is a concise snippet showing how to configure
drain_timeout
(from env) and how to close a session inside your session handler.
Copy code
import os
from livekit.agents import cli, JobContext, AgentServer

# read drain timeout from env (seconds). default 1s for local testing
drain_timeout = float(os.getenv("AGENT_DRAIN_TIMEOUT", "1.0"))

server = AgentServer(
    drain_timeout=drain_timeout,
)

@server.rtc_session()
async def my_agent(ctx: JobContext):
    session = ctx.session  # your AgentSession
    try:
        # your session logic here
        ...
    finally:
        # deterministically close this session if you need immediate cleanup
        await session.aclose()

if __name__ == "__main__":
    cli.run_app(server)
Use
await session.aclose()
for deterministic session cleanup in tests and a short
drain_timeout
(e.g., 0.1–5s) as a safety net for local testing. Sources: Agent server options | LiveKit docs | Job lifecycle | LiveKit docs
b
I'm not using the AgentServer() . I'm using the workeroptions with entrypoint argument. cli.run_app( WorkerOptions( _entrypoint_fnc_=entrypoint, _prewarm_fnc_=prewarm, ) )
t
You're using
WorkerOptions
with an entrypoint — good to clarify. Here’s how shutdown and drain behavior work for that pattern and actionable snippets. Key points •
drain_timeout
is a server-level setting (framework applies a default 30 minutes). You don't set
drain_timeout
on
AgentSession
. • With
WorkerOptions
+ entrypoint you control shutdown by calling session methods or invoking the framework shutdown hooks from your entrypoint. • For graceful shutdown: call
await session.shutdown(drain=True)
(drains active work). For immediate close: call
await session.aclose()
. Example: WorkerOptions entrypoint with env-based drain-timeout fallback and explicit session shutdown
Copy code
import os
import asyncio
from livekit.agents import cli, JobContext, WorkerOptions, AgentSession

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        # configure llm/stt/tts/vad...
    )
    await session.start(room=ctx.room)

    try:
        # keep running until signaled
        await asyncio.Event().wait()
    finally:
        # graceful drain (waits for session-level drain behavior)
        await session.shutdown(drain=True)

if __name__ == "__main__":
    # For local testing, set a short process-level drain via env as a safety net.
    # The framework's default drain timeout applies; change your env or process manager if needed.
    worker_opts = WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=None,
    )
    cli.run_app(worker_opts)
Local-testing recommendations • Use
await session.aclose()
in test teardown for deterministic immediate cleanup. • Use
await session.shutdown(drain=True)
when you want graceful completion of in-flight work. • Keep a short process-level drain timeout during local dev (e.g., set AGENT_DRAIN_TIMEOUT env to 0.1–5s if your runner supports it) as a safety net; the framework applies the server-level timeout on signals. • For quick force-quit in development, press Ctrl+C twice to bypass graceful draining. If you want, tell me: • whether your runner honors an AGENT_DRAIN_TIMEOUT env var (I can show how to set it), or • I can adapt the snippet to include a programmatic shutdown trigger (signal handler or RPC) instead of
asyncio.Event().wait()
. Which would you prefer? Sources: Agent server options | LiveKit docs | Building a Moviefone-style Theater Assistant | LiveKit docs
b
include a programmatic shutdown trigger
t
Below is a minimal example that adds two programmatic shutdown triggers to your WorkerOptions-based entrypoint: • a UNIX signal handler (SIGINT/SIGTERM) that initiates graceful shutdown • an HTTP endpoint you can call to trigger immediate or graceful shutdown remotely It demonstrates using
await session.shutdown(drain=True)
for graceful draining and
await session.aclose()
for immediate close.
Copy code
import os
import asyncio
import signal
from aiohttp import web
from livekit.agents import cli, JobContext, WorkerOptions, AgentSession

SHUTDOWN_TIMEOUT = float(os.getenv("AGENT_DRAIN_TIMEOUT", "1.0"))  # safety net for local testing

async def start_admin_http(shutdown_queue: asyncio.Queue):
    async def handle_shutdown(request):
        mode = request.query.get("mode", "graceful")  # "graceful" or "immediate"
        await shutdown_queue.put(mode)
        return web.Response(text=f"shutdown queued: {mode}")

    app = web.Application()
    app.router.add_post("/shutdown", handle_shutdown)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "127.0.0.1", 8080)
    await site.start()
    return runner, site

async def entrypoint(ctx: JobContext):
    shutdown_queue = asyncio.Queue()

    # start admin HTTP trigger (optional)
    admin_runner, admin_site = await start_admin_http(shutdown_queue)

    # create and start session
    session = AgentSession(
        # configure llm/stt/tts/vad...
    )
    await session.start(room=ctx.room)

    # hook OS signals to enqueue a graceful shutdown
    loop = asyncio.get_running_loop()
    def _on_signal():
        # enqueue graceful shutdown on first signal
        try:
            shutdown_queue.put_nowait("graceful")
        except asyncio.QueueFull:
            pass
    loop.add_signal_handler(signal.SIGINT, _on_signal)
    loop.add_signal_handler(signal.SIGTERM, _on_signal)

    try:
        # wait for a shutdown command
        mode = await shutdown_queue.get()

        if mode == "immediate":
            # immediate close (no drain)
            await session.aclose()
        else:
            # graceful drain (waits for session-level drain behavior)
            await session.shutdown(drain=True)

            # optional: wait up to SHUTDOWN_TIMEOUT for remaining cleanup
            try:
                await asyncio.wait_for(session.wait_closed(), timeout=SHUTDOWN_TIMEOUT)
            except asyncio.TimeoutError:
                # force immediate close if still open
                await session.aclose()

    finally:
        # stop the admin HTTP server
        await admin_runner.cleanup()

if __name__ == "__main__":
    worker_opts = WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=None,
    )
    cli.run_app(worker_opts)
How to use • Graceful via signal: press Ctrl+C (SIGINT) — enqueues graceful shutdown. • Graceful via HTTP: POST http://127.0.0.1:8080/shutdown (defaults to graceful). • Immediate via HTTP: POST http://127.0.0.1:8080/shutdown?mode=immediate Notes •
AgentSession
has no
drain_timeout
parameter;
drain_timeout
is a process-level safety value. Use a short
AGENT_DRAIN_TIMEOUT
for local testing. •
await session.shutdown(drain=True)
lets in-flight work finish;
await session.aclose()
closes immediately. • Adjust ports, timeouts, and auth on the admin endpoint as needed for your environment. Would you like this adapted to use a different trigger (e.g., gRPC, Redis pub/sub, or a CLI command)?
b
what is the default port on which livekit cli agent starts on?
t
The agent worker itself does not open a required inbound port — it connects outbound to the LiveKit server. Optional defaults: • Agent health-check server (optional): 0.0.0.0:8081 • LiveKit server (what agents connect to): default API/WebSocket port 7880 Use your runner/config to change the agent health port if needed. Sources: Deploying to custom environments | LiveKit docs | Ports and firewall | LiveKit docs | Examples | livekit/livekit_composite | DeepWiki
b
when running the agent-worker in a docker env behind a corporate firewall, do I need to define the dns settings as google DNS in the docker file of livekit-agent worker?
t
Short answer: No — you don't have to hardcode Google DNS in the Dockerfile. Use whatever DNS your environment requires; only change DNS if name resolution fails or corporate policy requires a specific resolver. What to consider and recommended approaches • Default behavior: containers inherit the host's resolver (or Docker daemon config). In many corporate networks that works fine if the host can resolve LiveKit/server endpoints. • When to change DNS: if container name resolution fails (cannot resolve LiveKit server, package registries, or other external services), then configure DNS to a resolver that can reach those names. • Prefer corporate DNS first: if your company has internal resolvers or split-horizon DNS (internal hostnames), point containers to the corporate DNS so internal names resolve correctly. Using Google DNS (8.8.8.8) can bypass internal records and break access to internal services. How to set DNS (options) • Docker run flag (runtime, no Dockerfile change): docker run --dns 10.0.0.10 ... # corporate DNS • Docker Compose: services: agent: image: my-livekit-agent dns: • 10.0.0.10 • Docker daemon level (all containers): Edit /etc/docker/daemon.json: { "dns": ["10.0.0.10","8.8.8.8"] } Then restart Docker daemon. • Avoid hardcoding in Dockerfile — Dockerfile RUN steps may use DNS at build time; if build needs special DNS, set build args or use docker build --network and daemon DNS settings instead. Firewall considerations • Ensure outbound connectivity from the container to the LiveKit server URL/port (typically websocket/API on port 7880 or 443) is allowed. • Allow DNS (UDP/TCP 53) to the configured resolver. • If your environment forces egress via a proxy, point the agent to the proxy (HTTP_PROXY/HTTPS_PROXY) rather than changing DNS. Quick checklist to diagnose/resolution 1. From host: can you resolve and reach the LiveKit server? (ping/dig/curl) 2. From a test container (alpine/busybox): try dig/nslookup/curl to verify DNS and connectivity. 3. If resolution fails, configure container DNS to your corporate resolver (or add fallback like 8.8.8.8) at runtime or daemon level. 4. Verify firewall allows outbound DNS and target ports (7880/443). If you tell me: • whether your agent needs to reach internal-only hostnames, or • a sample of the DNS failures you see from inside a container, I can give the exact docker/docker-compose/daemon configuration commands you'd use.
b
how to test the resolution of livekit server from the container?
t
You can verify DNS resolution and connectivity to your LiveKit server from inside a container with a few quick checks. Run a temporary container (alpine or busybox) and use these commands. 1) Start a test container (no image changes required) • Alpine: docker run --rm -it --network host alpine sh • Busybox: docker run --rm -it busybox sh 2) Quick DNS resolution checks inside the container • ping the hostname: ping -c 3 your.livekit.host • use nslookup (busybox may include
nslookup
via
bind-tools
on alpine): nslookup your.livekit.host • use dig (if not present, install in alpine:
apk add --no-cache drill
then
drill your.livekit.host
) 3) Test HTTP/WebSocket connectivity • curl (HTTP): curl -v https://your.livekit.host:443/ • curl to the API or health endpoint: curl -v https://your.livekit.host:7880/ # if your server uses 7880 • WebSocket check (if
wscat
available on host): try connecting to
wss://your.livekit.host:7880
from a container that has
wscat
installed, or use a simple Python websocket client. 4) If commands are missing, run an image with tools: docker run --rm -it --network host nicolaka/netshoot sh This image includes dig/nslookup/curl/tcping and many troubleshooting tools. 5) Troubleshooting steps if resolution fails • From host: run
dig your.livekit.host
/
nslookup
to compare results with container. • If host resolves but container doesn't, check Docker DNS settings: ◦ Try passing
--dns 10.0.0.10
(your corporate resolver) to docker run. ◦ Or set DNS in docker-compose
dns:
or daemon
/etc/docker/daemon.json
. • Ensure outbound DNS (UDP/TCP 53) and target ports (7880 or 443) are allowed through the firewall. • If corporate proxy is required, set `HTTP_PROXY`/`HTTPS_PROXY` in the container environment. If you share the hostname you’re testing and the failing command output, I can help interpret the results and suggest exact DNS or firewall changes.
b
So, in the WorkerOptions() port argument, which port does it configure?
t
You're asking which network port
port
on
WorkerOptions()
configures. There is no documented
port
parameter on
WorkerOptions()
in the SDK. WorkerOptions controls entrypoint/prewarm and worker metadata, but it does not configure an agent listener port. Relevant ports to consider instead: • Agent workers don't need an inbound port; they connect outbound to the LiveKit server (default server API/WebSocket port: 7880). • Optional agent health-check server defaults to 0.0.0.0:8081 (if your setup exposes one). • If you need an admin/HTTP endpoint (like the example we used), you must bind and manage that port yourself inside your entrypoint. If you can paste the
WorkerOptions(...)
code you have (or the exact SDK version), I can confirm whether that
port
field is from an older/extended API or suggest the correct place to configure any HTTP/admin port. Sources: Agent server options | LiveKit docs | Deploying to custom environments | LiveKit docs
b
https://docs.livekit.io/reference/agents-js/classes/agents.WorkerOptions.html#port As you can see, there is a "port" argument here as well
t
You're asking what the
port
field on
WorkerOptions()
configures. In the JS
@livekit/agents
API,
WorkerOptions.port
sets the signaling/WebSocket port the agent uses to connect to the LiveKit server (the server API/WebSocket port), not a media or peer port. In most default setups this is 7880. It does not configure WebRTC media ports (UDP range, TURN ports) or any automatic admin/health HTTP port inside your agent — those you must bind yourself in your entrypoint if needed. Sources: Deploying LiveKit | LiveKit docs | Ports and firewall | LiveKit docs | Deploy to a VM | LiveKit docs | Agent server options | LiveKit docs | Job lifecycle | LiveKit docs
b
{"level": "ERROR", "name": "livekit.agents", "message": "worker failed", "exc_info": "Traceback (most recent call last):\n File \"/usr/local/lib/python3.13/site-packages/livekit/agents/cli/cli.py\", line 1342, in _worker_run\n await server.run(devmode=args.devmode, unregistered=jupyter)\n File \"/usr/local/lib/python3.13/site-packages/livekit/agents/worker.py\", line 666, in run\n await self._http_server.start()\n File \"/usr/local/lib/python3.13/site-packages/livekit/agents/utils/http_server.py\", line 31, in start\n self._server = await self._loop.create_server(handler, self._host, self._port)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.13/asyncio/base_events.py\", line 1630, in create_server\n raise OSError(err.errno, msg) from None\nOSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 8081): [errno 98] address already in use", "timestamp": "2025-12-06T133857.655955+00:00"} Since you said 8081 for health check port is optional, then why I'm getting this error while starting the docker container
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
b
how to add latency logging for each step- STT, TTS, LLM