I've used the following dynamic worker and it's st...
# ask-ai
w
I've used the following dynamic worker and it's started. How can I create a new agent and a new session for this agent when a call comes in? Can I use a 'dispatch rule'? Please give me detailed instructions.
Copy code
# Python: agent worker entrypoint — read metadata and start AgentSession with dynamic params


import json
from livekit.agents import AgentSession, JobContext, cli
from livekit.plugins import silero, deepgram, openai, elevenlabs, cartesia

async def entrypoint(ctx: JobContext):
    metadata = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
    # Choose providers from metadata with safe defaults
    stt_choice = metadata.get("stt", "deepgram/nova-2")
    llm_choice = metadata.get("llm", "openai/gpt-4.1-mini")
    tts_choice = metadata.get("tts", "cartesia/sonic-3:default")
    vad_cfg = metadata.get("vad", {})

    # Load VAD with dynamic args if provided
    vad = await silero.VAD.load(**vad_cfg) if vad_cfg else await silero.VAD.load()

    session = AgentSession(
        stt=stt_choice,
        llm=llm_choice,
        tts=tts_choice,
        vad=vad,
    )

    # Optionally create an Agent subclass with instructions from metadata
    class DynamicAgent:
        def __init__(self, instructions):
            self.instructions = instructions
    agent_instructions = metadata.get("instructions", "You are a helpful assistant.")
    agent = DynamicAgent(agent_instructions)

    await session.start(room=ctx.room, agent=agent)
    # Optionally greet
    if metadata.get("greet", True):
        await session.generate_reply(instructions=f"Say hello to {metadata.get('user_name','user')}")
t
Thanks for reaching out, son. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're already on the right path — yes, you can use a SIP dispatch rule to create a new room, dispatch your dynamic agent worker, and start an AgentSession automatically when a call comes in. Below are concise, actionable steps that map directly to your provided entrypoint code. 1) Ensure your worker registers with the correct agent name • Add
agent_name
when you start the worker so dispatch targets it:
Copy code
if __name__ == "__main__":
    worker = WorkerOptions(
        entrypoint=entrypoint,
        agent_name="my-dynamic-agent"  # must match dispatch rule
    )
    cli.run_app(worker)
• Run the worker (e.g.,
uv run agent.py dev
). This makes the worker accept dispatched jobs. 2) Create a SIP dispatch rule that creates a new room and passes metadata • Example JSON (save as dispatch-rule.json). The
metadata
string is parsed by your
entrypoint
via `ctx.job.metadata`:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "name": "Voice Agent Dispatch Rule",
    "roomConfig": {
      "agents": [
        {
          "agentName": "my-dynamic-agent",
          "metadata": "{\"stt\":\"deepgram/nova-2\",\"llm\":\"openai/gpt-4.1-mini\",\"tts\":\"cartesia/sonic-3:default\",\"instructions\":\"You are a customer support assistant.\",\"user_name\":\"caller\",\"greet\":true}"
        }
      ]
    }
  }
}
• Key points: ◦
roomPrefix
creates a unique room per call. ◦
agentName
must match the worker’s
agent_name
. ◦ Put any dynamic config (models, instructions, greet, user_name, VAD options) in
metadata
. 3) Deploy the dispatch rule • Using LiveKit CLI: ◦
lk sip dispatch create dispatch-rule.json
• Or paste the JSON into the LiveKit Cloud Dashboard under Telephony → Dispatch rules → Create. 4) What happens on an incoming call • SIP INVITE → dispatch rule matches → new room created → LiveKit dispatches a job to any worker with
agentName: "my-dynamic-agent"
→ your
entrypoint(ctx)
runs, reads
ctx.job.metadata
, instantiates
AgentSession
, and calls
await session.start(room=ctx.room, agent=agent)
(as in your code). If
greet
is true, the session will send the greeting. 5) Optional: Dispatch programmatically or customize per-call • You can also dispatch an agent via CLI/API with custom metadata per call: ◦ Example CLI pattern: ▪︎
lk dispatch create --agent-name my-dynamic-agent --new-room --metadata '{"instructions":"You are a billing assistant."}'
• This is useful when you need per-call dynamic behavior beyond static dispatch rules. 6) Testing checklist • Start your worker with the matching
agent_name
. • Create or enable the dispatch rule. • Place a call to the phone number or SIP trunk configured with your LiveKit project. • Verify the worker logs show the job and that
session.start
runs and plays the greeting. If you’d like, tell me: • Are you using LiveKit Phone Numbers or a third-party SIP trunk? • Do you want per-call metadata supplied by an external system (so I can show an API/CLI dispatch example)? Sources: Agent server | LiveKit docs | SIP dispatch rule | LiveKit docs | Agent dispatch | LiveKit docs | Accepting inbound calls | LiveKit docs | https://blog.livekit.io/introducing-livekit-phone-numbers-zero-to-ringing-in-60-seconds/#/portal|
w
Can I define the agent_name more dynamically in the worker? With just one worker, but multiple dispatch rules, each rule would start a different agent, but share the same worker.
t
You're asking if a single worker process can register different `agent_name`s dynamically so multiple dispatch rules start different agents — short answer: you cannot change
agent_name
dynamically inside one running worker. What you can do • Run one worker per agent name (each worker started with a fixed
agent_name
) so dispatch rules targeting different agent names go to different processes. • Or use a single worker with one
agent_name
and make behavior dynamic via job
metadata
. Different dispatch rules can all target the same
agent_name
but pass different `metadata`; your
entrypoint(ctx)
reads
ctx.job.metadata
and instantiates different agent logic (models, instructions, VAD config, etc.). Recommended patterns • Multiple distinct agents (separate identities, scaling, or deployments): run multiple workers, each started with its own
agent_name
. • Single codebase, many behaviors: run one worker (one
agent_name
) and dispatch different metadata per rule. In your entrypoint, branch on metadata keys (e.g.,
agent_type
,
instructions
) and create the appropriate Agent or session config. If helpful, I can: • Show a small code example of branching on
ctx.job.metadata
in your existing entrypoint. • Show steps to run multiple worker instances with different `agent_name`s. Which would you prefer? Sources: Agent dispatch | LiveKit docs | Agents Framework | livekit/livekit_composite | DeepWiki
w
Can I start a worker using the following flow? 1. Node.js uses SDK links to deploy a new agent (optional name) 2. The worker also starts a new worker with that optional agent name
t
Short answer: No — a running worker cannot spawn or register new workers with different `agent_name`s. Deploying/starting workers is done outside the Node.js Agents SDK (via the LiveKit CLI / Cloud deployment), and each worker registers with a fixed
agent_name
at startup. What you can do (options): • Deploy multiple workers (recommended) ◦ Script CLI deployments that set AGENT_NAME per instance (e.g.,
lk agent create --secrets AGENT_NAME=billing-agent ...
). ◦ Each deployed worker runs the same code but reads
process.env.AGENT_NAME
and registers that name. • Reuse one worker for many behaviors (if you don’t need distinct agent identities) ◦ Use a single
agent_name
and vary behavior via dispatch
metadata
. ◦ In your entrypoint, branch on
ctx.job.metadata
to instantiate different Agents/instructions/models. • Automate deployments (outside the SDK) ◦ From Node.js you can call a deployment script or CI/CD that runs the LiveKit CLI or Cloud API to create new agent instances with the desired AGENT_NAME. The agent runtime itself cannot perform this. If you want, I can: • Show a short example of reading
AGENT_NAME
from env in Node or Python, or • Provide a small script pattern to automate CLI deployments from Node.js. Which would you prefer? Sources: Builds and Dockerfiles | LiveKit Docs | Agent deployment CLI reference | LiveKit docs | Deploying to production | LiveKit Docs | Agent dispatch | LiveKit docs | Agent server options | LiveKit docs
w
Please provide me with detailed examples of these flows
t
Below are detailed, practical examples for the three flows you can use: (A) single worker reading
AGENT_NAME
from env, (B) deploying multiple workers (each with its own agent name) via the LiveKit CLI, and (C) automating deployments from Node.js by invoking the CLI. I also include (D) how to use dispatch metadata so one worker can serve multiple behaviors. Pick the flow(s) you want to implement and follow the examples. A. Worker reads
AGENT_NAME
from environment (single codebase, deploy per agent) • Purpose: Use one codebase but start separate worker processes (containers/instances). Each process registers a different
agent_name
from env. • Node.js example (agent server startup)
Copy code
// server.js
import { AgentServer } from "@livekit/agents"; // pseudocode import
const agentName = process.env.AGENT_NAME || "default-agent";

const server = new AgentServer({
  agentName,
  // other config: credentials, requestFunc, etc.
});

server.start();
• Python example (your pattern):
Copy code
if __name__ == "__main__":
    worker = WorkerOptions(
        entrypoint=entrypoint,
        agent_name=os.environ.get("AGENT_NAME", "default-agent")
    )
    cli.run_app(worker)
• Deployment: set AGENT_NAME per instance (see B or C to automate). This lets dispatch rules target that name. B. Deploy multiple workers with different agent names using LiveKit CLI • Purpose: Create multiple agent deployments, each with a different AGENT_NAME environment variable, using the LiveKit CLI deploy commands. • Steps: a. Package your agent (Dockerfile present). b. Create/deploy each agent with different secrets/env: • Example CLI commands (replace placeholders): ◦ lk agent create --name customer-support-agent --secrets AGENT_NAME=customer-support-agent --image registry/your-agent:latest ◦ lk agent create --name billing-agent --secrets AGENT_NAME=billing-agent --image registry/your-agent:latest a. Confirm each agent shows as registered with the corresponding name. • Result: Dispatch rules referencing
agentName: "billing-agent"
or
"customer-support-agent"
will route jobs to the correct deployment. C. Automate deployments from Node.js by invoking CLI (scripted) • Purpose: Start deployments programmatically from a backend or CI job. The agent runtime itself must not spawn workers — do this from an orchestration service or script. • Approach: Node script that calls the LiveKit CLI (or Cloud API if available). Example uses child_process to run CLI.
Copy code
// deploy-agent.js
import { execSync } from "child_process";

function deployAgent({deployName, agentName, image}) {
  const cmd = `lk agent create --name ${deployName} --secrets AGENT_NAME=${agentName} --image ${image} --non-interactive`;
  console.log("Running:", cmd);
  execSync(cmd, { stdio: "inherit" });
}

// usage example
deployAgent({
  deployName: "agent-deploy-billing",
  agentName: "billing-agent",
  image: "registry/myagent:latest"
});
• Notes: ◦ Run this script from a CI runner, server, or admin backend that has the LiveKit CLI and credentials configured. ◦ You can also wrap
execSync
in async/promises and return logs or deployment metadata. D. Single worker, multiple behaviors via dispatch metadata • Purpose: Use one
agent_name
to handle many logical agent types by customizing behavior on each job using
ctx.job.metadata
. • How it works: ◦ Multiple dispatch rules point to the same
agentName
. ◦ Each dispatch rule includes different
metadata
JSON. ◦ Your
entrypoint
reads metadata and configures the AgentSession/Agent accordingly. • Example entrypoint (Python-style, compatible with your code)
Copy code
async def entrypoint(ctx: JobContext):
    metadata = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
    agent_type = metadata.get("agent_type", "generic")

    # choose behavior based on metadata
    if agent_type == "support":
        instructions = metadata.get("instructions", "You are a support assistant.")
        stt = metadata.get("stt", "deepgram/nova-2")
    elif agent_type == "sales":
        instructions = metadata.get("instructions", "You are a sales assistant.")
        stt = metadata.get("stt", "deepgram/commerce-model")
    else:
        instructions = metadata.get("instructions", "You are a helpful assistant.")
        stt = metadata.get("stt", "deepgram/nova-2")

    session = AgentSession(stt=stt, llm=metadata.get("llm","openai/gpt-4.1-mini"), tts=metadata.get("tts","cartesia/sonic-3:default"))
    class DynamicAgent:
        def __init__(self, instructions):
            self.instructions = instructions
    agent = DynamicAgent(instructions)
    await session.start(room=ctx.room, agent=agent)
• Example dispatch rule JSON (two rules can point to same agentName but different metadata)
Copy code
{
  "dispatch_rule": {
    "name": "support-call",
    "roomConfig": {
      "agents": [
        {
          "agentName": "generic-agent",
          "metadata": "{\"agent_type\":\"support\",\"instructions\":\"You are a support agent.\"}"
        }
      ]
    }
  }
}
and another rule:
Copy code
{
  "dispatch_rule": {
    "name": "sales-call",
    "roomConfig": {
      "agents": [
        {
          "agentName": "generic-agent",
          "metadata": "{\"agent_type\":\"sales\",\"instructions\":\"You are a sales agent.\"}"
        }
      ]
    }
  }
}
• Result: Single worker named
generic-agent
receives jobs and branches behavior by metadata. E. Testing and operational tips • Use environment variables for credentials and AGENT_NAME so the same image works for multiple deployments. • For automation, run CLI commands from CI or a privileged backend — do not attempt to run CLI from the agent runtime itself. • Monitor logs of each worker deployment to ensure dispatch jobs arrive and metadata is parsed. • If you need distinct identities in logs or dashboards, deploy separate workers (Flow B). If you want fewer deployments and flexible behavior, use Flow D. If you want, I can now: • Provide a full Dockerfile + sample Kubernetes manifest or Docker Compose to run multiple local worker instances with different AGENT_NAMEs, or • Convert the Node.js CLI automation script to use the LiveKit Cloud API (if you prefer an HTTP API route) — which would you like?
w
With (B) deploying multiple workers (each with its own agent name) via the LiveKit CLI. How are the workers started or registered? I'm using AWS for the workers. Please provide Python code examples and how to deploy the workers.
t
Acknowledged — you want detailed, runnable Python examples and AWS deployment steps showing how workers are started/registered so each worker has its own
agent_name
. Below are concise, practical examples and deployment options for EC2 and ECS (ECS recommended). Follow the flow that fits your environment. 1) Agent code (Python) — reads AGENT_NAME from env and registers • Put this in agent.py
Copy code
import os
import json
import asyncio
from livekit.agents import WorkerOptions, JobContext, cli, JobRequest

# Your entrypoint that starts an AgentSession (simplified)
async def entrypoint(ctx: JobContext):
    metadata = json.loads(ctx.job.metadata) if ctx.job.metadata else {}
    # Example: create session & agent based on metadata (insert your full logic)
    print(f"Starting AgentSession for agent_name={ctx.job.agent_name} room={ctx.room.name}")
    # ... your AgentSession start logic here ...
    await asyncio.sleep(3600)  # placeholder to keep session running

# Optional: accept only jobs targeted at this worker's AGENT_NAME
async def job_request_handler(req: JobRequest):
    expected = os.getenv("AGENT_NAME", "default-agent")
    if req.agent_name == expected:
        print(f"Accepting job for {req.agent_name}")
        await req.accept(entrypoint)
    else:
        # decline non-matching agent_name so this worker doesn't take other agent jobs
        await req.decline()

if __name__ == "__main__":
    # WorkerOptions ties into LiveKit agent runtime; CLI will read env for credentials
    worker_opts = WorkerOptions(
        request_handler=job_request_handler,
    )
    cli.run_app(worker_opts)
Key points: • Set AGENT_NAME env var per container/instance. • Worker connects to LiveKit (credentials via env: LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET). • When LiveKit dispatches a job for agentName X, only workers with AGENT_NAME==X should accept (handler enforces this). 2) Dockerfile (containerize the agent)
Copy code
FROM python:3.11-slim
WORKDIR /app
COPY pyproject.toml requirements.txt ./
RUN pip install -r requirements.txt
COPY . .
CMD ["uv", "run", "agent.py", "dev"]
3) Run on a single EC2 instance (quick start) • Build and push your image to ECR or use local image. • On EC2 (assumes Docker installed): Run worker for voice-assistant:
Copy code
docker run -d --name voice-assistant \
  -e LIVEKIT_URL="wss://your.livekit.cloud" \
  -e LIVEKIT_API_KEY="your-key" \
  -e LIVEKIT_API_SECRET="your-secret" \
  -e AGENT_NAME="voice-assistant" \
  -e OTHER_SECRETS="..." \
  your-repo/agent:latest
Run worker for transcriber (same host or different host):
Copy code
docker run -d --name transcriber \
  -e LIVEKIT_URL="wss://your.livekit.cloud" \
  -e LIVEKIT_API_KEY="your-key" \
  -e LIVEKIT_API_SECRET="your-secret" \
  -e AGENT_NAME="transcriber" \
  your-repo/agent:latest
Notes: • Each container registers with LiveKit using its AGENT_NAME. • For production, run multiple replicas of each agent type for HA. 4) Recommended: Deploy with AWS ECS (Fargate) — pattern • Create one ECS Task Definition per agent type using same container image but different environment variables. ◦ Task Definition env: AGENT_NAME=voice-assistant / AGENT_NAME=transcriber ◦ Include LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET in task env or AWS Secrets Manager. • Create an ECS Service per agent type. • Scale each service independently. ECS task (env) snippet:
Copy code
"environment":[
  {"name":"AGENT_NAME","value":"voice-assistant"},
  {"name":"LIVEKIT_URL","value":"wss://your.livekit.cloud"},
  {"name":"LIVEKIT_API_KEY","value":"your-key"},
  {"name":"LIVEKIT_API_SECRET","value":"your-secret"}
]
Deployment steps (high level): 1. Build Docker image and push to ECR. 2. Create ECS Task Definition referencing the image. 3. Create ECS Service using the task (Fargate recommended). 4. Set desired count; use autoscaling policies as needed. 5. Repeat for each agent type (change AGENT_NAME). 5) Health, logging, and scaling • Add a lightweight /health HTTP endpoint in container (sidecar or small server) for ECS health checks. • Send logs to CloudWatch; monitor accepted/declined job events and session lifecycle. • Run >=2 replicas per agent type for availability. 6) Security & credentials • Store LIVEKIT_API_KEY/SECRET in AWS Secrets Manager and inject via task role/secret integration. • Ensure outbound 443 allowed to LiveKit endpoints (no inbound ports required for workers). 7) Example: Scripted deploy with AWS CLI + CloudFormation (pattern) • Build image, push to ECR: ◦ docker build -t my-agent:latest . ◦ docker tag ... && docker push ... • Create/Update ECS task and service via CloudFormation or Terraform using AGENT_NAME as environment variable for each service. • Use CI to deploy new revisions. 8) Testing • Start worker(s) and confirm logs show connection and registration. • Create a dispatch rule referencing agentName (e.g., "voice-assistant"). • Call the number or trigger dispatch; verify that the matching worker accepts job and runs entrypoint. If you want, I can: • Provide a full sample ECS Task Definition JSON and CloudFormation snippet for one agent type, or • Provide a sample systemd unit or docker-compose file for local multi-worker testing. Which deployment artifact would you like next: ECS Task Definition + CloudFormation snippet or docker-compose for local testing? Sources: Agents Framework | livekit/livekit_composite | DeepWiki | Agent deployment CLI reference | LiveKit docs | AWS AI and LiveKit | LiveKit Docs | Deploying to production | LiveKit Docs | Agent dispatch | LiveKit docs
w
In aws, I use Amazon Elastic Container Service, so I can start a new task with a separate env (with AGENT_NAME) when the agent is created using the deploy-agent.js code. Give me a specific example, deploy-agent.js will have code to manage the status of this task.
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!