late-helmet-58096
08/29/2025, 11:09 AMHow can I direct agents to my own rooms or access information about the agent's room in Python?
tall-airline-16756
08/29/2025, 11:09 AMtall-airline-16756
08/29/2025, 11:10 AMcreate_dispatch()
method to assign agents to rooms easily. Here’s a quick example:
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.
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:
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:
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 Docslate-helmet-58096
08/29/2025, 11:21 AMtall-airline-16756
08/29/2025, 11:22 AM{
"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:
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.golate-helmet-58096
08/29/2025, 11:48 AMtall-airline-16756
08/29/2025, 11:49 AMcreate_dispatch()
method. Here’s a quick example:
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:
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.
{
"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 Docslate-helmet-58096
08/29/2025, 11:51 AMWhen 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?
tall-airline-16756
08/29/2025, 11:52 AMlate-helmet-58096
08/29/2025, 11:53 AMtall-airline-16756
08/29/2025, 11:53 AMJobContext
. 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 Docslate-helmet-58096
08/29/2025, 6:59 PMtall-airline-16756
08/29/2025, 7:00 PMctx.room.local_participant.identity
. Here’s a quick example:
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 Docslate-helmet-58096
08/29/2025, 7:05 PMtall-airline-16756
08/29/2025, 7:06 PMagent_name
parameter in WorkerOptions
when you start the agent application. Like this:
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:
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:
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 Docslate-helmet-58096
08/29/2025, 7:10 PMtall-airline-16756
08/29/2025, 7:10 PMagent_name
in WorkerOptions
. This disables automatic dispatch and gives you full control:
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`:
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:
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.pylate-helmet-58096
08/30/2025, 10:10 AMtall-airline-16756
08/30/2025, 10:11 AMctx.shutdown()
to disconnect the agent from the room like this:
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:
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:
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