How to share a token to frontend with which user w...
# ask-ai
c
How to share a token to frontend with which user will join the room and then what's the flow of agent dispatch in this case? will the agent join the room itself after the participant joins or we have to use Dispatch via API.
t
Thanks for reaching out, Arjun. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here’s a friendly guide to sharing a token with the frontend and managing agent dispatch in LiveKit: 1. Generate an Access Token: Start by creating a token on your backend with the right permissions (like
roomJoin
). If you want an agent to be dispatched automatically when someone joins, include a
RoomConfiguration
too. 2. Send Token to Frontend: Next, securely send that token to your frontend through an API endpoint. Make sure it contains the server URL, room name, and participant token. 3. Frontend Connection: On the frontend, use the LiveKit client SDK to connect to the room using the token you just sent. 4. Agent Dispatch: If your token has a
RoomConfiguration
with agent info, LiveKit will handle dispatching the agent(s) automatically when the participant joins. Or, if you prefer, you can dispatch agents manually using the API. If you want me to walk you through any of these steps with more details or examples, just give me a shout—I’m here to help! Sources: Web and mobile frontends | LiveKit Docs | Authentication | LiveKit Docs | Agent dispatch | LiveKit Docs | packages/livekit-server-sdk/src/AgentDispatchClient.ts | Next.js quickstart | LiveKit Docs
c
I see that for explicit dispatch we should set the agent name in the worker options, is it mandatory that the agent name which we set while creating the token must be same in the worker options?
Copy code
api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret) \
        .with_identity(request.user_id) \
        .with_name(request.target_persona) \
        .with_grants(api.VideoGrants(
            room_join=True,
            room=room_name,
        )).with_room_config(
            api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(agent_name="test-agent", metadata=meta)
                ],
            ),
        )
t
Just a heads-up: the agent name you put in
RoomAgentDispatch
really needs to match the one in
WorkerOptions
for everything to work smoothly. If they don’t line up, the agent won’t get assigned to the room, and the dispatch won’t go through. Here’s a quick example to make it clearer: • In
WorkerOptions
, you’d set
agent_name = "test-agent"
when you’re defining your agent worker. • Then, in
RoomAgentDispatch
, use that exact same name:
agent_name="test-agent"
when you’re setting up the dispatch rule or token configuration. This way, you’re making sure the right agent gets sent to the room just like you planned. If anything’s still fuzzy or you want to dive deeper, just let me know—I’m here to help! Sources: SIP troubleshooting guide | LiveKit Docs | Agent dispatch | LiveKit Docs | Dispatching agents | LiveKit Docs | packages/livekit-server-sdk/src/AgentDispatchClient.ts
c
so this means, our agent name will be static and for each room we can't assign different agent names?
t
Hey there! You can easily assign different agent names to each room in LiveKit using a few straightforward dispatch methods. Here’s a quick rundown: • API-based Dispatch: Simply use the API to send a named agent to a specific room on the fly. Don’t worry if the room doesn’t exist yet—it’ll be created automatically. • Participant Token Configuration: You can add the agent’s name right into the participant’s token setup. This way, the assignment can change dynamically depending on the user or session. • SIP Dispatch Rules: If you’re working with telephony, you can set up SIP dispatch rules to decide which agent gets assigned to rooms created from incoming calls. These options give you great flexibility to control who’s assigned where, making your app super dynamic. If you want, I’d be happy to share more details or examples—just let me know! Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name
c
After my agent and user are done talking, I want to export audio and transcription. How can I do that in the most simplest way.
t
Here’s how you can export audio and transcription after a session in LiveKit: 1. Export Audio: Try out the Room Composite Egress feature to record your session. You can set it up to save audio-only files (like OGG format) directly to cloud storage options such as Amazon S3, Google Cloud Storage, or Azure Blob Storage. The recording kicks off as soon as the session starts and gets uploaded automatically once it ends. 2. Export Transcription: There are a couple of ways to grab the transcription: ◦ Use
session.history
to pull the full conversation history and save it as a JSON file right after the session ends, using a shutdown callback. ◦ Or, listen to real-time transcription events (like
conversation_item_added
) to log or stream transcripts as the session happens. If you want, I’m happy to share some detailed examples or help you get these features set up! Sources: Session recording and transcripts | LiveKit Docs
c
• API-based Dispatch: Simply use the API to send a named agent to a specific room on the fly. Don’t worry if the room doesn’t exist yet—it’ll be created automatically. If i use this, how will the frontend recieve the token with which usercan join the room
t
Hey there! If you're using API-based agent dispatch and want to provide a token to the frontend, here’s a simple way to do it: 1. Generate a Token on the Backend: Start by creating a participant access token with a
RoomConfiguration
that includes the agent dispatch details, like the
agentName
and any optional metadata you might want to add. 2. Expose an API Endpoint: Next, set up a backend endpoint that can generate and send this token to your frontend. Make sure this endpoint securely signs the token using your LiveKit API key and secret. 3. Frontend Requests the Token: On the frontend side, simply make a request to that backend endpoint to grab the token—using something like
fetch
works great here. 4. Connect to LiveKit: Finally, use the token you received with the LiveKit client SDK to connect the participant to the room. The agent will be dispatched automatically as soon as the connection happens. This method keeps your token delivery secure and makes agent dispatch smooth and hassle-free. If you want, I’d be happy to share some code examples or explain anything in more detail—just let me know! Sources: Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts | src/pages/api/token.ts | client/web/src/app/api/connection-details/route.ts | Generating tokens | LiveKit Docs
c
If we are using API-based Dispatch strategy, is there any need to generate a token using:
Copy code
api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret) \
        .with_identity(request.user_id) \
        .with_name(request.target_persona) \
        .with_grants(api.VideoGrants(
            room_join=True,
            room=room_name,
        )).with_room_config(
            api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(agent_name="test-agent", metadata=meta)
                ],
            ),
        )
If not, then how will the frontend know that user will enter which room?
t
When using API-based agent dispatch, you don’t always have to generate a token. Here’s a quick rundown to help you out: • Direct API Dispatch: You can use the
AgentDispatchService
to send an agent straight to a room without needing a token. This works great if you’re managing things on the backend or want to dispatch agents proactively. • Token-Based Dispatch: If you want the agent to join automatically as soon as a participant connects, you’ll want to generate a token with a
RoomConfiguration
that includes the agent dispatch details. This is perfect for setups where the user kicks things off and the agent should jump in right away. Pick the approach that fits your needs best. And if you’d like a hand figuring it out or getting it set up, just let me know what you’re aiming for—I’m here to help! Sources: Agent dispatch | LiveKit Docs | Web and mobile frontends | LiveKit Docs | examples/agent-dispatch/index.ts | examples/agent_dispatch.py | app/api/connection-details/route.ts
c
If we are using API-based Dispatch strategy, is there any need to generate a token using:
Copy code
api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret) \
        .with_identity(request.user_id) \
        .with_name(request.target_persona) \
        .with_grants(api.VideoGrants(
            room_join=True,
            room=room_name,
        )).with_room_config(
            api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(agent_name="test-agent", metadata=meta)
                ],
            ),
        )
If not, then how will the frontend know that user will enter which room?
t
Hey there! If you’re using the API-based Dispatch strategy, generating a token with the code snippet isn’t absolutely required to dispatch the agent. But don’t worry—you’ll still need to create a token for the user so they can join the room. This token will include the room name and the permissions needed (like
room_join=True
). Here’s a simple way the frontend can figure out which room the user will enter: 1. Backend Determines Room Name: The backend picks or creates the room name when it sets up the dispatch request or gets the user’s token ready. 2. Send Room Details to Frontend: Along with the user’s token, the backend can send the room name and server URL to the frontend through an API response. 3. Frontend Connects to Room: The frontend then uses the room name and token it received to connect to the LiveKit server. So, even if you’re working with API-based dispatch, the user’s token is still super important for joining the room. If you want me to walk you through it more or share some examples, just let me know—I’m here to help!
c
My agent isn't joining automatically in dev mode: I created a token using:
Copy code
token = api.AccessToken(settings.livekit_api_key, settings.livekit_api_secret) \
        .with_identity(request.user_id) \
        .with_name(request.target_persona) \
        .with_grants(api.VideoGrants(
            room_join=True,
            room=room_name,
        )).with_room_config(
            api.RoomConfiguration(
                agents=[
                    api.RoomAgentDispatch(agent_name="test-agent", metadata=meta)
                ],
            ),
        )
now, using the token and my livekit url, I pasted in hosted deployments manual mode and tried to enter a room. My assumption is that my agent job should auto dispatch the agent, i am running it in debug mode. It also ran fine for 1-2 times but now when i enter a room with new token, no new agent is being dispatched.
Copy code
if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
            agent_name="test-agent"
        ),
    )
t
Hey there! The reason this issue pops up is that when you set an
agent_name
in
WorkerOptions
, it actually turns off automatic dispatch on purpose. So, if you’ve defined
agent_name
, you’ll need to dispatch the agent explicitly either: • By making an API call using
AgentDispatchService
. • Or by using a participant token that includes
RoomConfiguration.agents
with a
RoomAgentDispatch
entry. To make sure your agent gets dispatched as soon as a participant connects, just double-check that your participant token has the agent configuration like this:
Copy code
at.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName: 'test-agent',
      metadata: '{"mydata": "myvalue"}',
    }),
  ],
});
If you’d prefer things to happen automatically without having to manage it yourself, simply remove the
agent_name
from
WorkerOptions
. And hey, if you have any questions or want a hand with this, just let me know—I’m here to help! Sources: Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs | examples/agent-dispatch/index.ts | examples/agent_dispatch.py
c
I am using the same config shared by you and using a participant token, but after that as well it's not dispatching
t
Hey there! If your agent isn’t dispatching even though everything seems set up correctly, no worries—let’s walk through some troubleshooting steps together: 1. Make Sure the Agent is Running: Double-check that your agent is actually running and that the
agent_name
in
WorkerOptions
is set correctly. Without this, the agent won’t be able to dispatch. 2. Match Those Agent Names: Take a look at the
agent_name
in your participant token’s
RoomAgentDispatch
and make sure it exactly matches the
agent_name
in the agent’s
WorkerOptions
. Even small differences can cause issues. 3. Check the Token Setup: Make sure your participant token has a properly formatted
RoomConfiguration
that includes the
agents
field with the right agent name and any optional metadata. 4. Confirm Room and Agent Are Ready: Verify that the room was created successfully and that your agent worker is idle and ready to receive dispatch requests. You can use the LiveKit CLI or API to peek at active dispatches. 5. Peek at the Logs: Take a look at both the agent logs and server logs for any errors or warnings related to dispatch or room creation—they often give great clues. 6. Check Version Compatibility: Make sure all your SDKs and services are running compatible versions to avoid any unexpected hiccups. If you’re still stuck after trying these, just give me a shout! We can dig into specific logs or configurations together and get this sorted out. Sources: Agent dispatch | LiveKit Docs | SIP troubleshooting guide | LiveKit Docs | examples/agent-dispatch/index.ts | Authentication | LiveKit Docs | Getting Help | livekit/livekit_composite | DeepWiki
c
need more help
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
c
how to use LiveKit CLI or API to peek at active dispatches.