i want to use my livekit cloud deployed agent for ...
# ask-ai
l
i want to use my livekit cloud deployed agent for both inbound call as well as for my custom frontend voice chat, this is my current dispatch rule, { "sipDispatchRuleId": "SDR_2QkmQEpBuXLb", "rule": { "dispatchRuleIndividual": { "roomPrefix": "call-" } } } ryt now the agent connects only through inbound call and not through my frontend, i want it to connect to both also i have given my agent a name, if name == "__main__": cli.run_app(WorkerOptions( entrypoint_fnc=entrypoint, agent_name = "ml-agent" ))
t
Thanks for reaching out, Computer. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Let's walk through how you can set up your LiveKit agent to handle both inbound calls and custom frontend voice chat. I’m here to help you every step of the way! 1. Inbound SIP Calls: First, make sure your SIP dispatch rule is set up correctly to route calls to your agent. Using a SIP trunk provider like Twilio or Plivo is a great way to manage inbound calls and connect them to LiveKit seamlessly. 2. Custom Frontend Voice Chat: Next, you’ll want to use the LiveKit SDKs, such as the JavaScript SDK, to connect your users to a room where your agent is available. This setup enables smooth, real-time audio communication between the user and the agent. 3. Connect Agent and Frontend: To bring it all together, configure your agent to join the same room as the frontend user. You can do this by setting the right room token configuration or by using event-based dispatch—whichever works best for your setup. 4. Deploy to LiveKit Cloud: Finally, when you’re ready for production, deploying your agent to LiveKit Cloud will help ensure your system is scalable and reliable. If you’d like to see some detailed examples, feel free to check out the SIP Agent Example and the Agent Starter for React. And please don’t hesitate to reach out if you have any questions or need a hand—I’m here to support you! Sources: Web and mobile frontends | LiveKit Docs | README.md | Agents telephony integration | LiveKit docs | Create and configure Telnyx SIP trunk | LiveKit docs | OpenAI and LiveKit partner to turn Advanced Voice into an API
l
show me the sample code for it, i have used twilio and setup everything but now inbound call works but agent is not connecting to my custom frontend, check my dispatch rules i provided above and tell me what to do
t
To help you connect your agent to both inbound calls and your custom frontend, here’s a friendly sample setup you can follow: 1. Dispatch Rule for Inbound Calls
Copy code
{
  "sipDispatchRuleId": "SDR_2QkmQEpBuXLb",
  "rule": {
    "dispatchRuleIndividual": {
      "roomPrefix": "call-"
    }
  },
  "roomConfig": {
    "agents": [
      {
        "agentName": "ml-agent",
        "metadata": "inbound_call_agent"
      }
    ]
  }
}
2. Custom Frontend Integration Make sure your frontend connects to the same room created by the dispatch rule. Here’s a simple example using JavaScript:
Copy code
const room = new Room();
await room.connect('wss://your-livekit-url', 'your-access-token', {
  publishDefaults: { video: false, audio: true },
});
3. Agent Code Be sure your agent is set up to join the room and manage interactions smoothly:
Copy code
async def agent_worker(session: AgentSession):
    await session.start()
    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )
If you have any questions or need more examples, please don’t hesitate to ask—I’m here to help! Sources: Agents telephony integration | LiveKit docs | src/setup-livekit.ts | packages/sip--um-actually/src/setup-livekit.ts | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki
l
C:\Users\AaronFrancis\Desktop\my work\vscode\research\eds_malayalam_agent\eds_malayalam_agent_backend>lk sip dispatch create dispatch-rule.json WARNING: config file C:\Users\AaronFrancis/.livekit/cli-config.yaml should have permissions 600 WARNING: config file C:\Users\AaronFrancis/.livekit/cli-config.yaml should have permissions 600 Using project [agent] could not read request: proto: (line 2:3): unknown field "sipDispatchRuleId"
t
It looks like the error happens because the
sipDispatchRuleId
field shouldn’t be included when you’re creating a new dispatch rule. This field is actually generated automatically by the system when a rule is created, and it’s mainly used when updating or identifying existing rules. To fix this, simply remove the
sipDispatchRuleId
field from your
dispatch-rule.json
file. Here’s an updated example to guide you:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "name": "My dispatch rule",
    "roomConfig": {
      "agents": [
        {
          "agentName": "ml-agent",
          "metadata": "inbound_call_agent"
        }
      ]
    }
  }
}
Give running the command again with this updated file a try, and please don’t hesitate to reach out if you run into any other issues—I’m here to help! Sources: livekit/sip.go | SIP dispatch rule | LiveKit docs
l
i have set the dispatch rules as mentioned yet the agent is not joining in livekit playground or in my custom frontend
t
If your agent isn’t joining the room after setting the dispatch rules, don’t worry! Let’s walk through some helpful steps together to get this sorted out: 1. Verify Dispatch Rule Configuration: First, double-check that your dispatch rule includes the correct
agentName
in the
roomConfig
. Here’s an example to guide you:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "ml-agent"
        }
      ]
    }
  }
}
2. Test Agent Dispatch: Next, try manually dispatching the agent to a test room to ensure everything’s working smoothly. Here’s a Python example you can use:
Copy code
async def test_agent_dispatch():
    lkapi = api.LiveKitAPI()
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name="ml-agent", 
            room="test-room", 
            metadata="test_dispatch"
        )
    )
    print("Created dispatch:", dispatch)
    await lkapi.aclose()
3. Check Agent Logs: It’s important to make sure your agent is running and the logs indicate it’s ready to accept jobs. Keep in mind, if
agent_name
is set in
WorkerOptions
, automatic dispatch won’t work, so you’ll need to dispatch explicitly. 4. Monitor Connection Events: To catch any connection hiccups, monitor the connection state by checking
room.connectionState
or listening for the
Disconnected
event. 5. Load Testing: Finally, you can use the LiveKit CLI to put your agent through a load test and observe its dispatch and joining behavior:
lk agent load-test --agent-name "ml-agent" --rooms 1 --duration 30s
If you run into any questions or want a hand with any of these steps, just let me know—I’m here to help! Sources: src/setup-livekit.ts | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | Web and mobile frontends | LiveKit Docs | Agents telephony integration | LiveKit docs | examples/agent_dispatch.py
l
listen i want my agent for which i havent given any name, to be connected to my frontend which is working now as i removed the dispatch rules but i want the agent to connect for inbound calls as well, tell me exactly how to make these 2 use cases to work and show me the steps
t
To help you set up your agent for both inbound calls and your custom frontend, here’s a simple step-by-step guide: 1. Set an Agent Name: It’s important to give your agent a name so explicit dispatch can work smoothly. You can update your agent code like this:
Copy code
if __name__ == "__main__":
    cli.run_app(WorkerOptions(
        entrypoint_fnc=entrypoint,
        agent_name="ml-agent"  # Assign a name
    ))
2. Configure Inbound Calls: Next, set up a SIP trunk (like Twilio or Plivo) and create a dispatch rule to direct calls to your agent. Here’s an example dispatch rule:
Copy code
{
  "dispatch_rule": {
    "rule": {
      "dispatchRuleIndividual": {
        "roomPrefix": "call-"
      }
    },
    "roomConfig": {
      "agents": [
        {
          "agentName": "ml-agent"
        }
      ]
    }
  }
}
3. Connect to Custom Frontend: Make sure your frontend connects to the same room as the agent. Here’s a quick example using JavaScript:
Copy code
const room = new Room();
await room.connect('wss://your-livekit-url', 'your-access-token', {
  publishDefaults: { video: false, audio: true },
});
4. Test Both Use Cases: Finally, double-check that inbound calls are correctly routed to the agent and that the agent joins the same room as your frontend user. If you have any questions or need a hand with any of these steps, please don’t hesitate to reach out—I’m here to help! Sources: Agents telephony integration | LiveKit Docs | Agents telephony integration | LiveKit docs | templates.yaml | README.md | Create and configure Telnyx SIP trunk | LiveKit docs
l
but when i give my backend agent a name and uploade it livekit cloud, the agent doesnt connect on livekit playground or my frontend, but i remove the name and it connects to both
t
When you assign a name to your agent, it activates explicit dispatch mode, which means the agent needs to be specifically requested in the room configuration. Let me walk you through how to make sure your agent connects smoothly to both the LiveKit Playground and your custom frontend: 1. Verify Agent Name Configuration: Double-check that the agent name is set in your backend code and exactly matches the name you use in the Playground or frontend configuration. For example:
Copy code
if __name__ == "__main__":
    cli.run_app(WorkerOptions(
        entrypoint_fnc=entrypoint,
        agent_name="ml-agent"
    ))
2. Configure the Playground: Before connecting in the LiveKit Playground, make sure to enter the same agent name in the "Agent Name" field. 3. Update Frontend Configuration: Confirm that your frontend includes the agent name in the room configuration. Here's an example:
Copy code
body: JSON.stringify({
  room_config: {
    agents: [{ agent_name: "ml-agent" }]
  }
})
4. Run in Development Mode: While developing, keep your agent running in
dev
mode to help ensure it connects properly. 5. Test Explicit Dispatch: Try manually dispatching the agent to a test room using the LiveKit API or CLI to verify the connection works as expected. If your agent still isn’t connecting, a good next step is to check the agent logs for any errors and confirm that the
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
are all set correctly. Please don’t hesitate to reach out if you’d like me to help you troubleshoot further—I’m here for you! Sources: Agents telephony integration | LiveKit docs | Agents telephony integration | LiveKit Docs | README.md | Voice AI quickstart | LiveKit docs | README.md
l
this is my backend code, once i have uploaded this agent to livekit cloud, the agent is not connecting to livekit playground or in my frontend, i have given the agent name in jwt in my frontend still not connecting
t
To better assist you with this issue, could you please share a few details with me? • The exact JWT payload you're using in your frontend, especially the
room_config
and
agent_name
fields. • Any error messages or logs you see from the agent after it's uploaded to LiveKit Cloud. • Confirmation that the agent name in your backend code matches the one in the JWT and frontend configuration. Once I have this information, I'll be able to guide you more effectively. Thanks so much for your patience!
l
this is the file that generates livekit token in my frontend
t
Could you please share the content of the file that generates the LiveKit token in your frontend? I’d love to take a closer look, especially to see how the
agent_name
and
room_config
are being set in the token payload. This will really help me understand what’s going on and assist you better!
l
the file i uploaded above has the mentioned things go through it
t
Hi there! It looks like the file content didn’t come through in your message. When you get a chance, could you please paste the relevant code or configuration here? Especially the sections where
agent_name
and
room_config
are set. I’m here to help you every step of the way!
l
import type { Handler, HandlerEvent } from "@netlify/functions"; import { AccessToken } from 'livekit-server-sdk'; import type { VideoGrant } from 'livekit-server-sdk'; const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || ''; const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || ''; const LIVEKIT_URL = process.env.LIVEKIT_URL || process.env.LIVEKIT_SERVER_URL || ''; const AGENT_IDENTITY = process.env.AGENT_IDENTITY || 'ml-agent'; const handler: Handler = async (event: HandlerEvent) => { console.log('Token request received with params:', { room: event.queryStringParameters?.room, identity: event.queryStringParameters?.identity, language: event.queryStringParameters?.language, hasEmail: !!event.queryStringParameters?.email, hasName: !!event.queryStringParameters?.name, }); // Check environment variables const envStatus = { hasApiKey: !!LIVEKIT_API_KEY, hasApiSecret: !!LIVEKIT_API_SECRET, hasUrl: !!LIVEKIT_URL, urlProtocol: LIVEKIT_URL ? LIVEKIT_URL.split('://')[0] : 'none' }; console.log('Environment status:', envStatus); if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL) { console.error('Missing required environment variables'); return { statusCode: 500, body: JSON.stringify({ error: "Server is not configured correctly.", details:
Missing: ${!LIVEKIT_API_KEY ? 'API_KEY ' : ''}${!LIVEKIT_API_SECRET ? 'API_SECRET ' : ''}${!LIVEKIT_URL ? 'URL' : ''}
.trim() }), }; } const { room, identity, name, email, language, timezone } = event.queryStringParameters || {}; if (!room || !identity) { console.error('Missing required parameters:', { hasRoom: !!room, hasIdentity: !!identity }); return { statusCode: 400, body: JSON.stringify({ error: "Missing 'room' or 'identity' query parameters" }), }; } const grant: VideoGrant = { room, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, // Allow participants to update their own metadata which can help the agent and UI canUpdateOwnMetadata: true, }; try { console.log('Attempting to generate token with:', { hasIdentity: !!identity, hasRoom: !!room, metadata: { hasName: !!name, hasEmail: !!email, language, timezone } }); const metadata = JSON.stringify({ name, email, language, timezone, role: 'user' }); console.log('Creating AccessToken with API key length:', LIVEKIT_API_KEY.length); const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity, metadata }); console.log('Adding grant:', grant); at.addGrant(grant); // Generate the JWT token string console.log('Generating JWT...'); const tokenString = await Promise.resolve(at.toJwt()); // Log token info without exposing the full token const tokenInfo = { length: typeof tokenString === 'string' ? tokenString.length : 0, isString: typeof tokenString === 'string', startsWithEy: typeof tokenString === 'string' && tokenString.startsWith('ey'), preview: typeof tokenString === 'string' ?
${tokenString.slice(0, 3)}...
: 'null' }; console.log('Token generated:', tokenInfo); // Verify we have a valid token string if (typeof tokenString !== 'string' || !tokenString) { console.error('Token validation failed:', { type: typeof tokenString, isNull: tokenString === null, isUndefined: tokenString === undefined }); throw new Error('Failed to generate token string'); } // Normalize LIVEKIT_URL: ensure it's provided and return both
url
and
serverUrl
for compatibility if (!LIVEKIT_URL.startsWith('ws://') && !LIVEKIT_URL.startsWith('wss://')) { console.log('Warning: LIVEKIT_URL should start with ws:// or wss://', { providedUrl: LIVEKIT_URL }); } return { statusCode: 200, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", // Enable CORS "Access-Control-Allow-Headers": "Content-Type" }, body: JSON.stringify({ token: tokenString, serverUrl: LIVEKIT_URL, url: LIVEKIT_URL, agentIdentity: AGENT_IDENTITY }) }; } catch (error) { console.error('Error generating token:', error); return { statusCode: 500, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ error: "Failed to generate token", details: error instanceof Error ? error.message : String(error) }) }; } }; export { handler };
t
Thanks for sharing your token generation code! Let’s walk through some steps together to make sure your agent connects smoothly to both the LiveKit Playground and your frontend: 1. Verify Agent Name: Double-check that the
AGENT_IDENTITY
environment variable matches the agent name you’ve set in your backend code. For example:
const AGENT_IDENTITY = process.env.AGENT_IDENTITY || 'ml-agent';
2. Include Agent Name in Room Configuration: When you generate the token, make sure the
room_config
includes the agent name. You can update your token generation logic like this:
Copy code
const grant: VideoGrant = {
  room,
  roomJoin: true,
  canPublish: true,
  canPublishData: true,
  canSubscribe: true,
  canUpdateOwnMetadata: true,
};

const roomConfig = {
  agents: [{ agent_name: AGENT_IDENTITY }],
};

const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity, metadata });
at.addGrant(grant);
at.roomConfig = roomConfig;
3. Frontend Integration: Make sure your frontend sends the correct agent name when requesting the token. For example:
Copy code
const response = await fetch('/api/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    roomName: 'my-room',
    participantName: 'user123',
    agentName: 'ml-agent'
  }),
});
4. Test Explicit Dispatch: Try using the LiveKit API or CLI to manually dispatch the agent to a test room and check that it connects properly. If you run into any bumps or want me to clarify any of these steps, just let me know—I’m here to help! Sources: Agent dispatch | LiveKit Docs | client/web/src/app/api/connection-details/route.ts | Authentication | LiveKit Docs | src/pages/api/token.ts | app/api/connection-details/route.ts
l
import type { Handler, HandlerEvent } from "@netlify/functions"; import { AccessToken } from 'livekit-server-sdk'; import type { VideoGrant } from 'livekit-server-sdk'; const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || ''; const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || ''; const LIVEKIT_URL = process.env.LIVEKIT_URL || process.env.LIVEKIT_SERVER_URL || ''; const AGENT_IDENTITY ='ml-agent'; const handler: Handler = async (event: HandlerEvent) => { console.log('Token request received with params:', { room: event.queryStringParameters?.room, identity: event.queryStringParameters?.identity, language: event.queryStringParameters?.language, hasEmail: !!event.queryStringParameters?.email, hasName: !!event.queryStringParameters?.name, }); // Check environment variables const envStatus = { hasApiKey: !!LIVEKIT_API_KEY, hasApiSecret: !!LIVEKIT_API_SECRET, hasUrl: !!LIVEKIT_URL, urlProtocol: LIVEKIT_URL ? LIVEKIT_URL.split('://')[0] : 'none' }; console.log('Environment status:', envStatus); if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL) { console.error('Missing required environment variables'); return { statusCode: 500, body: JSON.stringify({ error: "Server is not configured correctly.", details:
Missing: ${!LIVEKIT_API_KEY ? 'API_KEY ' : ''}${!LIVEKIT_API_SECRET ? 'API_SECRET ' : ''}${!LIVEKIT_URL ? 'URL' : ''}
.trim() }), }; } const { room, identity, name, email, language, timezone } = event.queryStringParameters || {}; if (!room || !identity) { console.error('Missing required parameters:', { hasRoom: !!room, hasIdentity: !!identity }); return { statusCode: 400, body: JSON.stringify({ error: "Missing 'room' or 'identity' query parameters" }), }; } const grant: VideoGrant = { room, roomJoin: true, canPublish: true, canPublishData: true, canSubscribe: true, // Allow participants to update their own metadata which can help the agent and UI canUpdateOwnMetadata: true, }; try { console.log('Attempting to generate token with:', { hasIdentity: !!identity, hasRoom: !!room, metadata: { hasName: !!name, hasEmail: !!email, language, timezone } }); // Check if this is the agent requesting a token const isAgent = identity === AGENT_IDENTITY; // Prepare metadata based on whether this is the agent or a user const metadata = JSON.stringify(isAgent ? { role: 'agent', language, timezone, isAgent: true } : { name, email, language, timezone, role: 'user', isAgent: false }); console.log('Creating AccessToken for:', { identity, isAgent, role: isAgent ? 'agent' : 'user' }); const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity, name: isAgent ? 'Malayalam AI Agent' : name || identity, ttl: isAgent ? 24 * 60 * 60 : 60 * 60, // 24 hours for agent, 1 hour for users metadata }); if (isAgent) { // Add additional permissions for agent grant.canPublish = true; grant.canPublishData = true; grant.canSubscribe = true; grant.canUpdateOwnMetadata = true; } console.log('Adding grant:', { grant, isAgent }); at.addGrant(grant); // Generate the JWT token string console.log('Generating JWT...'); const tokenString = await Promise.resolve(at.toJwt()); // Log token info without exposing the full token const tokenInfo = { length: typeof tokenString === 'string' ? tokenString.length : 0, isString: typeof tokenString === 'string', startsWithEy: typeof tokenString === 'string' && tokenString.startsWith('ey'), preview: typeof tokenString === 'string' ?
${tokenString.slice(0, 3)}...
: 'null' }; console.log('Token generated:', tokenInfo); // Verify we have a valid token string if (typeof tokenString !== 'string' || !tokenString) { console.error('Token validation failed:', { type: typeof tokenString, isNull: tokenString === null, isUndefined: tokenString === undefined }); throw new Error('Failed to generate token string'); } // Normalize LIVEKIT_URL: ensure it's provided and return both
url
and
serverUrl
for compatibility if (!LIVEKIT_URL.startsWith('ws://') && !LIVEKIT_URL.startsWith('wss://')) { console.log('Warning: LIVEKIT_URL should start with ws:// or wss://', { providedUrl: LIVEKIT_URL }); } return { statusCode: 200, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", // Enable CORS "Access-Control-Allow-Headers": "Content-Type" }, body: JSON.stringify({ token: tokenString, serverUrl: LIVEKIT_URL, url: LIVEKIT_URL, agentIdentity: AGENT_IDENTITY }) }; } catch (error) { console.error('Error generating token:', error); return { statusCode: 500, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ error: "Failed to generate token", details: error instanceof Error ? error.message : String(error) }) }; } }; export { handler }; what about the code now?? i have set my backend agent name as ml-agent
t
Your updated code looks well-structured, and the inclusion of the
AGENT_IDENTITY
as
ml-agent
is spot on. To help make sure your agent connects smoothly to both the LiveKit Playground and your frontend, let’s walk through a few important checks together: 1. Frontend Token Request: Please double-check that your frontend explicitly includes the agent name in the token request. For example:
Copy code
const response = await fetch('/api/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    room: 'my-room',
    identity: 'user123',
    agentName: 'ml-agent'
  }),
});
2. Room Configuration: If your agent isn’t connecting yet, make sure the
room_config
includes the agent name when creating the room. You can update your backend like this:
Copy code
const roomConfig = {
  agents: [{ agent_name: AGENT_IDENTITY }],
};
at.roomConfig = roomConfig;
3. Agent Logs: It’s really helpful to check the logs of your agent running on LiveKit Cloud. This will confirm if it’s registering correctly and ready for jobs. Keep an eye out for any errors or warnings. 4. Playground Configuration: When you’re using the LiveKit Playground, please make sure the "Agent Name" field is set to
ml-agent
before connecting. 5. Environment Variables: Lastly, double-check that
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
, and
LIVEKIT_URL
are all correctly set and accessible in both your backend and agent environments. If you’re still running into issues after these steps, don’t hesitate to reach out. I’m here to help you dig deeper into the agent logs or the token generation process so we can get this working perfectly for you.