after moving to AgentServer from Agents.Workers it...
# ask-ai
a
after moving to AgentServer from Agents.Workers it has started to crash the server on redeploying
t
Thanks for reaching out, Aditya. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I’m sorry that redeploys started crashing after moving from Agents.Workers to AgentServer — I can help get this sorted. To diagnose quickly, please share the following and I’ll point to concrete fixes: 1. Exact error message or stack trace you see when the server crashes. 2. The agent entrypoint and server initialization code (the function decorated with
@server.rtc_session()
or
defineAgent
and how you call
agents.cli.run_app(server)
/
cli.runApp(server)
). 3. Are you running locally or in production / a container orchestration platform? 4. LiveKit Agents SDK version you’re using. 5. Any recent changes to shutdown/exception handling or process lifecycle code. While you gather that, check these common causes: • Ensure the entrypoint is correctly registered for AgentServer (mismatch with Worker patterns causes failures). • Confirm you start the server via the CLI helper (
agents.cli.run_app(server)
in Python or
cli.runApp(server)
in Node). • Inspect logs during redeploy with
lk agent logs
to capture startup/shutdown errors. • Look for uncaught exceptions in job processes or improper shutdown handling that can destabilize the server. Send the error/entrypoint code and environment details and I’ll give targeted steps to fix it. Sources: Job lifecycle | LiveKit docs | Agent server options | LiveKit docs | Deploying to custom environments | LiveKit Docs | Agent deployment CLI reference | LiveKit docs | Voice AI quickstart | LiveKit docs
a
# NOTE: this object must be pickle-able @dataclass class ServerOptions: entrypoint_fnc: Callable[[JobContext], Awaitable[None]] """Entrypoint function that will be called when a job is assigned to this worker.""" request_fnc: Callable[[JobRequest], Awaitable[None]] = _default_request_fnc """Inspect the request and decide if the current worker should handle it. When left empty, all jobs are accepted.""" prewarm_fnc: Callable[[JobProcess], Any] = _default_setup_fnc """A function to perform any necessary initialization before the job starts.""" load_fnc: Callable[[AgentServer], float] | Callable[[], float] = _DefaultLoadCalc.get_load """Called to determine the current load of the worker. Should return a value between 0 and 1.""" job_executor_type: JobExecutorType = _default_job_executor_type """Which executor to use to run jobs. (currently thread or process are supported)""" load_threshold: float | ServerEnvOption[float] = _default_load_threshold """When the load exceeds this threshold, the worker will be marked as unavailable. Defaults to 0.7 on "production" mode, and is disabled in "development" mode. """ job_memory_warn_mb: float = 500 """Memory warning threshold in MB. If the job process exceeds this limit, a warning will be logged.""" # noqa: E501 job_memory_limit_mb: float = 0 """Maximum memory usage for a job in MB, the job process will be killed if it exceeds this limit. Defaults to 0 (disabled). """ # noqa: E501 drain_timeout: int = 1800 """Number of seconds to wait for current jobs to finish upon receiving TERM or INT signal.""" num_idle_processes: int | ServerEnvOption[int] = ServerEnvOption( dev_default=0, prod_default=min(math.ceil(get_cpu_monitor().cpu_count()), 4) ) """Number of idle processes to keep warm.""" shutdown_process_timeout: float = 10.0 """Maximum amount of time to wait for a job to shut down gracefully""" initialize_process_timeout: float = 10.0 """Maximum amount of time to wait for a process to initialize/prewarm""" permissions: WorkerPermissions = field(default_factory=WorkerPermissions) """Permissions that the agent should join the room with.""" agent_name: str = "" """Set agent_name to enable explicit dispatch. When explicit dispatch is enabled, jobs will not be dispatched to rooms automatically. Instead, you can either specify the agent(s) to be dispatched in the end-user's token, or use the AgentDispatch.createDispatch API""" # noqa: E501 worker_type: WorkerType = WorkerType.ROOM """Whether to spin up an agent for each room or publisher.""" max_retry: int = 16 """Maximum number of times to retry connecting to LiveKit.""" ws_url: str = "ws://localhost:7880" """URL to connect to the LiveKit server. By default it uses ``LIVEKIT_URL`` from environment""" api_key: str | None = None """API key to authenticate with LiveKit. By default it uses ``LIVEKIT_API_KEY`` from environment""" api_secret: str | None = None """API secret to authenticate with LiveKit. By default it uses ``LIVEKIT_API_SECRET`` from environment""" host: str = "" # default to all interfaces port: int | ServerEnvOption[int] = ServerEnvOption(dev_default=0, prod_default=8081) """Port for local HTTP server to listen on. The HTTP server is used as a health check endpoint. """ http_proxy: NotGivenOr[str | None] = NOT_GIVEN """HTTP proxy used to connect to the LiveKit server. By default it uses ``HTTP_PROXY`` or ``HTTPS_PROXY`` from environment """ multiprocessing_context: Literal["spawn", "forkserver"] = ( "spawn" if not sys.platform.startswith("linux") else "forkserver" ) """The multiprocessing context to use. By default it uses "spawn" on all platforms, but "forkserver" on Linux. """ prometheus_port: NotGivenOr[int] = NOT_GIVEN """When enabled, will expose prometheus metrics on :{prometheus_port}/metrics""" prometheus_multiproc_dir: str | None = None """Directory for prometheus multiprocess mode to enable metrics collection from child job processes. When set, the PROMETHEUS_MULTIPROC_DIR environment variable will be configured automatically. When None (default), multiprocess mode is disabled and only main process metrics are collected. Users can also set PROMETHEUS_MULTIPROC_DIR environment variable directly before starting the worker.""" def validate_config(self, devmode: bool) -> None: load_threshold = ServerEnvOption.getvalue(self.load_threshold, devmode) if load_threshold > 1 and not devmode: logger.warning( f"load_threshold in prod env must be less than 1, current value: {load_threshold}" )
t
Thanks — I see you’ve pasted your
ServerOptions
dataclass. That’s helpful. To narrow why redeploys crash after moving to AgentServer, a few focused checks and one quick set of questions: Quick checks (please confirm): • Ensure your
entrypoint_fnc
is pickle-able (top-level function or callable) — AgentServer requires picklable entrypoints for child processes. • Verify you start the server with the CLI helper (
agents.cli.run_app(server)
/
cli.runApp(server)
). • Confirm you aren’t mixing legacy Worker patterns with AgentServer (entrypoint decoration and lifecycle differ). • Check `multiprocessing_context`: on Linux it defaults to `"forkserver"`; on other platforms it’s
"spawn"
. Mismatched context can cause child process failures on redeploy. • Inspect memory settings: if
job_memory_limit_mb
is set >0, child processes may be killed on exceed and cause instability. • Check
drain_timeout
/
shutdown_process_timeout
— short timeouts can cause forceful kills during redeploy. • If using Prometheus multiproc mode, ensure
PROMETHEUS_MULTIPROC_DIR
is set when
prometheus_multiproc_dir
is used. Please send these items so I can give targeted steps: 1. Exact error message or stack trace from the crash (deploy logs via
lk agent logs
are best). 2. The entrypoint function code and how you register/start the
AgentServer
. 3. Whether this happens locally, in a container, or on a cloud platform (and your orchestration method). 4. LiveKit Agents SDK version you’re running. 5. Any custom shutdown/exception handling or changes to
multiprocessing_context
, memory limits, or prewarm logic. Share those and I’ll recommend the precise fixes or a minimal repro to replicate the crash.
g
worker_options = agents.WorkerOptions( _ws_url_=get_config().livekit_url, _api_key_=get_config().livekit_api_key, _api_secret_=get_config().livekit_api_secret, _entrypoint_fnc_=_worker_entry, _agent_name_=_agent_name_, _max_retry_=3, port=0, # Use random available port to avoid conflicts ) worker = AgentServer.from_server_options(worker_options) we are using this
t
Thanks — I see your
WorkerOptions
snippet and that you call
AgentServer.from_server_options(...)
. To diagnose the redeploy crash, please provide the following so I can give exact fixes: 1. The crash error message or full stack trace (from
lk agent logs
if possible). 2. The
_worker_entry
function code (ensure it’s a top-level, pickle-able callable). 3. Exact LiveKit Agents SDK version. 4. Deployment environment: local, Docker container, Kubernetes, or a cloud service. 5. Any custom shutdown/exception handling or changes to
multiprocessing_context
, memory limits, or prewarm logic. While you gather that, double-check these immediately: • Field names: use
ws_url
,
api_key
,
api_secret
,
entrypoint_fnc
,
agent_name
,
max_retry
,
port
(not underscored variants). • Confirm
entrypoint_fnc
is defined at module top level (not nested or a lambda) so it’s pickle-able. • If using Docker/K8s, ensure the chosen
multiprocessing_context
and process lifecycle work inside containers (forkserver vs spawn). • Try setting
port
to a non-random fixed port temporarily to rule out port-binding race conditions during redeploy. Send the logs and
_worker_entry
code and I’ll provide targeted remediation.
a
I was using agents.Workers which got deppricated and i switched to AgentServer, what should i change in order to keep my agents available
t
You're on the right track—AgentServer requires a few concrete changes compared to the deprecated Workers model to keep agents stable and available. Below is a concise migration checklist and best-practices to prevent redeploy crashes. What to change / verify • Use correct options field names when building options (no leading underscores):
ws_url
,
api_key
,
api_secret
,
entrypoint_fnc
,
agent_name
,
max_retry
,
port
. • Ensure the entrypoint is pickle‑able: define
_worker_entry
as a top‑level function or top‑level callable (not nested, not a lambda, not a bound method). • Start the server with the CLI helper: in Python use
agents.cli.run_app(server)
(or equivalent entry used by your deploy tooling). This hooks lifecycle and signal handling correctly. • Use
AgentServer.from_server_options(...)
(you already do) but pass validated ServerOptions / WorkerOptions built with the fields above. • Pick a stable port strategy for health checks: using random ports can cause race conditions during redeploys; prefer a fixed port for the HTTP health endpoint if your orchestrator expects consistent readiness probes. • Multiprocessing context: on Linux the default is
"forkserver"
, otherwise
"spawn"
. Confirm your environment supports the chosen context—mismatches can break child process startup on redeploy. • Shutdown and drain timing: set reasonable
drain_timeout
,
shutdown_process_timeout
, and
initialize_process_timeout
so jobs can finish or be drained gracefully during redeploy. • Memory and load settings: review
job_memory_limit_mb
,
job_memory_warn_mb
,
num_idle_processes
, and
load_threshold
so child processes aren’t unexpectedly killed or marked unavailable. • Prometheus multiproc: if you enable
prometheus_multiproc_dir
, ensure
PROMETHEUS_MULTIPROC_DIR
is set in the environment or metrics from child processes will fail. Common causes of redeploy crashes • Non‑pickleable entrypoint causing failure when child processes are spawned. • Mixing legacy Worker lifecycle patterns with AgentServer startup/CLI usage. • Random port collisions or health-check probes failing during fast restarts. • Incompatible multiprocessing context inside containers. • Uncaught exceptions in prewarm/entrypoint code that bubble up and destabilize the server during redeploy. Immediate actions I recommend 1. Change your options to use the canonical field names and ensure
_worker_entry
is a top‑level function. 2. Use a fixed
port
for the HTTP health endpoint to avoid probe race conditions. 3. Run the server via
agents.cli.run_app(server)
so the CLI-managed lifecycle handles signals and graceful shutdown. 4. Reproduce redeploy locally while streaming logs with
lk agent logs
and capture the stack trace if it still crashes. If you’d like, send: • The
_worker_entry
function code, • The exact options object you pass (after renaming fields), • The crash stack trace from
lk agent logs
, and I’ll give a targeted fix for the crash.
a
if i keep the port same, it only runs a single agent, but i want to run multiple agents
t
You're right to worry — port conflicts often look like "only one agent runs" but the HTTP
port
is just the health endpoint, not the agent count. Here's a clear plan to run multiple agents safely with AgentServer. Key facts • The
port
in ServerOptions is the local HTTP health endpoint. It does not limit how many agents you can run. • Each AgentServer process needs its own health port if you run multiple AgentServer processes on the same host. • To run multiple agents concurrently you can either: 1) Run a single AgentServer that accepts/hosts multiple agent sessions (recommended), or 2) Run multiple AgentServer processes (one per server instance) — each must use a unique health
port
(or
port=0
to let the OS pick one) and, if using explicit dispatch, a unique
agent_name
. What to do next • If you want many agents from one process: keep one AgentServer process and ensure your entrypoint and
worker_type
allow multiple concurrent jobs (e.g., ROOM vs PUBLISHER). Configure
num_idle_processes
,
job_executor_type
, and load settings to control concurrency. • If you prefer multiple AgentServer processes: start each process with a different
port
value (or
port=0
per process) and give distinct
agent_name
values when using explicit dispatch. Ensure your orchestration assigns separate ports or lets the OS assign them. • Avoid port collisions during rolling redeploys by using fixed ports per instance in your orchestrator, or by letting the port be random (
port=0
) and relying on your health-check integration that discovers the actual port. • Keep
entrypoint_fnc
pickleable and start via
agents.cli.run_app(server)
so lifecycle and signal handling work for graceful shutdown during redeploys. If you tell me which mode you prefer (single AgentServer multi‑agent vs multiple AgentServer processes) and your deployment environment (local, Docker, Kubernetes), I’ll give the exact configuration snippet and recommended ServerOptions values.
a
which mode will be best as i have multiple agents for different client, which can be used at any time. earlier the workers use to keep one insce of the agent running so that it could be dispatched anytime
t
For your use case — multiple agents for different clients that must be available on demand — I recommend running a single AgentServer process that can host multiple agent sessions (preferred). It matches your previous Workers behavior (keep agents ready) while avoiding port-talk complexity and redeploy port collisions. Why single AgentServer (recommended) • Keeps one process with many idle agent slots, so agents can be dispatched anytime without launching new server processes. • Easier lifecycle and signal handling (one health port, one CLI-managed process). • Use
num_idle_processes
,
job_executor_type
, and load settings to control concurrency and warm workers similar to the old model. • Avoids having to manage unique health ports and many processes during rolling redeploys. When to use multiple AgentServer processes • You need strict process-level isolation per client (security, resource limits, or per-client autoscaling). • You need distinct
agent_name
per process for long-lived explicit dispatch tied to a single agent instance. • Your orchestrator requires one agent per container instance. How to configure the single-server mode to replicate “one instance ready per agent” behavior • Keep one AgentServer and enable explicit dispatch if you want pre-assigned agent names, or keep automatic dispatch and let server spawn agents per room. • Set
num_idle_processes
to the number of concurrent idle agents you want warmed. • Tune
job_executor_type
to
process
if jobs are CPU/memory heavy, or
thread
for lighter workloads. • Use
load_threshold
and
load_fnc
to prevent overcommit; set `job_memory_warn_mb`/`job_memory_limit_mb` to protect stability. • Keep
port
fixed for the health endpoint so redeploys and readiness probes are stable. • Start with
agents.cli.run_app(server)
so lifecycle/signals are handled properly. • Ensure
entrypoint_fnc
is pickle-able and that
multiprocessing_context
is appropriate for your environment. If you want, tell me: • Deployment environment (Kubernetes, Docker Compose, VM, etc.) • Whether you require per-client process isolation or can share one server • Desired number of warmed agents per server I’ll give a concrete ServerOptions snippet and recommended values for
num_idle_processes
,
job_executor_type
,
port
, and timeouts for your environment.
a
how much resources dose a agentServer take up?
t
Good question — here’s a concise summary to help capacity-plan. Baseline recommendation • Start with ~4 CPU cores and 8 GB RAM per AgentServer for most voice-AI workloads. This typically supports ~10–25 concurrent jobs depending on features. Per‑agent/session overhead • Expect ~100 MB RAM per active conversation/session. • CPU usage scales with processing (VAD, noise cancellation, STT/TTS, LLM calls); heavy models or real‑time processing increase CPU substantially. Factors that change resource needs • Enabled features (noise cancellation, TURN detection) raise CPU/memory. • Large ML models or non‑prewarmed model loads increase memory and startup time. • Job isolation: jobs run in separate processes, so total usage scales with concurrent sessions and
job_executor_type
(process vs thread). • Prometheus multiproc and other instrumentation add some overhead. Sizing & scaling guidance • Use multiple AgentServer instances for higher concurrency; LiveKit will distribute jobs across them. • Autoscale on CPU (use a conservative threshold such as 50% to trigger scale-out). • Set
num_idle_processes
to warm the number of ready agents you want; each idle process consumes memory. • Give long drain/grace periods (10+ minutes) to avoid dropping active sessions during redeploys. Monitoring & tuning • Expose metrics and use a
load_fnc
that reflects real load (CPU or active sessions). • Monitor actual memory per session and CPU during a load test, then adjust instance size and
num_idle_processes
accordingly. If you tell me your expected concurrent sessions and whether you use heavy models (STT/TTS/LLM) or just light audio processing, I’ll recommend a specific instance size and
num_idle_processes
setting. Sources: Deploying to custom environments | LiveKit Docs | examples/drive-thru | livekit/livekit_composite | DeepWiki | Agent server options | LiveKit docs