I have two agents deployed and connected to differ...
# ask-ai
f
I have two agents deployed and connected to different livekit clouds. How can I create a room in ane of the clouds and dispatch both agents in that room. Provide Python code examples.
t
Thanks for reaching out, Taras. 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 create a room in one of your LiveKit clouds and dispatch both agents to it, here’s a simple step-by-step guide you can follow: 1. Set Up Your Agents First, make sure each agent is running with a specified
agent_name
in its
WorkerOptions
. This is important for explicit dispatching. Here’s an example to get you started:
Copy code
from livekit.agents import WorkerOptions, cli

opts = WorkerOptions(
    agent_name="agent-1",  # Unique name for the agent
)

async def entrypoint(ctx):
    pass  # Your agent logic here

if __name__ == "__main__":
    cli.run_app(opts, entrypoint)
2. Create a Room and Dispatch Agents Next, you can use the LiveKit API to create a room and explicitly dispatch your agents like this:
Copy code
import asyncio
from livekit import api

async def create_room_and_dispatch():
    lkapi = api.LiveKitAPI(
        url="your-livekit-url",  # e.g., wss://project.livekit.cloud
        api_key="your-api-key",
        api_secret="your-api-secret"
    )

    # Dispatch the first agent
    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-1",
            room="my-room",
            metadata='{"role": "support"}'
        )
    )

    # Dispatch the second agent
    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-2",
            room="my-room",
            metadata='{"role": "assistant"}'
        )
    )

    print("Agents dispatched to room 'my-room'")
    await lkapi.aclose()

asyncio.run(create_room_and_dispatch())
3. A Few Helpful Notes • Make sure both agents are up and running, each registered with their own
agent_name
. • Rooms will be created automatically during dispatch if they don’t already exist, so no worries there! • You can pass metadata to customize how agents behave within the room, which can be really handy. If you have any questions or need a hand with any part of this, please don’t hesitate to reach out. I’m here to help! Sources: Agent dispatch | LiveKit Docs | pkg/service/agent_dispatch_service.go | livekit-protocol/livekit/protocol/agent_dispatch.pyi | Authentication | LiveKit Docs
f
My second agent is connected to different LiveKit cloud, how lkapi will know how to find it??
t
Hi there! To help you dispatch agents connected to different LiveKit clouds, you'll want to configure and authenticate each LiveKit instance separately. Don’t worry, I’ll walk you through the steps: 1. Set Up Each Agent with a Unique
agent_name
Make sure each agent runs with its own unique
agent_name
and connects to the correct LiveKit cloud instance. For example:
Copy code
opts = WorkerOptions(
    agent_name="agent-1",  # For the first LiveKit cloud
)

opts = WorkerOptions(
    agent_name="agent-2",  # For the second LiveKit cloud
)
2. Authenticate and Dispatch to Each Cloud You’ll use the LiveKit API to authenticate and dispatch agents to their respective clouds. For each cloud, just initialize the API client with the right URL, API key, and secret like this:
Copy code
import asyncio
from livekit import api

async def dispatch_to_cloud_1():
    lkapi = api.LiveKitAPI(
        url="https://cloud1.livekit.cloud",  # First LiveKit cloud
        api_key="api-key-cloud1",
        api_secret="api-secret-cloud1"
    )

    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-1",
            room="my-room",
            metadata='{"role": "support"}'
        )
    )
    await lkapi.aclose()

async def dispatch_to_cloud_2():
    lkapi = api.LiveKitAPI(
        url="https://cloud2.livekit.cloud",  # Second LiveKit cloud
        api_key="api-key-cloud2",
        api_secret="api-secret-cloud2"
    )

    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-2",
            room="my-room",
            metadata='{"role": "assistant"}'
        )
    )
    await lkapi.aclose()

async def main():
    await asyncio.gather(dispatch_to_cloud_1(), dispatch_to_cloud_2())

asyncio.run(main())
3. Key Notes • Each LiveKit cloud instance needs its own API client with the correct credentials. • Be sure the
agent_name
matches what you set in the agent’s
WorkerOptions
. • Rooms will be created automatically during dispatch if they don’t already exist. This way, your agents connected to different LiveKit clouds can be dispatched to the same room name within their own clouds. If anything feels unclear or you want me to explain further, just let me know—I’m here to help! Sources: Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts | examples/voice_agents/realtime_joke_teller.py
f
I need these 2 agents to communicate with each other in the same room
t
Hi there! To help two agents from different LiveKit clouds chat together in the same room, here’s a simple guide you can follow: 1. Make Sure Both Agents Join the Same Room It’s important that both agents connect using the same room name and URL. Each should have valid access tokens and a unique
agent_name
to keep things clear. 2. Turn On Agent-to-Agent Communication By default, agents don’t hear audio from other agents. To enable this, you’ll want to set up the
RoomInputOptions
so they can listen to each other’s audio like this:
Copy code
room_io = RoomIO(
    session,
    room=ctx.room,
    input_options=RoomInputOptions(listen_to_agents=True)
)
You could also try:
Copy code
RoomInputOptions(agents_allowed=True)
Or specify the participant types like this:
Copy code
RoomInputOptions.participant_kinds = [rtc.ParticipantKind.PARTICIPANT_KIND_AGENT]
3. Set Up Cross-Cloud Communication LiveKit is designed so participants (including agents) from different clouds can join the same logical room. Just make sure each agent is properly authenticated with the right API credentials for their cloud. 4. Important Things to Keep in Mind • Both agents need to connect to the exact same room name/URL. • Agent-to-agent audio must be enabled for them to hear each other. • For full interaction, set up Text-to-Speech (TTS) and Speech-to-Text (STT) as well. If you’d like, I’m happy to share a full code example to help you get this going smoothly. Just let me know! Sources: examples/voice_agents/llamaindex-rag/data/raw_data.txt | delay-handling/raw_data.txt | Agent Testing & CI/CD | livekit/livekit_composite | DeepWiki | How to Enable Agent-to-Agent Speech Detection in LiveKit | Knowledge Base Content | livekit/livekit_composite | DeepWiki
f
Provide Python example on how to Make Sure Both Agents Join the Same Room (generate and deliver access tokens, etc.)
t
To make sure both agents can join the same room smoothly, you'll want to generate and share access tokens for each agent. Let's walk through how you can do this in Python: 1. Generate Access Tokens Here's a handy function to create a token for an agent with the right room setup:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

def create_token_with_agent_dispatch(room_name: str, participant_identity: str, agent_name: str, metadata: str = None) -> str:
    token = (
        AccessToken()
        .with_identity(participant_identity)
        .with_grants(
            VideoGrants(
                room_join=True,
                room=room_name,
            )
        )
        .with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name=agent_name,
                        metadata=metadata or "",  # Optional metadata
                    )
                ],
            ),
        )
        .to_jwt()
    )
    return token
2. Deliver Tokens Securely Here's an example of a REST API endpoint you can use to safely deliver these tokens:
Copy code
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

@app.route('/generate-token', methods=['POST'])
def generate_token():
    data = request.json
    room_name = data.get('room_name')
    identity = data.get('identity', f'user-{os.urandom(4).hex()}')
    agent_name = data.get('agent_name', 'default-agent')

    try:
        token = create_token_with_agent_dispatch(
            room_name=room_name,
            participant_identity=identity,
            agent_name=agent_name,
            metadata='{"user_id": "12345"}'
        )
        return jsonify({"token": token, "room": room_name})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(port=5000)
3. Key Notes • Make sure the
agent_name
matches the name you've set in the agent's
WorkerOptions
. • Always deliver tokens securely over HTTPS to keep things safe and prevent unauthorized access. • Rooms will be created automatically the moment a token is used to join. If anything isn’t clear or if you'd like me to provide more examples, just let me know! I'm here to help. Sources: auth.py | rover/auth.py | complex-agents/nova-sonic/nova-sonic-form-agent/app/api/connection-details/... | livekit-agents/livekit/agents/jupyter.py | README.md
f
how do I use this token to add my agent to the room? Provide python example
t
To help you add your agent to a room using an access token, here’s a simple step-by-step guide: 1. Generate the Access Token Start by using this Python code to create a token that includes agent dispatch:
Copy code
from livekit import api
import os

# Create access token with agent dispatch
def generate_agent_token():
    token = (
        api.AccessToken(
            api_key=os.getenv('LIVEKIT_API_KEY'),
            api_secret=os.getenv('LIVEKIT_API_SECRET')
        )
        .with_identity("participant-identity")  # Unique identity for the participant
        .with_grants(api.VideoGrants(
            room_join=True,
            room="my-room"
        ))
        .with_room_config(
            api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(
                        agent_name="test-agent",      # Must match the name in WorkerOptions
                        metadata="optional context"   # Passed to the agent when it joins
                    )
                ]
            )
        )
        .to_jwt()
    )
    return token

print("Generated token:", generate_agent_token())
2. Use the Token to Join the Room Once you have your token, you can use it to connect the participant to the room. When they join, the agent you specified will automatically be dispatched to the same room:
Copy code
from livekit import Room
import asyncio

async def join_room_with_token(token):
    room = Room()
    await room.connect("wss://your-livekit-instance.livekit.cloud", token)
    print("Participant and agent joined the room")

# Example usage
asyncio.run(join_room_with_token(generate_agent_token()))
3. A Few Important Notes • Make sure the
agent_name
exactly matches the name set in the agent’s
WorkerOptions
. • The agent worker should be up and running, registered with the correct
agent_name
. • Rooms will be created automatically as soon as the first participant or agent connects. If anything is unclear or you’d like me to walk you through more examples, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-bey/livekit/plugins/bey/avatar.py | Generating tokens | LiveKit docs | Agent dispatch | LiveKit Docs | Authentication | LiveKit Docs | README.md
f
ImportError: cannot import name 'Room' from 'livekit'
t
It seems like the
Room
class might not be available in the version of the LiveKit Python SDK you're currently using. No worries! A great alternative is to use the
livekit-agents
framework, which is designed for agent-based applications and makes interacting with rooms much simpler. Here's a helpful example to get you started: Using
JobContext
for Agent Interaction
Copy code
from livekit.agents import JobContext, AutoSubscribe

async def entrypoint(ctx: JobContext):
    # Connect to the room
    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)

    # Wait for a participant to join
    participant = await ctx.wait_for_participant()
    print(f"Participant joined: {participant.identity}")

    # Perform additional actions here

if __name__ == "__main__":
    from livekit.agents import cli
    cli.run_app(entrypoint=entrypoint)
Alternatively: Use the LiveKit API for Room Management If you're looking to manage rooms programmatically, the
livekit-api
package is a wonderful tool to consider:
Copy code
from livekit.api import LiveKitAPI, CreateRoomRequest
import asyncio

async def create_and_manage_room():
    async with LiveKitAPI() as lkapi:
        # Create a room
        room_info = await lkapi.room.create_room(CreateRoomRequest(name="my-room"))
        print("Room created:", room_info)

asyncio.run(create_and_manage_room())
Please feel free to reach out if you'd like me to walk you through any part of this or if you have any other questions. I'm here to help! Sources: examples/basic_room.py | agent.py | sip-refer/README.mdoc | Managing rooms | LiveKit docs
f
how do I dispatch agent to the created room?
t
To dispatch an agent to a created room in LiveKit, you can use the
AgentDispatchService
from the LiveKit API. Let me walk you through how to do it in Python: 1. Configure the Agent Worker First, make sure your agent is running with a specified
agent_name
in its
WorkerOptions
. For example:
Copy code
opts = WorkerOptions(
    agent_name="test-agent",  # Unique name for the agent
)
2. Dispatch the Agent to the Room Here's a simple way to explicitly dispatch the agent to a room:
Copy code
import asyncio
from livekit import api

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

async def create_explicit_dispatch():
    lkapi = api.LiveKitAPI(
        url="wss://your-livekit-server.com",
        api_key="your-api-key",
        api_secret="your-api-secret"
    )

    # Dispatch the agent to the room
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name,
            room=room_name,
            metadata='{"user_id": "12345"}'  # Optional metadata
        )
    )
    print("Created dispatch:", dispatch)

    # List all dispatches in the room
    dispatches = await lkapi.agent_dispatch.list_dispatch(room_name=room_name)
    print(f"There are {len(dispatches)} dispatch(es) in {room_name}")

    await lkapi.aclose()

asyncio.run(create_explicit_dispatch())
3. Key Notes • The
agent_name
in the dispatch request should match the name registered in the agent's
WorkerOptions
. • If the room doesn’t exist yet, it will be created automatically for you. • You can also pass optional metadata to the agent to provide extra context. If you have any questions or would like me to provide more examples, please don’t hesitate to ask. I’m here to help! Sources: Agent dispatch | LiveKit Docs | livekit-protocol/livekit/protocol/agent_dispatch.pyi
f
I need to dispatch another agent running on different livekit cloud
t
I'm happy to guide you through dispatching another agent running on a different LiveKit cloud to the same room. To do this, you'll want to configure and authenticate each LiveKit instance separately. Let’s walk through the steps together: 1. Dispatch the First Agent Start by using the API client for the first LiveKit cloud to dispatch the first agent:
Copy code
import asyncio
from livekit import api

async def dispatch_to_cloud_1():
    lkapi = api.LiveKitAPI(
        url="https://cloud1.livekit.cloud",  # First LiveKit cloud
        api_key="api-key-cloud1",
        api_secret="api-secret-cloud1"
    )

    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-1",
            room="my-room",
            metadata='{"role": "support"}'
        )
    )
    await lkapi.aclose()
2. Dispatch the Second Agent Next, use the API client for the second LiveKit cloud to dispatch the second agent:
Copy code
async def dispatch_to_cloud_2():
    lkapi = api.LiveKitAPI(
        url="https://cloud2.livekit.cloud",  # Second LiveKit cloud
        api_key="api-key-cloud2",
        api_secret="api-secret-cloud2"
    )

    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="agent-2",
            room="my-room",
            metadata='{"role": "assistant"}'
        )
    )
    await lkapi.aclose()
3. Run Both Dispatches Finally, you can use
asyncio.gather
to run both dispatches at the same time:
Copy code
async def main():
    await asyncio.gather(dispatch_to_cloud_1(), dispatch_to_cloud_2())

asyncio.run(main())
Key Notes • Remember, each LiveKit cloud instance needs its own API client with the right credentials. • Make sure the
agent_name
matches the name you’ve set in the agent’s
WorkerOptions
. • If the room doesn’t exist yet, it will be created automatically during dispatch. This setup helps you dispatch agents from different LiveKit clouds to the same room name in their own clouds smoothly. If anything feels unclear or you want to dive deeper, please don’t hesitate to ask—I’m here to help! Sources: SIP dispatch rule | LiveKit docs | Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts
f
I need both agent to communicate in the same room
t
To help you enable communication between agents from different LiveKit clouds in the same room, here’s a step-by-step guide that should make the process smoother for you: 1. Enable Agent-to-Agent Interaction By default, agents don’t process audio from other agents, but you can easily change this by configuring the
RoomInputOptions
. Here’s how:
Copy code
room_io = RoomIO(
    session,
    room=ctx.room,
    options=RoomInputOptions(agents_allowed=True)  # Allow agents to process each other's media
)
Alternatively, you can specify participant kinds like this:
Copy code
RoomInputOptions.participant_kinds = [rtc.ParticipantKind.PARTICIPANT_KIND_AGENT]
2. Leverage LiveKit’s Distributed Mesh Architecture LiveKit’s architecture is designed to automatically relay media between SFU instances across different clouds. Just make sure both agents connect to the same room name, and the system will take care of the cross-cloud communication seamlessly. 3. Authenticate Agents It’s important that each agent connects using a valid access token with the right permissions. Here’s a simple example to create such a token:
Copy code
from livekit.api import AccessToken, VideoGrants

def create_agent_token(room_name, agent_name):
    token = (
        AccessToken()
        .with_identity(agent_name)
        .with_grants(VideoGrants(room_join=True, room=room_name))
        .to_jwt()
    )
    return token
4. Dispatch Agents to the Room To explicitly dispatch agents to the room from their respective LiveKit clouds, use the
AgentDispatchService
. Just ensure each API client is properly set up for the correct cloud instance. Here’s how you can do it:
Copy code
async def dispatch_agent(api_url, api_key, api_secret, room_name, agent_name):
    lkapi = api.LiveKitAPI(
        url=api_url,
        api_key=api_key,
        api_secret=api_secret
    )

    await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name,
            room=room_name,
            metadata='{"role": "assistant"}'
        )
    )
    await lkapi.aclose()
Key Notes • Make sure both agents are set up to process media from other agents. • Rooms will be created automatically during dispatch if they don’t already exist. • LiveKit’s architecture handles cross-cloud communication smoothly and behind the scenes. If you have any questions or need more examples, please feel free to ask—I’m here to help you every step of the way! Sources: test/agent_test.go | Knowledge Base Content | livekit/livekit_composite | DeepWiki | How to Enable Agent-to-Agent Speech Detection in LiveKit | examples/voice_agents/llamaindex-rag/data/raw_data.txt | delay-handling/raw_data.txt
f
How exactly do I Authenticate Agents using created token?
t
To help you authenticate agents in LiveKit using access tokens, here’s a simple step-by-step guide you can follow: 1. Create an Access Token for the Agent Here’s a Python snippet that shows how to generate a JWT token for your agent:
Copy code
from livekit import api
import datetime

# Replace with your API key and secret
api_key = "your-api-key"
api_secret = "your-api-secret"

def create_agent_token(agent_name, room_name):
    token = (
        api.AccessToken(api_key, api_secret)
        .with_identity(agent_name)  # Unique identity for the agent
        .with_grants(api.VideoGrants(room_join=True, room=room_name))
        .with_ttl(datetime.timedelta(hours=1))  # Token valid for 1 hour
        .to_jwt()
    )
    return token

agent_token = create_agent_token("agent-1", "my-room")
print("Generated token:", agent_token)
2. Use the Token to Authenticate the Agent When your agent connects to the LiveKit server, you’ll want to pass the token like this in the worker’s code:
Copy code
from livekit.agents import WorkerOptions, cli

opts = WorkerOptions(
    agent_name="agent-1",  # Must match the identity in the token
    access_token=agent_token  # Use the generated token here
)

async def entrypoint(ctx):
    print("Agent authenticated and connected to room")

if __name__ == "__main__":
    cli.run_app(opts, entrypoint)
3. A Few Important Tips • Make sure the
agent_name
in your token exactly matches the name set in the agent’s
WorkerOptions
. • Always generate tokens securely on your server and avoid exposing them to clients. • Set a sensible TTL (time-to-live) for your tokens to keep things secure. If anything isn’t clear or you’d like me to walk you through more examples, just let me know—I’m here to help! Sources: app/api/connection-details/route.ts | Mobile Application Examples | livekit/livekit_composite | DeepWiki | Authentication | LiveKit Docs | livekit-agents/livekit/agents/inference/_utils.py | Agent dispatch | LiveKit Docs
f
how can I include mock participant to the room during or after agent dispatch?
t
Hi there! I understand you're looking to add a "mock participant" to a production room in LiveKit, and I’m here to help guide you through what’s possible. Currently, LiveKit doesn’t natively support adding a mock participant directly into a production room during or after agent dispatch. But don’t worry! There are some great simulation tools designed specifically for testing and development that might just do the trick for you: 1. Simulate Participants Using the JavaScript SDK The JavaScript SDK offers a handy
simulateParticipants
method to help you test:
Copy code
const room = new Room();
room.simulateParticipants({
    numParticipants: 3, // Simulate 3 participants
    useRealTracks: false, // Use dummy media tracks
});
This lets you create a simulated room with mock participants, perfect for testing your UI or how agents behave. Just keep in mind, this is meant for testing and not for use in production environments. 2. Simulate Jobs Using the Agents SDK Another helpful option is the LiveKit Agents SDK, which allows you to simulate a job with a mock participant context like this:
Copy code
from livekit.agents import simulate_job, SimulateJobInfo

async def simulate_agent_job():
    job_info = SimulateJobInfo(
        room_name="simulated-room",
        participant_identity="mock-participant"
    )
    await simulate_job(job_info)
This approach is great if you want to test your agent logic without needing to connect to a real room. 3. A Few Important Notes • These simulation tools are designed just for testing and development, not for use in production rooms. • Mock participants exist only within the simulation environment and don’t connect to actual signaling servers. If you have a particular scenario in mind or need help tailoring these tools to your use case, please don’t hesitate to reach out! I’m here to support you every step of the way. Sources: src/room/Room.ts | livekit-agents/livekit/agents/worker.py | Agent dispatch | LiveKit Docs | examples/agent_dispatch.py | Authentication | LiveKit Docs