billions-lawyer-8588
07/21/2025, 10:53 PMtall-airline-16756
07/21/2025, 10:53 PMtall-airline-16756
07/21/2025, 10:54 PMAgentDispatchService. Here’s a step-by-step example:
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