```How can I direct agents to my own rooms or acce...
# ask-ai
l
Copy code
How can I direct agents to my own rooms or access information about the agent's room in Python?
t
Thanks for reaching out, biberim45. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
If you want to guide agents to specific rooms or check out agent room details in Python using LiveKit, here are some handy ways to do it: • Directing Agents to Specific Rooms: You can use the
create_dispatch()
method to assign agents to rooms easily. Here’s a quick example:
Copy code
import asyncio
from livekit import api

async def create_explicit_dispatch():
    lkapi = api.LiveKitAPI()
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="test-agent",
            room="my-room",
            metadata='{"user_id": "12345"}'  # JSON works great for structured info
        )
    )
    print("Created dispatch:", dispatch)
    await lkapi.aclose()

asyncio.run(create_explicit_dispatch())
Dispatch via Participant Token: Another neat way is to embed
RoomAgentDispatch
inside a participant’s access token, so the agent gets dispatched as soon as the participant joins.
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

def create_token_with_agent_dispatch():
    token = (
        AccessToken()
        .with_identity("my_participant")
        .with_grants(VideoGrants(room_join=True, room="my-room"))
        .with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name="test-agent",
                        metadata='{"user_id": "12345"}'
                    )
                ]
            )
        )
        .to_jwt()
    )
    return token
Accessing Agent Room Information: To see all agent dispatches in a room, just use
list_dispatch()
like this:
Copy code
dispatches = await lkapi.agent_dispatch.list_dispatch(room_name="my-room")
for dispatch in dispatches:
    print(f"Agent: {dispatch.agent_name}, Room: {dispatch.room}, Metadata: {dispatch.metadata}, State: {dispatch.state}")
Retrieve Dispatch by ID: If you want to grab a specific dispatch by its ID, here’s how you can do that:
Copy code
dispatch = await lkapi.agent_dispatch.get_dispatch(dispatch_id="disp_abc123", room_name="my-room")
if dispatch:
    print(f"Found dispatch: {dispatch.agent_name}, Metadata: {dispatch.metadata}")
Feel free to reach out if you want me to walk you through any of these or if you have other questions! Sources: README.md | mcp/server.py | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs
l
how can organizate my agents and rooms with my own backends
t
To help you organize agents and rooms with your own backend in LiveKit, here are some friendly approaches you can try out: • Dispatching Agents to Rooms: You can set up SIP dispatch rules to automatically create rooms and assign agents. For instance, you might configure a rule that names rooms based on caller info and assigns specific agents like this:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "name": "My dispatch rule",
    "roomConfig": {
      "agents": [
        {
          "agentName": "inbound-agent",
          "metadata": "job dispatch metadata"
        }
      ]
    }
  }
}
Using Custom Backends: You can build agents using backend SDKs like Python, Rust, or Node.js. These agents can handle real-time media and interact with rooms programmatically. Here’s a quick example in Python:
Copy code
from livekit import rtc

async def main():
    room = rtc.Room()
    # Connect to a room and process media
Multi-Agent Workflows: Think about workflows where agents can hand off tasks to others while keeping all the context intact. For example, a greeter agent could transfer a session smoothly to a reservation or billing agent. • Namespaces and Job Types: Organizing agents by namespaces and job types can help you control dispatch behavior and make sure each agent specializes where they’re best. If you’d like, I can share a specific example tailored just for your use case—whether it’s customer support, AI moderation, or something else. Just let me know! Sources: An open source stack for real-time multimodal AI | Agents Overview | LiveKit Docs | complex-agents/medical_office_triage/triage.py | examples/voice_agents/restaurant_agent.py | test/agent_test.go
l
session = AgentSession() await session.start( agent=LenaAgent(), room=ctx.room, room_input_options=RoomInputOptions(video_enabled=False), room_output_options=RoomOutputOptions(transcription_enabled=True), ) if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="LenaAgent")) ı example this code ı am starting random agent how can i route my selected rooms how can i organizate agents and rooms?
t
Hey there! If you want to route specific rooms to agents and keep everything organized in LiveKit using Python, here are some friendly ways to do it: • Explicit Dispatch via API: You can easily assign agents to particular rooms by using the
create_dispatch()
method. Here’s a quick example:
Copy code
import asyncio
from livekit import api

async def create_explicit_dispatch():
    lkapi = api.LiveKitAPI("<wss://your-livekit-server>", "API_KEY", "API_SECRET")
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="test-agent",
            room="my-room",
            metadata='{"user_id": "12345"}'  # Optional structured data
        )
    )
    print("Created dispatch:", dispatch)
    await lkapi.aclose()

asyncio.run(create_explicit_dispatch())
Token-based Dispatch: Another neat way is to dispatch agents automatically when a participant joins a room by embedding
RoomAgentDispatch
right into their access token:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

def create_token_with_agent_dispatch(room_name: str, agent_name: str) -> str:
    token = (
        AccessToken("API_KEY", "API_SECRET")
        .with_identity("participant-identity")
        .with_grants(VideoGrants(room_join=True, room=room_name))
        .with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name=agent_name,
                        metadata='{"user_id": "12345"}'
                    )
                ]
            )
        )
        .to_jwt()
    )
    return token
SIP Dispatch Rules: If you’re handling inbound phone calls, you can automate assigning agents by setting up SIP dispatch rules that create rooms and assign agents dynamically.
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "name": "Inbound Call Dispatch",
    "roomConfig": {
      "agents": [
        {
          "agentName": "inbound-agent",
          "metadata": "{\"caller_id\": \"${SIP_CALLER_ID}\"}"
        }
      ]
    }
  }
}
To keep your agents and rooms nicely organized, here are some tips: • Give each agent a unique
agent_name
so you can easily tell them apart (like support-bot, moderation-agent, etc.). • Use the
metadata
field to pass along useful info such as user IDs or room purposes — this data is accessible in the agent’s
JobContext
. • Manage rooms smoothly by using the
RoomServiceClient
or
LiveKitAPI.room
methods. If you want me to walk you through any part of this or need some tailored examples, just let me know — I’m here to help! Sources: complex-agents/ivr-agent/flask_livekit/extension.py | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | SIP dispatch rule | LiveKit Docs
l
async def entrypoint(ctx: JobContext): session = AgentSession() await session.start( agent=LenaAgent(), room=ctx.room, room_input_options=RoomInputOptions(video_enabled=False), room_output_options=RoomOutputOptions(transcription_enabled=True), ) if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="LenaAgent"))
Copy code
When I run an agent like this, how do I know which room the agent will join and how do I get the room's token?
t
Hey there! Just wanted to check—are you using explicit dispatch, where agents are assigned to specific rooms manually, or automatic dispatch, where agents get assigned to new rooms on their own? Knowing this will help me guide you better on how to find the room and grab the token. Thanks!
l
automatic dispatch now ı am only use this code:async def entrypoint(ctx: JobContext): session = AgentSession() await session.start( agent=LenaAgent(), room=ctx.room, room_input_options=RoomInputOptions(video_enabled=False), room_output_options=RoomOutputOptions(transcription_enabled=True), ) if name == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="LenaAgent"))
t
When it comes to automatic dispatch, agents get assigned to all new rooms automatically, but there isn’t an external API that tells you exactly which room an agent joined. Don’t worry though—the agent can still find this info internally while running: • Find Out the Room: The room name is tucked away in the agent’s
JobContext
. You can grab it from the job metadata or connection context during execution. • Get the Room Token: The room token lives inside the agent too, accessible via
JobContext.info.token
. This token is created by the server to authenticate the agent into the room. If you’re looking for more clarity and control over which rooms agents join, you might want to try explicit dispatch methods where you directly specify the room name during dispatch. And hey, if you want a hand setting this up, just let me know—I’m here to help! Sources: examples/agent_dispatch.py | examples/agent-dispatch/index.ts | client/web/src/app/api/connection-details/route.ts | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs
l
async def start_agent(): session = AgentSession() print(f"Starting agent session for agent ID: {agent_id}") await session.start( agent=DynamicAgent(agent_model=agent), room_input_options=RoomInputOptions(video_enabled=False), room_output_options=RoomOutputOptions(transcription_enabled=True), ) # asyncio event loop başlat import asyncio asyncio.run(start_agent()) how can i get agent id/name this code
t
Hey there! If you want to grab the agent's ID and name right when an agent session starts in LiveKit using Python, here’s a simple way to do it: • Agent Identity (ID): Once you’ve connected to the room, you can easily get the agent’s identity with
ctx.room.local_participant.identity
. Here’s a quick example:
Copy code
async def entrypoint(ctx: JobContext):
    # Connect the agent to the room
    await ctx.connect()

    # Retrieve agent's identity after connection
    agent_id = ctx.room.local_participant.identity
    print(f"Agent ID: {agent_id}")
Agent Name (Display Name): The display name is usually set when you initialize the agent (like with the
name
parameter in
request_fnc
). However, there isn’t a built-in way to pull it during the session. If you need it later, a good idea is to save the name in your agent’s state when you set things up or pass it along through job metadata. Feel free to reach out if you want me to walk you through more examples or if there’s anything else you’re curious about! Sources: Beyond Presence virtual avatar integration guide | LiveKit Docs | External data and RAG | LiveKit Docs | examples/avatar_agents/bey/agent_worker.py | Inside a session | LiveKit Docs | Worker options | LiveKit Docs
l
async def start_agent(): session = AgentSession() print(f"Starting agent session for agent ID: {agent_id}") await session.start( agent=DynamicAgent(agent_model=agent), room_input_options=RoomInputOptions(video_enabled=False), room_output_options=RoomOutputOptions(transcription_enabled=True), ) # asyncio event loop başlat import asyncio asyncio.run(start_agent()) how can i set agent name manuelly on this code
t
Hey there! If you want to manually set the agent's name in your code, it’s best to do it before the session kicks off. Here’s a simple way to do it: • Set Agent Name at Worker Level: Just use the
agent_name
parameter in
WorkerOptions
when you start the agent application. Like this:
Copy code
if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="my-agent-name"  # This sets the agent worker name
        )
    )
Set Display Name in Room: You can also set the agent’s display name (what everyone sees in the room) by using the
name
parameter inside
req.accept()
within your
request_fnc
function:
Copy code
async def request_fnc(req: JobRequest):
    await req.accept(
        name="Friendly AI Assistant",  # Display name in the room
        identity="ai-agent-01"
    )
Update Name After Join: And if you ever want to change the agent’s name after joining the room, you can easily do that with
set_name()
like this:
Copy code
await ctx.room.local_participant.set_name("Updated Agent Name")
Feel free to reach out if you want me to walk you through this or if you need more examples. I’m here to help! Sources: livekit-rtc/livekit/rtc/participant.py | Agent dispatch | LiveKit Docs | Worker options | LiveKit Docs | Accepting incoming calls | LiveKit Docs | Dispatching agents | LiveKit Docs
l
my agent how join the custom rooms?
t
Hey there! If you want your agent to join custom rooms in LiveKit, you can use explicit dispatch methods. Here’s a friendly guide to help you out: • Register the Agent: Just set the
agent_name
in
WorkerOptions
. This disables automatic dispatch and gives you full control:
Copy code
from livekit.agents import WorkerOptions, cli

opts = WorkerOptions(
    worker_type="room",
    agent_name="test-agent",  # Make sure this matches the name you’ll use in dispatch
    entrypoint_fnc=entrypoint  # Your agent's entrypoint function
)
Dispatch via API: You can assign the agent to a specific room programmatically using `AgentDispatchService`:
Copy code
import asyncio
from livekit import api

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

    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="test-agent",
            room="my-room",
            metadata='{"user_id": "12345"}'  # Optional metadata you can add
        )
    )
    print("Agent dispatched:", dispatch)

asyncio.run(dispatch_agent())
Dispatch via Participant Token: Another cool way is to configure a participant’s access token so the agent gets dispatched as soon as they join the room:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

def create_token_with_agent_dispatch(room_name: str, participant_identity: str) -> str:
    token = (
        AccessToken()
        .with_identity(participant_identity)
        .with_grants(VideoGrants(room_join=True, room=room_name))
        .with_room_config(
            RoomConfiguration(
                agents=[
                    RoomAgentDispatch(
                        agent_name="test-agent",
                        metadata='{"user_id": "12345"}'
                    )
                ]
            )
        )
        .to_jwt()
    )
    return token
If you have any questions or want to chat more about these methods, just let me know—I’m here to help! Sources: Agent dispatch | LiveKit Docs | livekit-api/livekit/api/agent_dispatch_service.py
l
when room is closed how can i close agent
t
Hey there! Just a quick heads-up: when a room closes in LiveKit, agents get disconnected automatically. But if you want a bit more control over how and when agents are disconnected, here are some handy options for you: • Disconnect the Agent: You can use
ctx.shutdown()
to disconnect the agent from the room like this:
Copy code
async def entrypoint(ctx: JobContext):
    # Do your agent tasks here
    ...
    # Then disconnect the agent
    ctx.shutdown(reason="Session ended")
Close the Room: If you want to close the whole room for everyone, just use the
delete_room
API like this:
Copy code
from livekit import api

async def entrypoint(ctx: JobContext):
    api_client = api.LiveKitAPI(
        os.getenv("LIVEKIT_URL"),
        os.getenv("LIVEKIT_API_KEY"),
        os.getenv("LIVEKIT_API_SECRET"),
    )
    await api_client.room.delete_room(
        api.DeleteRoomRequest(room=ctx.job.room.name)
    )
Close the Agent Session: If you’re working with
AgentSession
, just call
session.aclose()
to wrap things up:
Copy code
class MyAgent(Agent):
    @function_tool
    async def end_session(self):
        await self.session.aclose()
Automatic Closure: By default,
AgentSession
closes itself when the last participant leaves. But if you want to change that, you can set
RoomInputOptions(close_on_disconnect=False)
. Hope this helps! Feel free to reach out if you want to chat more about these options or need a hand with anything else. Sources: Agents telephony integration | LiveKit Docs | Anatomy of an Agent | LiveKit Docs | Job lifecycle | LiveKit Docs | Events and error handling | LiveKit Docs | basics/exit_message.py