cuddly-vr-85751
12/04/2025, 6:12 PMtall-airline-16756
12/04/2025, 6:13 PMtall-airline-16756
12/04/2025, 6:13 PMcuddly-vr-85751
12/04/2025, 6:13 PMtall-airline-16756
12/04/2025, 6:14 PMimport json
from fastapi import APIRouter, Depends, HTTPException
from livekit import api
from app.config.load_env import LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET
from app.services import agent_service
from app.services.auth import verify_token
router = APIRouter()
@router.post("/connect-agent/{type}")
async def connect_agent(type: str, agentData: dict, current_user: dict = Depends(verify_token)):
async with api.LiveKitAPI(url=LIVEKIT_URL, api_key=LIVEKIT_API_KEY, api_secret=LIVEKIT_API_SECRET) as lk_client:
try:
agent = await agent_service.get_agent(agentData["agent_id"], current_user.get("client_id"))
tts = agent.get("tts") or {}
agent_dict = {
"id": agent.get("id"),
"name": agent.get("name"),
"role": agent.get("role"),
"system_prompt": agent.get("system_prompt"),
"greeting": agent.get("greeting"),
"tts": {
"provider": getattr(tts.get("provider"), "value", tts.get("provider")),
"voice_id": tts.get("voice_id"),
"model": tts.get("model"),
},
}
await lk_client.agent_dispatch.create_dispatch(
request=api.CreateAgentDispatchRequest(
agent_name=type,
room=agentData["room_name"],
metadata=json.dumps({"user": current_user, "web-agent": agent_dict}),
)
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to dispatch agent: {e}")
return {"room": agentData["room_name"]}
@router.post("/token")
async def generate_token(payload: dict):
room = payload["room_name"]
identity = payload["participant_name"]
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name(identity)
.with_grants(
api.VideoGrants(
room_join=True,
room=room,
can_publish=True,
can_subscribe=True,
)
)
)
return {"token": token.to_jwt(), "url": LIVEKIT_URL, "room": room}
4) Run server:
• uvicorn app.main:app --reload
If you'd like, I can:
• Show a minimal example for load_env.py
• Show request examples (curl/JS) for both endpoints
• Add room permission restrictions in the token grants
Which of those would you like next?
Sources: Generating tokens | LiveKit docs | Agent dispatch | LiveKit docs | Observability data hooks | LiveKit docs | Python SDKs | livekit/livekit_composite | DeepWiki | Authentication | LiveKit docscuddly-vr-85751
12/04/2025, 6:14 PMtall-airline-16756
12/04/2025, 6:15 PMLIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
PORT=3000
3) server.js
import express from "express";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import { LiveKitServer, AccessToken, VideoGrant } from "livekit-server-sdk";
dotenv.config();
const { LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, PORT = 3000 } = process.env;
const app = express();
app.use(bodyParser.json());
// Helper to create a LiveKit REST client
function makeLiveKitClient() {
return new LiveKitServer(LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
}
// POST /connect-agent/:type
app.post("/connect-agent/:type", async (req, res) => {
const type = req.params.type;
const agentData = req.body; // expects { agent_id, room_name, ... }
const current_user = req.headers["x-current-user"] ? JSON.parse(req.headers["x-current-user"]) : {}; // adapt auth
try {
// Replace with your actual agent_service.get_agent implementation
const agent = await getAgent(agentData.agent_id, current_user.client_id);
const tts = agent.tts || {};
const agent_dict = {
id: agent.id,
name: agent.name,
role: agent.role,
system_prompt: agent.system_prompt,
greeting: agent.greeting,
tts: {
provider: (tts.provider && tts.provider.value) || tts.provider,
voice_id: tts.voice_id,
model: tts.model,
},
};
const lk = makeLiveKitClient();
// Agent Dispatch createDispatch — LiveKit server SDK exposes REST methods on LiveKitServer
await lk.agentDispatch.createDispatch({
agent_name: type,
room: agentData.room_name,
metadata: JSON.stringify({ user: current_user, "web-agent": agent_dict }),
});
return res.json({ room: agentData.room_name });
} catch (err) {
console.error("Failed to dispatch agent:", err);
return res.status(500).json({ error: "Failed to dispatch agent", details: err.message });
}
});
// POST /token
app.post("/token", (req, res) => {
const { room_name: room, participant_name: identity } = req.body || {};
if (!room || !identity) return res.status(400).json({ error: "room_name and participant_name required" });
const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity });
const grant = new VideoGrant({ roomJoin: true, room, canPublish: true, canSubscribe: true });
at.addGrant(grant);
try {
const token = at.toJwt();
return res.json({ token, url: LIVEKIT_URL, room });
} catch (err) {
console.error("token generation failed:", err);
return res.status(500).json({ error: "Token generation failed", details: err.message });
}
});
app.listen(PORT, () => console.log(`Server listening on ${PORT}`));
/*
NOTE: Implement `getAgent(agentId, clientId)` to match your Python agent_service.get_agent.
If you use async DB calls, mark it async and await inside the route.
*/
Notes:
• Adapt auth: I used a placeholder for current_user; wire your existing auth (verify_token) into Express middleware.
• Replace getAgent with your real agent service call.
• The server SDK method names (e.g., agentDispatch.createDispatch) match the SDK pattern — adjust if your SDK version exposes different method names.
Would you like:
• a version using CommonJS (require) instead of ES modules, or
• a ready-to-run example including a mock getAgent and auth middleware? Sources: server-sdk-js | livekit/livekit_composite | DeepWiki | Generating tokens | LiveKit docs | Authentication | LiveKit docs | Server-side | livekit/livekit_composite | DeepWiki | Agents (Node.js) | livekit/livekit_composite | DeepWiki