provide example on how to include an agent in the ...
# ask-ai
f
provide example on how to include an agent in the room at creation using api.CreateRoomRequest(agents=...)
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.
Thanks for reaching out! I wanted to share that it's not possible to include agents directly in the room at creation using
api.CreateRoomRequest
. But don’t worry—agents can be added in two friendly ways: either by embedding the agent dispatch within the room configuration in an access token, or by dispatching the agent explicitly after the room is created. Here’s a helpful example of how to embed agent dispatch in a participant’s access token, so the agent joins right when the participant does:
Copy code
token = api.AccessToken() \
    .with_identity("participant-identity") \
    .with_grants(api.VideoGrants(room_join=True, room="my-room")) \
    .with_room_config(
        api.RoomConfiguration(
            agents=[
                api.RoomAgentDispatch(
                    agent_name="test-agent",
                    metadata="my-metadata"
                )
            ]
        )
    ).to_jwt()
If you prefer, you can also dispatch an agent after the room has been created like this:
Copy code
dispatch = await lkapi.agent_dispatch.create_dispatch(
    api.CreateAgentDispatchRequest(
        agent_name="test-agent",
        room="my-room",
        metadata="my-metadata"
    )
)
Please feel free to ask if you'd like me to walk you through this in more detail or if there’s anything else I can help with. I’m here for you! Sources: Agent dispatch | LiveKit Docs | Authentication | LiveKit Docs | examples/agent_dispatch.py | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | examples/agent-dispatch/index.ts
f
how do I use the token to embed agent? provide example
t
To embed an agent using a token, you’ll want to generate a JWT token that includes a
RoomConfiguration
with the agent dispatch configuration. Here’s a friendly example in Python to help you get started:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

token = (
    AccessToken()
    .with_identity("my_participant")
    .with_grants(VideoGrants(room_join=True, room="my-room"))
    .with_room_config(
        RoomConfiguration(
            agents=[RoomAgentDispatch(agent_name="my-agent", metadata='{"user_id": "12345"}')]
        )
    )
    .to_jwt()
)
When you use this token to join a room, the specified agent (like "my-agent") will be dispatched automatically for you. If you’d like me to walk you through this further or provide examples in other programming languages, just let me know—I’m here to help! Sources: Web Applications & Integration Examples | livekit/livekit_composite | DeepW... | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts | examples/agent_dispatch.py
f
where do I define and initialize my-agent?
t
Hi there! Let's walk through how to define and initialize an agent (like "my-agent") together. It’s pretty straightforward, and I’m here to help every step of the way. 1. Define the Agent First, you’ll want to use the
Agent
class to set up your agent’s behavior. Here’s a simple example in Python:
Copy code
from livekit import Agent

agent = Agent(
    instructions="You are a friendly voice assistant built by LiveKit.",
    tools=[lookup_weather],
)
If you’d like to customize it a bit more, you can extend the
Agent
class like this:
Copy code
class CustomAgent(Agent):
    def __init__(self):
        super().__init__(instructions="You are a helpful assistant.")
2. Initialize the Agent in a Session Next, create an
AgentSession
to handle real-time interactions. Here’s how you can set it up:
Copy code
from livekit import AgentSession, silero, deepgram, openai, elevenlabs

session = AgentSession(
    vad=silero.VAD.load(),
    stt=deepgram.STT(model="nova-3"),
    llm=openai.LLM(model="gpt-4o-mini"),
    tts=elevenlabs.TTS(),
)
Then, start the session by connecting your agent to a room like this:
Copy code
await session.start(agent=agent, room="my-room")
3. Deploy the Agent When you’re ready to run your agent server in development mode, just use:
Copy code
python myagent.py dev
And when it’s time to deploy, the LiveKit CLI makes it easy:
Copy code
lk agent deploy
If you’d like, I’m more than happy to provide more details or examples in another programming language. Just let me know! Sources: .cursor/rules/agent-core.mdc | cmd/lk/agent.go | livekit-plugins/livekit-plugins-hedra/livekit/plugins/hedra/avatar.py | Workflows | LiveKit Docs
f
so, how do I connect the token with agent session?
t
Hi there! To connect a token with an agent session, you’ll want to generate a participant token that includes the agent dispatch configuration. Let me walk you through the steps: 1. Generate a Token with Agent Dispatch Make sure to include the agent in the
RoomConfiguration
when you generate the token. Here’s an example in Python:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

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()
)
When you use this token to join the room, the agent you specified (like "test-agent") will be dispatched automatically. 2. Use the Token in the Client Next, pass this token to your client SDK to connect to the room. Here’s how you can do it in Swift:
Copy code
let session = Session.withAgent(
    "test-agent",
    tokenSource: tokenSource, // Provides the JWT
    options: SessionOptions(agentConnectTimeout: 10.0)
)
await session.start()
This way, the agent will join the room as soon as the participant connects. 3. Agent Joins and Handles Session The agent worker will listen for dispatch events and join the room automatically. Here’s a quick example in Python:
Copy code
async def entrypoint(ctx: JobContext):
    await ctx.connect()
    await session.start(agent=agent, room=ctx.room)
If you have any questions or need me to clarify anything, please don’t hesitate to ask—I’m here to help! Sources: Web and mobile frontends | LiveKit Docs | Agent dispatch | LiveKit Docs | Sources/LiveKit/Agent/Session.swift | livekit-plugins/livekit-plugins-simli/livekit/plugins/simli/avatar.py
f
provide 2. Use the Token in the Client in python code
t
I'd love to help you get started with using the token in the Python client to connect to a room with an agent. Here's a step-by-step guide to make it as smooth as possible for you: 1. Generate the Token First, make sure you have a function that generates the token with agent dispatch included. Here's an example:
Copy code
from livekit.api import AccessToken, RoomAgentDispatch, RoomConfiguration, VideoGrants

def generate_token_with_agent():
    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="my_metadata"
                    )
                ]
            )
        )
    )
    return token.to_jwt()
2. Connect to the Room Next, you can use the
livekit
Python package to connect to the room like this:
Copy code
import asyncio
from livekit import rtc

async def connect_to_room():
    # Create a Room instance
    room = rtc.Room()

    # Set up event listeners (optional)
    @room.on("participant_connected")
    def on_participant_connected(participant):
        print(f"Participant connected: {participant.identity}")

    @room.on("connected")
    def on_connected():
        print("Connected to the room!")

    @room.on("disconnected")
    def on_disconnected():
        print("Disconnected from the room")

    # Connect to the room using the URL and token
    await room.connect(
        url="wss://your-livekit-server-url",  # e.g., wss://my-project.livekit.cloud
        token=generate_token_with_agent()
    )

    # Keep the connection alive
    await asyncio.sleep(3600)  # Keep alive for 1 hour

if __name__ == "__main__":
    asyncio.run(connect_to_room())
Just a quick note: be sure to replace
"wss://your-livekit-server-url"
with the actual WebSocket URL of your LiveKit server. Once you do that, the agent will automatically join the room as soon as the participant connects with the token. If you have any questions or need a hand with anything else, please don’t hesitate to reach out. I’m here to help! Sources: Agent dispatch | LiveKit Docs | examples/room_example.py | Agent-assisted warm transfer | LiveKit docs | agent.py | Authentication | LiveKit Docs