how to prevent the agent from joining directly ? ...
# ask-ai
p
how to prevent the agent from joining directly ? i'm using python version
t
Thanks for reaching out, Yassine. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! To help you prevent an agent from joining a room directly in LiveKit using the Python SDK, you can set up the agent with an
agent_name
in the
WorkerOptions
. This is a great way to disable automatic dispatch, so the agent won’t join rooms automatically when a participant arrives. Instead, you have full control and can dispatch the agent explicitly to a room whenever you choose. Let me walk you through the steps: 1. Disable Automatic Dispatch: Start by defining the agent with an
agent_name
in
WorkerOptions
. Here’s an example:
Copy code
# Define worker with agent_name (disables automatic dispatch)
worker_options = WorkerOptions(
    worker_name="my-worker",
    agent_name="test-agent"  # This disables automatic dispatch
)
1. Use Explicit Dispatch: When you want the agent to join, dispatch it explicitly using one of these methods: • Via API: You can use the
AgentDispatchService.create_dispatch()
method to specify the agent name and the target room like this:
Copy code
from livekit import api

lkapi = api.LiveKitAPI()

dispatch = await lkapi.agent_dispatch.create_dispatch(
    api.CreateAgentDispatchRequest(
        agent_name="test-agent",
        room="my-room",
        metadata="my_metadata"
    )
)
• Via Participant Token: Alternatively, include the agent in the
RoomConfiguration
of a participant’s access token, like so:
Copy code
token = (
    api.AccessToken()
    .with_identity("my_participant")
    .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()
)
Using
agent_name
this way gives you complete control over when and how your agent joins a room, so you can avoid any unintended or automatic entries. If you have any questions or want to explore this further, feel free to ask—I’m here to help! Sources: Agent dispatch | LiveKit Docs | livekit-api/livekit/api/agent_dispatch_service.py | Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki
Thanks for sharing that you're using the latest Python agent and Next.js UI! To make sure I fully understand your situation, could you please clarify a couple of things? • Are you hoping to stop the agent from joining automatically in every case, or just in certain situations? • Are you using any particular configuration or token generation method in your Next.js backend to manage room access? Knowing this will really help me guide you in the best way possible for your setup. Looking forward to your reply! Sources: Server-Side SDKs & Authentication | livekit/livekit_composite | DeepWiki | app/api/connection-details/route.ts | Agent dispatch | LiveKit Docs | examples/agent_dispatch.py
p
i'm using nextjs how to create the api to call the agent
t
I'd be happy to guide you through creating an API in Next.js to call an agent in LiveKit. Just follow these steps, and feel free to ask if anything is unclear! 1. Set Up Environment Variables: Start by defining the following in your
.env.local
file:
Copy code
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
LIVEKIT_URL=your_livekit_server_url
1. Create an API Route: Next, add a file at
app/api/connection-details/route.ts
to generate connection details, including a token for agent dispatch. Here’s an example to help you get started:
Copy code
import { NextResponse } from 'next/server';
import { AccessToken, type AccessTokenOptions, type VideoGrant } from 'livekit-server-sdk';
import { RoomConfiguration } from '@livekit/protocol';

const API_KEY = process.env.LIVEKIT_API_KEY;
const API_SECRET = process.env.LIVEKIT_API_SECRET;
const LIVEKIT_URL = process.env.LIVEKIT_URL;

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const agentName = body?.room_config?.agents?.[0]?.agent_name;

    const participantIdentity = `user_${Math.random()}`;
    const roomName = `room_${Math.random()}`;

    const token = new AccessToken(API_KEY, API_SECRET, { identity: participantIdentity });
    token.addGrant({ room: roomName, roomJoin: true });

    if (agentName) {
      token.roomConfig = new RoomConfiguration({
        agents: [{ agentName }],
      });
    }

    return NextResponse.json({
      serverUrl: LIVEKIT_URL,
      roomName,
      participantToken: token.toJwt(),
    });
  } catch (error) {
    return new NextResponse(error.message, { status: 500 });
  }
}
1. Call the API from Your Frontend: To get the connection details, send a POST request with the agent name like this:
Copy code
const response = await fetch('/api/connection-details', {
  method: 'POST',
  body: JSON.stringify({
    room_config: {
      agents: [{ agent_name: 'my-agent' }]
    }
  }),
});

const data = await response.json();
console.log('Connect to room:', data.roomName, 'with token:', data.participantToken);
1. Connect to LiveKit Room: Finally, use the
participantToken
and
roomName
to connect your client with the LiveKit SDK. This approach makes sure the agent is dispatched only when you want it to be. If you have any questions or need more help, just let me know — I'm here for you! Sources: Agents telephony integration | LiveKit Docs | app/api/connection-details/route.ts | Next.js quickstart | LiveKit docs