How do you suggest dispatching a specific agent th...
# ask-ai
f
How do you suggest dispatching a specific agent that might be different depending on some conditional configuration?
t
Thanks for reaching out, Anish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
If you want to dispatch a specific agent based on some conditions, you can use explicit agent dispatch. Here’s a friendly walkthrough on how to set it up: 1. Set Agent Name for Explicit Dispatch: First, register your agent with an
agent_name
in
WorkerOptions
. This turns off automatic dispatch and gives you full control.
Copy code
agents.cli.run_app(agents.WorkerOptions(
    entrypoint_fnc=entrypoint,
    agent_name="my-agent"
))
2. Dispatch via API: Next, use the
AgentDispatchService
to send your agent to a room explicitly. Here’s how it looks: Node.js: `const { AgentDispatchClient } = require('livekit-server-sdk'); const agentDispatchClient = new AgentDispatchClient(process.env.LIVEKIT_URL); const dispatch = await agentDispatchClient.createDispatch( "my-room", "my-agent", { metadata: '{"mydata": "myvalue"}' } );`*Python:*
Copy code
import asyncio
from livekit import api

lkapi = api.LiveKitAPI()
dispatch = await lkapi.agent_dispatch.create_dispatch(
    api.CreateAgentDispatchRequest(
        agent_name="test-agent",
        room="my-room",
        metadata="my_metadata"
    )
)
3. Dispatch on Participant Connection: You can also set up a participant’s access token to automatically dispatch an agent when they join a room. Here’s an example: Node.js: `const { AccessToken, RoomConfiguration, RoomAgentDispatch } = require('livekit-server-sdk'); const at = new AccessToken(); at.identity = 'my-participant'; at.addGrant({ roomJoin: true, room: 'my-room' }); at.roomConfig = new RoomConfiguration({ agents: [ new RoomAgentDispatch({ agentName: 'test-agent', metadata: '{"mydata": "myvalue"}' }) ] }); const token = await at.toJwt();`*Python:*
Copy code
from livekit.api import RoomAgentDispatch, RoomConfiguration
token = (
    AccessToken()
    .with_identity("my_participant")
    .with_room_config(
        RoomConfiguration(
            agents=[
                RoomAgentDispatch(agent_name="test-agent", metadata="my_metadata")
            ],
        ),
    )
    .to_jwt()
)
4. Job Metadata: Any metadata you pass during dispatch will be available in the agent’s
JobContext
. This way, you can tailor your agent’s behavior based on different scenarios.
Copy code
async def entrypoint(ctx: JobContext):
    <http://logger.info|logger.info>(f"Job metadata: {ctx.job.metadata}")
    if ctx.job.metadata == '{"type": "customer-support"}':
        await handle_customer_support(ctx)
    else:
        await handle_default_case(ctx)
If you have any questions or need a hand with the implementation, just let me know — I’m happy to help!
f
I'm talking about instantiating an entirely new agent entirely
t
Hey there! If you want to dynamically create a brand-new agent in LiveKit, you can do this by extending the
Agent
class to add your own custom behavior, and then make an instance of it inside an
entrypoint
function. Here’s a simple way to get you started: 1. Extend the
Agent
Class:
Create a new class that inherits from
Agent
and define how it should behave.
Copy code
from livekit.agents import Agent

class DynamicAgent(Agent):
    def __init__(self, instructions: str):
        super().__init__(instructions=instructions)
2. Create an Instance of the Agent: Make your agent with the instructions you want it to follow.
Copy code
agent_instance = DynamicAgent(
    instructions="You are a helpful voice AI assistant."
)
3. Start the Agent Session: Use the
entrypoint
function to kick off the agent session.
Copy code
from livekit.agents import AgentSession
from livekit.plugins import openai, silero

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        vad=silero.VAD.load(),
        stt=openai.STT(),
        llm=openai.LLM(),
        tts=openai.TTS(),
    )

    await session.start(
        agent=agent_instance,
        room=ctx.room
    )
This approach gives you the flexibility to define and spin up agents on the fly, which is super handy if you want to handle different scenarios or specific needs. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: README.md