Skip to content

Commit 6ec4a42

Browse files
committed
added explicit agent dispatch example
1 parent f392454 commit 6ec4a42

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

examples/agent_dispatch.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import asyncio
2+
import os
3+
import aiohttp
4+
from livekit.protocol.room import RoomConfiguration
5+
from livekit.protocol.agent_dispatch import (
6+
RoomAgentDispatch,
7+
CreateAgentDispatchRequest,
8+
)
9+
from livekit.api import AccessToken, VideoGrants
10+
from livekit.api.agent_dispatch_service import AgentDispatchService
11+
12+
13+
room_name = "my-room"
14+
agent_name = "test-agent"
15+
16+
"""
17+
This example demonstrates how to have an agent join a room
18+
without using the automatic dispatch. In order to use this
19+
feature, you must have an agent running with `agentName` set
20+
when defining your WorkerOptions. A dispatch requests the
21+
agent to enter a specific room with optional metadata.
22+
"""
23+
24+
25+
async def create_explicit_disptach(http_session: aiohttp.ClientSession):
26+
agent_disptach_service = AgentDispatchService(
27+
session=http_session,
28+
url=os.getenv("LIVEKIT_URL"),
29+
api_key=os.getenv("LIVEKIT_API_KEY"),
30+
api_secret=os.getenv("LIVEKIT_API_SECRET"),
31+
)
32+
dispatch_request = CreateAgentDispatchRequest(
33+
agent_name=agent_name, room=room_name, metadata="my_metadata"
34+
)
35+
dispatch = await agent_disptach_service.create_dispatch(dispatch_request)
36+
print("created dispatch", dispatch)
37+
dispatches = await agent_disptach_service.list_dispatch(room_name=room_name)
38+
print(f"there are {len(dispatches)} dispatches in {room_name}")
39+
40+
41+
"""
42+
When agent name is set, the agent will no longer be automatically dispatched
43+
to new rooms. If you want that agent to be dispatched to a new room as soon as
44+
the participant connects, you can set the roomConfig with the agent
45+
definition in the access token.
46+
"""
47+
48+
49+
async def create_token_with_agent_dispatch() -> str:
50+
token = (
51+
AccessToken()
52+
.with_identity("my_participant")
53+
.with_grants(VideoGrants(room_join=True, room=room_name))
54+
.with_room_config(
55+
RoomConfiguration(
56+
agents=[
57+
RoomAgentDispatch(agent_name="test-agent", metadata="my_metadata")
58+
],
59+
),
60+
)
61+
.to_jwt()
62+
)
63+
return token
64+
65+
66+
async def main():
67+
async with aiohttp.ClientSession() as http_session:
68+
token = await create_token_with_agent_dispatch()
69+
print("created participant token", token)
70+
print("creating explicit dispatch")
71+
await create_explicit_disptach(http_session)
72+
73+
74+
asyncio.run(main())

0 commit comments

Comments
 (0)