how to make an agent join a specific room in pytho...
# ask-ai
a
how to make an agent join a specific room in python
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.
Hi there! To help you get an agent to join a specific room in Python using LiveKit, here are a couple of friendly methods you can try: 1. Explicit Dispatch via API You can use the
LiveKitAPI.agent_dispatch.create_dispatch()
method to programmatically send an agent to a room. Here’s a simple example to guide you:
Copy code
import asyncio
from livekit import api

room_name = "my-room"
agent_name = "test-agent"

async def create_explicit_dispatch():
    lkapi = api.LiveKitAPI()

    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name, room=room_name, metadata="my_metadata"
        )
    )
    print("created dispatch", dispatch)

    dispatches = await lkapi.agent_dispatch.list_dispatch(room_name=room_name)
    print(f"there are {len(dispatches)} dispatches in {room_name}")
    await lkapi.aclose()

asyncio.run(create_explicit_dispatch())
2. Dispatch via Access Token If you want the room to automatically dispatch an agent whenever a participant joins, you can embed a
RoomConfiguration
right into the participant’s access token like this:
Copy code
async def create_token_with_agent_dispatch() -> str:
    token = (
        api.AccessToken()
        .with_identity("my_participant")
        .with_grants(api.VideoGrants(room_join=True, room=room_name))
        .with_room_config(
            api.RoomConfiguration(
                agents=[api.RoomAgentDispatch(agent_name="test-agent", metadata="my_metadata")],
            ),
        )
        .to_jwt()
    )
    return token
Agent Worker Setup Don’t forget to make sure your agent worker is set up with the correct
agent_name
in
WorkerOptions
so everything matches perfectly:
Copy code
from livekit.agents import WorkerOptions, cli

async def entrypoint(ctx):
    print(f"Agent joining room: {ctx.room.name}")

if __name__ == "__main__":
    worker_opts = WorkerOptions(
        entrypoint_fnc=entrypoint,
        agent_name="test-agent"  # This must match the dispatch name
    )
    cli.run_app(worker_opts)
If you have any questions or need a hand with anything else, just let me know—I’m here to help! Sources: Authentication | LiveKit Docs | examples/agent_dispatch.py | Agent dispatch | LiveKit Docs