How to specify which livekit agent should join the...
# ask-ai
s
How to specify which livekit agent should join the room?
t
Thanks for reaching out, Anuj. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you specify which LiveKit agent should join a room! You have a couple of friendly options to do this: 1. Using the AgentDispatchService API: This lets you programmatically send a specific agent to a room. Here’s a simple example in Node.js:
Copy code
const agentDispatchClient = new AgentDispatchClient(process.env.LIVEKIT_URL);
const dispatch = await agentDispatchClient.createDispatch(
  'my-room',           // room name
  'test-agent',        // agent name
  { metadata: '{"mydata": "myvalue"}' }
);
1. Dispatch on Participant Connection: You can also set up a participant’s access token so agents are dispatched automatically when they join the room. Here’s how you might do that in Node.js:
Copy code
const at = new AccessToken();
at.identity = 'my-participant';
at.addGrant({ roomJoin: true, room: 'my-room' });
at.roomConfig = new RoomConfiguration({
  agents: [
    new RoomAgentDispatch({
      agentName: 'test-agent',
      metadata: '{"mydata": "myvalue"}'
    }),
  ],
});
Just make sure your agent is registered with an
agent_name
in the
WorkerOptions
so you have full control. If you have any questions or want to walk through this together, I’m here to help! Sources: packages/livekit-server-sdk/src/AgentDispatchClient.ts | examples/agent_dispatch.py | Authentication | LiveKit Docs | examples/avatar_agents/bey/README.md | Agent dispatch | LiveKit Docs
s
i'm using python sdk, 1. how to configure the agent that should join the call 2. how to get joining details that can be send to client side
t
I'd love to guide you through how to configure an agent to join a call using the Python SDK and share the joining details for the client side. Here's a step-by-step approach: • 1. Configure the Agent: First, you'll want to set up explicit agent dispatch by defining the
agent_name
in
WorkerOptions
. Here's an example to illustrate:
Copy code
class OutboundCaller(Agent):
    def __init__(self, name: str, appointment_time: str, dial_info: dict[str, Any]):
        super().__init__(instructions=f"Confirm appointment with {name} at {appointment_time}")
        self.dial_info = dial_info

async def entrypoint(ctx: JobContext):
    dial_info = json.loads(ctx.job.metadata)
    agent = OutboundCaller(
        name="Jayden",
        appointment_time="next Tuesday at 3pm",
        dial_info=dial_info,
    )
    session = AgentSession(
        stt=deepgram.STT(),
        tts=cartesia.TTS(),
        llm=openai.LLM(model="gpt-4o"),
        vad=silero.VAD.load(),
        turn_detection=EnglishModel()
    )
    await session.start(
        agent=agent,
        room=ctx.room,
        room_input_options=RoomInputOptions(noise_cancellation=noise_cancellation.BVCTelephony()),
    )

if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            agent_name="outbound-caller",
        )
    )
• 2. Dispatch the Agent: Next, you can dispatch the agent to a specific room using the LiveKit CLI or API like this:
Copy code
lk dispatch create \
  --new-room \
  --agent-name outbound-caller \
  --metadata '{"phone_number": "+1234567890", "transfer_to": "+9876543210"}'
• 3. Generate Client-Side Joining Details: To help your client connect, you’ll want to generate a connection token using the
livekit-server-sdk
. Here’s a simple function to do that:
Copy code
from livekit import api

def generate_token(room_name: str, identity: str):
    token = (
        api.AccessToken(api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET)
        .with_identity(identity)
        .with_name("Client User")
        .with_grants(
            api.VideoGrants(
                room_join=True,
                room=room_name,
                can_publish=True,
                can_subscribe=True,
                can_publish_data=True
            )
        )
        .to_jwt()
    )
    return {
        "serverUrl": LIVEKIT_URL,
        "roomName": room_name,
        "participantToken": token,
        "participantIdentity": identity
    }
• 4. Client-Side Connection: Finally, on the client side, you can use the LiveKit Client SDK to connect like this:
Copy code
import { Room } from 'livekit-client';

const room = new Room();
await room.connect(
  connectionDetails.serverUrl,
  connectionDetails.participantToken
);
If any part of this feels unclear or if you’d like me to walk you through any step in more detail, please don’t hesitate to ask. I’m here to help! Sources: README.md | auth.py | complex-agents/shopify-voice-shopper/README.md | Generating tokens | LiveKit Docs | Agent dispatch | LiveKit Docs
s
can the room creation happen via the sdk before token generation?
t
Absolutely, you can create a room using the Python SDK even before generating a token. It’s quite straightforward with the
RoomService
client. Here’s a simple example to help you get started:
Copy code
from livekit import api
import asyncio

async def main():
    lkapi = api.LiveKitAPI("https://my-project.livekit.cloud")
    room_info = await lkapi.room.create_room(
        api.CreateRoomRequest(name="my-room"),
    )
    print(room_info)
    await lkapi.aclose()

asyncio.run(main())
If you prefer, there’s also the
RoomServiceClient
approach you can use:
Copy code
client = api.RoomServiceClient(self.host, self.api_key, self.api_secret)
room = client.create_room(name=room_name)
After you’ve created the room, generating an access token for participants is the next step. Just make sure to specify the room name in the token’s grants. If you have any questions or need a hand with this, feel free to ask—I’m here to help! Sources: complex-agents/ivr-agent/flask_livekit/extension.py | CreateRoom() is Taking Too Long | examples/rpc.py
s
what happens to the room after creation?
t
Thanks for your question! When a room is created in LiveKit, it acts as a real-time session space to help manage communication between everyone involved. Here’s a little overview of what happens: • The room stays open as long as there’s at least one participant inside. Once the last person leaves, the room will close after the
departure_timeout
period. • If no one joins within the
empty_timeout
timeframe, the room will automatically close to keep things tidy. • The room keeps track of important info like metadata, how many participants are connected, whether recording is active, and timestamps such as when it was created. • If needed, admins can delete a room anytime using the
DeleteRoom
API, which immediately disconnects everyone and ends the session. • Rooms also support some great advanced features like egress for recording or streaming, agent dispatch, and AV sync options, all of which can be set up right when the room is created. • You can even update room metadata on the fly with the
UpdateRoomMetadata
API to keep everything current as the session evolves. If you’d like, I’m here to help with any more details or to guide you through managing your rooms smoothly! Sources: Rooms, participants, and tracks | LiveKit Docs | Core Platform Architecture | livekit/livekit_composite | DeepWiki | livekit-protocol/livekit/protocol/room.pyi | Connecting to LiveKit | LiveKit Docs | Managing rooms | LiveKit Docs
s
If I have a few different entrypoints, they all use the same Agent class but with different tools and stt and tts configurations, then can I just define the entrypoints and not have to define seperate Agents?
t
Absolutely! You can definitely use the same Agent class across multiple entrypoints, each with its own unique tools, STT, and TTS configurations. The key is to pass different configurations when you initialize the Agent class for each entrypoint. Here’s a simple way to do it: • Dynamic Configuration: Just pass the specific STT, TTS, and tool settings to the Agent class constructor. For example:
Copy code
class TestAgent(Agent):
    def __init__(self, stt, tts, llm):
        super().__init__(
            instructions=f"You are a test agent using {stt} and {tts}",
            stt=stt,
            tts=tts,
            llm=llm
        )
• Entrypoint Example: Each entrypoint can create the same Agent class but with different configurations like this:
Copy code
async def entrypoint_one(ctx):
    agent = TestAgent(stt=deepgram.STT(), tts=cartesia.TTS(), llm=openai.LLM())
    await agent.start(ctx)

async def entrypoint_two(ctx):
    agent = TestAgent(stt=google.STT(), tts=elevenlabs.TTS(), llm=anthropic.LLM())
    await agent.start(ctx)
• Runtime Flexibility: Plus, if you want, you can update tools and configurations on the fly during runtime using methods like
agent.update_tools()
. This way, you avoid duplicating your Agent definitions while still having the flexibility to customize configurations as needed. If you'd like, I’m here to help with more examples or to clarify anything further! Sources: examples/src/comprehensive_test.ts | Introducing LiveKit Inference: A unified model interface for voice AI | Models | LiveKit Docs | docs/index.yaml | Tool definition and use | LiveKit Docs
s
but you did not specify different agent_names in the entrypoints?
t
Thanks for your question! When it comes to entrypoints using the same Agent class in LiveKit, they don’t necessarily need different
agent_name
values. The
agent_name
mainly helps with agent dispatch control and identifying workers, rather than distinguishing between different Agent classes or entrypoints. That said, there are a few things to keep in mind: • Dispatch Rule Conflicts: If multiple entrypoints share the same
agent_name
, they might end up intercepting the same dispatch rules, which can cause some unpredictable behavior. • Scaling Requirements: You can use the same
agent_name
across multiple servers or worker processes to keep things available and running smoothly. • Telephony Use Cases: For inbound calls, it’s important that the
agent_name
matches in both the agent configuration and the dispatch rule. Using unique
agent_name
values for different entrypoints can really help avoid conflicts here. So, to sum it up, while reusing the same
agent_name
is definitely possible, it’s usually best to pick unique names for different entrypoints if you want to steer clear of dispatch conflicts and keep routing predictable. If you have any more questions or need me to explain anything further, please don’t hesitate to ask—I’m here to help! Sources: SIP troubleshooting guide | LiveKit Docs | avatars/hedra/realtime_avatar/agent.py | Agents telephony integration | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik...
s
can i have two entrypoints with different agents in the same file? Can i execute two in the same file? cli.run_app( WorkerOptions( entrypoint_fnc=outbound_call_entrypoint, agent_name="outbound-caller", ) ) cli.run_app( WorkerOptions( entrypoint_fnc=example_call_entrypoint, agent_name="example-caller", ) )
t
I understand that running two separate
cli.run_app
calls in the same file isn’t directly possible, since each call is meant to run a single worker process. But don’t worry! You can still manage multiple entrypoints or agents within a single
entrypoint_fnc
by orchestrating their behavior dynamically. Here are some friendly approaches to help you out: • Agent Handoff: Consider using a lead agent that hands off control to other agents based on the context. For example:
Copy code
class LeadAgent(Agent):
    @function_tool
    async def switch_to_specialist(self, context):
        specialist_agent = SpecialistAgent()
        return specialist_agent, "Switching to specialist agent."

async def entrypoint(ctx):
    session = AgentSession()
    await session.start(agent=LeadAgent(), room=ctx.room)
• Multiple Participant Tasks: You can register multiple participant entrypoints within the same main entrypoint like this:
Copy code
async def entrypoint(ctx):
    async def participant_task_1(ctx, participant):
        # Handle specific behavior
        pass

    async def participant_task_2(ctx, participant):
        # Handle different behavior
        pass

    ctx.add_participant_entrypoint(entrypoint_fnc=participant_task_1)
    ctx.add_participant_entrypoint(entrypoint_fnc=participant_task_2)
    await ctx.connect()
• Dynamic Agent Updates: Another way is to programmatically switch between agents during a session:
Copy code
async def entrypoint(ctx):
    session = AgentSession()
    await session.start(agent=InitialAgent(), room=ctx.room)
    session.update_agent(SpecialistAgent())
These methods should give you the flexibility to manage multiple agents or entrypoints within a single
cli.run_app
call. If you’d like me to walk you through any of these examples in more detail or provide additional help, just let me know—I’m here for you! Sources: main.py | Workflows | LiveKit Docs | Worker options | LiveKit Docs | examples/voice_agents/silent_function_call.py
s
can the same joining details be used to rejoin a room if the participant has left it once?
t
Absolutely, you can use the same joining details (token) to rejoin a LiveKit room after leaving, as long as the token hasn’t expired yet. Here are a few important things to keep in mind: • Token Expiration: Tokens come with a Time-To-Live (TTL). If your token is still active, you’re good to go and can use it to rejoin the room. • Identity Uniqueness: Each participant’s identity needs to be unique in the room. So, if you rejoin using the same token (and identity), any previous connection with that identity will be disconnected automatically. • Security Measures: To keep things secure and avoid unwanted rejoining, you might want to generate tokens with a shorter TTL or manage token issuance carefully through your backend. If you have any questions or want me to walk you through token management in more detail, just let me know—I’m here to help! Sources: Managing participants | LiveKit Docs | Authentication | LiveKit Docs | CLI Tools & Token Management | livekit/livekit_composite | DeepWiki | Connecting to LiveKit | LiveKit Docs