brainy-pizza-19487
12/06/2025, 10:33 AMtall-airline-16756
12/06/2025, 10:34 AMtall-airline-16756
12/06/2025, 10:34 AMbrainy-pizza-19487
12/06/2025, 10:36 AMtall-airline-16756
12/06/2025, 10:36 AMuv 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 docsbrainy-pizza-19487
12/06/2025, 10:37 AMtall-airline-16756
12/06/2025, 10:37 AMdrain_timeout on the AgentServer when you create it. Value is in seconds:
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 docsbrainy-pizza-19487
12/06/2025, 10:39 AMtall-airline-16756
12/06/2025, 10:39 AMdrain_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?brainy-pizza-19487
12/06/2025, 10:41 AMtall-airline-16756
12/06/2025, 10:41 AMdrain_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?brainy-pizza-19487
12/06/2025, 10:46 AMtall-airline-16756
12/06/2025, 10:46 AMawait 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?brainy-pizza-19487
12/06/2025, 10:48 AMtall-airline-16756
12/06/2025, 10:48 AMdrain_timeout from an environment variable
• using await session.aclose() in test teardown
• recommended local values
1) Agent server with env-based drain timeout
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
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?brainy-pizza-19487
12/06/2025, 10:51 AMtall-airline-16756
12/06/2025, 10:51 AMdrain_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.
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 docsbrainy-pizza-19487
12/06/2025, 10:53 AMtall-airline-16756
12/06/2025, 10:54 AMWorkerOptions 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
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 docsbrainy-pizza-19487
12/06/2025, 10:56 AMtall-airline-16756
12/06/2025, 10:57 AMawait session.shutdown(drain=True) for graceful draining and await session.aclose() for immediate close.
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)?brainy-pizza-19487
12/06/2025, 11:53 AMtall-airline-16756
12/06/2025, 11:54 AMbrainy-pizza-19487
12/06/2025, 12:12 PMtall-airline-16756
12/06/2025, 12:12 PMbrainy-pizza-19487
12/06/2025, 12:15 PMtall-airline-16756
12/06/2025, 12:16 PMnslookup 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.brainy-pizza-19487
12/06/2025, 12:29 PMtall-airline-16756
12/06/2025, 12:29 PMport 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 docsbrainy-pizza-19487
12/06/2025, 12:30 PMtall-airline-16756
12/06/2025, 12:31 PMport 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 docsbrainy-pizza-19487
12/06/2025, 1:45 PMtall-airline-16756
12/06/2025, 1:46 PMbrainy-pizza-19487
12/07/2025, 2:10 PM