help me explain this: The worker-based architectur...
# ask-ai
b
help me explain this: The worker-based architecture for agents allows a single worker to manage multiple agent instances across different rooms
t
Thanks for reaching out, Jupiter. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking for a clear explanation of: "The worker-based architecture for agents allows a single worker to manage multiple agent instances across different rooms." Here's a concise, user-facing explanation you can use. What it means • A single agent worker process runs on a machine and can handle many independent agent sessions at once. • Each time a room or participant triggers an agent job, the worker starts a separate agent instance (a job/session) to manage that room's interaction. • Those instances run independently inside the same worker, so state and activity for one room don’t interfere with others. Why it’s useful • Efficient resource use: many sessions share the same worker process and machine resources. • Scalability: add more workers to handle higher load; incoming jobs are distributed across the worker pool. • Resilience: if one instance fails, other instances on the same worker keep running; load balancing and failover keep the system responsive. Short analogy • Think of the worker as a call center agent who can run multiple chat conversations at once; each chat is a separate session, but one person (the worker) manages all of them concurrently. If you want, I can turn this into a one-paragraph summary, a short slide bullet list, or a diagram-ready version. Which would help most? Sources: An open source stack for real-time multimodal AI | Agent server | LiveKit docs | Agent server options | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit docs
b
so every time the new call is coming, a new instance is created and the code in entrypoint will run one again right
t
Yes — that's correct. Each time a new call/job is dispatched, the worker starts a new agent instance (a job/session) for that room, and the entrypoint code for that instance runs. Each instance runs independently inside the worker, so the entrypoint executes per session without affecting other active instances.
b
is the logger created per new instance
t
Yes — the logger is created per agent instance. Each job runs in its own process, so the entrypoint for that session creates its own logger. This provides isolation (logs tied to that session) and lets you add per-session fields like
worker_id
and
room_name
via
ctx.log_context_fields
for easier debugging. Sources: Job lifecycle | LiveKit docs
b
these agent instances are separate processes or separate threads?
t
They run as separate processes. Each dispatched job starts its own agent process (an isolated session). That process runs the entrypoint, creates its own logger, and keeps state independent from other sessions. Process-level isolation prevents one instance's crash, memory leak, or blocking work from affecting others and makes per-session logging and diagnostics (e.g.,
worker_id
,
room_name
via
ctx.log_context_fields
) straightforward.
b
so you are saying the architecture is one worker, multiple processes
t
Yes — that's right. One worker process manages multiple agent instances by spawning a separate process for each dispatched job/session. Why this matters • Isolation: each agent runs in its own process so crashes, memory leaks, or blocking work in one instance won't affect others. • Per-session state & logging: each process runs the entrypoint and creates its own logger; you can attach fields like
worker_id
and
room_name
via
ctx.log_context_fields
for easy tracing. • Scalability: you can add more workers to increase capacity and the system will distribute jobs across the worker pool.
b
so if in the agent code, I create a logger like this in python:
Copy code
logger = setup_logger()
would this logger instance be used across agent instances? Or each agent instance has a different logger. Remember I initiated the logger at the top of the code, not inside the entrypoint function
t
You're correct to check — because each agent instance runs in its own process, the top-level
logger = setup_logger()
will be created once per process. That means: • If your module with
logger = setup_logger()
is imported/executed in each agent process, each process gets its own logger instance (they are not shared across processes). • If you spawn multiple instances as separate processes, the top-level logger in each process is independent and will not collide with others. Recommended practices • Add per-session fields (e.g.,
worker_id
,
room_name
,
session_id
) to the logger or log records so you can distinguish logs from different processes. You can set these in the entrypoint using your context helpers (for example,
ctx.log_context_fields
). • If you need centralized correlation, have each process include a unique session identifier in every log line and send logs to a central collector (e.g., stdout->aggregator) rather than relying on in-process objects. If you want, share a minimal snippet of your entrypoint and logger setup and I’ll point out exactly where to add session fields.
b
the setup_logger is kind of like this:
Copy code
logger = logging.getLogger()
I just want to understand if this logger instance is created only one and then used for all agent instances (created per phone call), or I will have the same number of logger instance created as the number of phone calls (for example, 5 calls means 5 logger instances created)
t
Short answer: you'll get one logger per agent process. Since each call runs as a separate process, a module-level
Copy code
logger = logging.getLogger()
is executed once inside each process — so 5 concurrent calls → 5 logger instances (one per process). They are independent; they don't share in-process objects. If you want correlated logs, add a per-session field (e.g.,
session_id
,
worker_id
,
room_name
) in the entrypoint or via
ctx.log_context_fields
so each process includes identifying metadata in every log line.
b
this is an example code:
Copy code
import logging

from dotenv import load_dotenv
from livekit import rtc
from livekit.agents import (
    Agent,
    AgentServer,
    AgentSession,
    JobContext,
    JobProcess,
    cli,
    inference,
    room_io,
)
from livekit.plugins import noise_cancellation, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

load_dotenv(".env.local")


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant. The user is interacting with you via voice, even if you perceive the conversation as text.
            You eagerly assist users with their questions by providing information from your extensive knowledge.
            Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
            You are curious, friendly, and have a sense of humor.""",
        )
server = AgentServer()


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


server.setup_fnc = prewarm


@server.rtc_session()
async def my_agent(ctx: JobContext):
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, AssemblyAI, and the LiveKit turn detector
    session = AgentSession(
        stt=inference.STT(model="assemblyai/universal-streaming", language="en"),
        llm=inference.LLM(model="openai/gpt-4.1-mini"),
        tts=inference.TTS(
            model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"
        ),
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
    )
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_options=room_io.RoomOptions(
            audio_input=room_io.AudioInputOptions(
                noise_cancellation=lambda params: noise_cancellation.BVCTelephony()
                if params.participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP
                else noise_cancellation.BVC(),
            ),
        ),
    )

    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(server)
So you are saying, the log in this code will be initiated every time a new call is coming?
t
Yes — in that code the logger is created each time a new agent process starts. Because each call/job runs in its own process, the module-level line
Copy code
logger = logging.getLogger("agent")
is executed once inside every process. So 5 concurrent calls → 5 separate logger instances (one per process). They are independent and do not share in-memory state. To make logs distinguishable, add per-session context in the entrypoint (you already set
ctx.log_context_fields = {"room": ctx.room.name}
) or attach a `session_id`/`worker_id` when the session starts so every log line includes identifying metadata.
b
and turn detection, vad is created again at every call?
t
Yes — VAD and turn detection are created per call. Each job runs in its own process, so whatever you initialize for the session (for example in
prewarm
or inside the
my_agent
entrypoint) is instantiated for that agent process only. In your code: •
prewarm
populates
proc.userdata["vad"]
once when the job process starts, and that VAD instance is used by that process for the lifetime of the call. •
MultilingualModel()
used in
AgentSession(turn_detection=...)
is also instantiated per agent process. So 5 concurrent calls → 5 separate VAD instances and 5 separate turn-detection instances, one per process. Sources: An open source stack for real-time multimodal AI | Turn detection and interruptions | LiveKit Docs | examples/survey | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit docs | Agent server options | LiveKit docs
b
what is the purpose of prewarm then, I thought it creates only one VAD? If not, it's the same as turn detector
t
Good question — prewarm does not create a single global VAD shared across calls. It runs once per job process to load expensive resources so they’re reused within that process. What prewarm does in your setup • When a worker accepts a job, it starts a new agent process. The process runs your module-level code and then calls
prewarm(proc)
once for that process. •
prewarm
sets
proc.userdata["vad"] = silero.VAD.load()
, so that VAD instance is created once for the lifetime of that process and reused by the agent session(s) running in that process. Why this matters • If you have 5 concurrent calls, there are 5 processes →
prewarm
runs 5 times → 5 VAD instances (one per process). • Within a single process, the VAD loaded in
prewarm
is reused by the session(s) in that process, avoiding repeated heavy loads inside the entrypoint. • Turn detection instantiated in the
AgentSession(...)
call is likewise per-process (created for that session), but if you want to reuse a turn-detector across sessions in the same process you can load it in
prewarm
and pass it from
proc.userdata
. If you’d like, I can show a short code example that loads both VAD and a turn detector in
prewarm
and reuses them in
my_agent
.
b
yes
t
Below is a minimal example showing how to load VAD and turn-detection models in
prewarm
and reuse them in
my_agent
. This keeps expensive loads to once per agent process while still giving each process its own instances.
Copy code
import logging
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, JobProcess, cli, room_io
from livekit.plugins import silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

server = AgentServer()

def prewarm(proc: JobProcess):
    # Runs once when the job process starts — load heavy resources here
    proc.userdata["vad"] = silero.VAD.load()
    proc.userdata["turn_detector"] = MultilingualModel()

server.setup_fnc = prewarm

@server.rtc_session()
async def my_agent(ctx: JobContext):
    # Attach per-session log fields
    ctx.log_context_fields = {"room": ctx.room.name}

    # Reuse the prewarmed instances from proc.userdata
    vad = ctx.proc.userdata["vad"]
    turn_detector = ctx.proc.userdata["turn_detector"]

    session = AgentSession(
        vad=vad,
        turn_detection=turn_detector,
        # ... other components ...
    )

    await session.start(
        agent=Agent(), 
        room=ctx.room,
        room_options=room_io.RoomOptions(
            # audio_input etc.
        ),
    )
    await ctx.connect()

if __name__ == "__main__":
    cli.run_app(server)
Benefits • Heavy models load once per process (in
prewarm
) instead of every time the entrypoint runs. • Each agent process still has isolated instances (no cross-call sharing). • Faster session startup inside the process because models are already loaded. • You can still add per-session identifiers to logs for correlation.
b
should we initialize turn detector in prewarm?
t
Yes — it's recommended to initialize the turn detector in
prewarm
when the model is expensive to load. Doing so gives you the same benefits as prewarming VAD: • Loads the model once per agent process instead of on every session start, reducing per-call startup latency. • Keeps the model instance isolated to that process (no cross-call sharing). • Lets multiple sessions in the same process reuse the loaded detector via
proc.userdata
. When to skip prewarm: • If the turn detector is cheap to construct or must be fresh per session (contains per-session mutable state you cannot share), initialize it inside the entrypoint instead. Quick example (reuse in entrypoint):
Copy code
def prewarm(proc: JobProcess):
    proc.userdata["turn_detector"] = MultilingualModel()

@server.rtc_session()
async def my_agent(ctx: JobContext):
    turn_detector = ctx.proc.userdata["turn_detector"]
    session = AgentSession(turn_detection=turn_detector, ...)
    ...
Would you like a version that clones the detector per session (if it’s stateful) or guidance on measuring load/startup time to decide?