I want to create flask api endpoint for dispatchin...
# ask-ai
b
I want to create flask api endpoint for dispatching agents.
t
Thanks for reaching out, Harsh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You can create a Flask API endpoint for dispatching agents in LiveKit using the LiveKit Python SDK's
AgentDispatchService
. Here’s a step-by-step example:
Copy code
from flask import Flask, request, jsonify
import asyncio
from livekit import api

app = Flask(__name__)

@app.route('/dispatch-agent', methods=['POST'])
def dispatch_agent():
    try:
        data = request.get_json()
        room_name = data.get('room_name')
        agent_name = data.get('agent_name')
        metadata = data.get('metadata', '')
        if not room_name or not agent_name:
            return jsonify({'error': 'room_name and agent_name are required'}), 400
        result = asyncio.run(create_dispatch(room_name, agent_name, metadata))
        return jsonify({'success': True, 'dispatch': result})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

async def create_dispatch(room_name: str, agent_name: str, metadata: str):
    lkapi = api.LiveKitAPI()
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name,
            room=room_name,
            metadata=metadata
        )
    )
    await lkapi.aclose()
    return {
        'id': dispatch.id,
        'agent_name': dispatch.agent_name,
        'room': dispatch.room,
        'metadata': dispatch.metadata
    }

if __name__ == '__main__':
    app.run(debug=True)
Key points: • Your agent must be registered with an
agent_name
in
WorkerOptions
. • If the specified room doesn’t exist, it will be created automatically during dispatch. • Metadata passed during dispatch will be available in the agent’s
JobContext
. • Set your LiveKit API credentials as environment variables or pass them to
LiveKitAPI
. This setup allows you to dispatch agents to rooms via a simple POST request to
/dispatch-agent
with
room_name
,
agent_name
, and optional
metadata
in the JSON body. Sources: Dispatching agents | LiveKit Docs | examples/agent_dispatch.py