I have an API endpoint where I need to spawn a wor...
# ask-ai
f
I have an API endpoint where I need to spawn a worker with an explicit agent dispatch to an explicitly defined room name. What's the best way to do this?
t
Thanks for reaching out, Eden. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To spawn a worker with explicit agent dispatch to a defined room name using the API, follow these steps: • Configure the Worker with an Agent Name: Set up your worker with an
agent_name
in the
WorkerOptions
to enable explicit dispatch. For example: • Use the API to Create Explicit Dispatch: Once your worker is running with a named agent, you can dispatch it to specific rooms using the API. For example: Key Features: • Automatic Room Creation: The room is automatically created during dispatch if it doesn’t already exist. • Job Metadata: You can pass metadata to the agent, which is available in the
JobContext
. Use JSON for structured data. • High Performance: The dispatch system supports high concurrency and low latency, typically handling hundreds of thousands of connections per second. This method provides precise control over agent-room assignments while leveraging LiveKit's optimized dispatch system.
f
Can you give me a code example?
t
Node.js Example:
Copy code
import { AgentDispatchClient } from 'livekit-server-sdk';

const roomName = 'my-room';
const agentName = 'test-agent';

async function createExplicitDispatch() {
  const agentDispatchClient = new AgentDispatchClient(process.env.LIVEKIT_URL);

  // Dispatch the agent to the specified room
  const dispatch = await agentDispatchClient.createDispatch(roomName, agentName, {
    metadata: '{"mydata": "myvalue"}',
  });
  console.log('Created dispatch:', dispatch);
}

createExplicitDispatch().catch(console.error);
Python Example:
Copy code
import asyncio
from livekit import api

room_name = "my-room"
agent_name = "test-agent"

async def create_explicit_dispatch():
    lkapi = api.LiveKitAPI()
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name, 
            room=room_name, 
            metadata='{"user_id": "12345"}'
        )
    )
    print("Created dispatch:", dispatch)
    await lkapi.aclose()

asyncio.run(create_explicit_dispatch())
Hey there! I've got some cool code examples that show you how to send a worker to a specific room using LiveKit. These snippets are super handy if you're looking to dispatch an agent with some custom settings. I broke it down for both Node.js and Python, so you can see how straightforward it can be. Need me to walk you through any part of these examples? I'm totally here to help and make sure you understand exactly what's going on! 😊 Just give me a shout if something isn't crystal clear.