give me code example for how to get livekit agent ...
# ask-ai
w
give me code example for how to get livekit agent to dial a phone number and add participant to room using twilio
t
Thanks for reaching out, Sunil. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To use LiveKit to dial a phone number and add a participant to a room using Twilio, you can follow these steps: Direct Outbound Calls with LiveKit SIP Here is an example in Node.js/TypeScript:
Copy code
import {
  SipClient,
} from 'livekit-server-sdk';

const sipClient = new SipClient(
  LIVEKIT_URL,
  LIVEKIT_API_KEY,
  LIVEKIT_API_SECRET,
);

async function makeCall(phoneNumber) {
  const formattedPhoneNumber = formatPhoneNumber(phoneNumber);
  const roomName = `room_${Math.floor(Math.random() * 10_000)}`;
  const participantIdentity = `caller_${formattedPhoneNumber}`;

  // Create the room first
  await roomServiceClient.createRoom({name: roomName, emptyTimeout: 60});

  // Create SIP participant to initiate the call
  const sipParticipant = await sipClient.createSipParticipant(
    SIP_OUTBOUND_TRUNK_ID, // Your outbound trunk ID
    formattedPhoneNumber,   // Phone number to dial
    roomName,              // LiveKit room name
    {participantIdentity}  // Participant options
  );
}
Here is the equivalent in Python:
Copy code
from livekit import api

async def make_call(phone_number):
    lkapi = api.LiveKitAPI()
    
    # Create SIP participant to make the call
    sip_participant = await lkapi.sip.create_sip_participant(
        api.CreateSIPParticipantRequest(
            room_name=room_name,
            sip_trunk_id=outbound_trunk_id,  # Your trunk ID
            sip_call_to=phone_number,        # Phone number to dial
            participant_identity="phone_user",
        )
    )
Agent Integration Example If you are integrating this functionality within an agent, here is an example:
Copy code
import { SipClient } from 'livekit-server-sdk';

export default defineAgent({
  entry: async (ctx: JobContext) => {
    await ctx.connect();

    const sipClient = new SipClient(
      process.env.LIVEKIT_URL ?? '',
      process.env.LIVEKIT_API_KEY ?? '',
      process.env.LIVEKIT_API_SECRET ?? '',
    );

    const trunkId = '...'; // Your trunk ID
    const phoneNumber = '...'; // Phone number to dial
    const roomName = ctx.room.name ?? '';
    const participantIdentity = 'Example participant identity';

    await sipClient.createSipParticipant(
      trunkId, 
      phoneNumber, 
      roomName, 
      { participantIdentity }
    );

    const participant = await ctx.waitForParticipant(participantIdentity);
    // Continue with agent logic...
  },
});
Prerequisites • An outbound SIP trunk configured with Twilio • Environment variables set up, including
LIVEKIT_URL
,
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
, and
SIP_OUTBOUND_TRUNK_ID
• Phone numbers formatted in E.164 format (e.g.,
+15105550100
) Let me know if you need further clarification or assistance! Sources: packages/sip--make-a-call/src/make-call.ts | complex-agents/ivr-agent/flask_livekit/extension.py | examples/src/outbound.ts | Inbound calls with Twilio Voice | LiveKit Docs | SIP outbound trunk | LiveKit Docs
w
give me the complete python code please
t
Hey there! I've got a super handy Python script that shows you how to use LiveKit to dial a phone number and bring someone into a room using Twilio. Let me walk you through it!
Copy code
import asyncio
import os
import logging
from pathlib import Path
from dotenv import load_dotenv
from livekit import api

# Load environment variables
load_dotenv(dotenv_path=Path(__file__).parent / '.env')

# Set up logging
logger = logging.getLogger("make-call")
logger.setLevel(<http://logging.INFO|logging.INFO>)

# Configuration
room_name = "my-room"
agent_name = "test-agent"
outbound_trunk_id = os.getenv("SIP_OUTBOUND_TRUNK_ID")

async def make_call(phone_number):
    """Create a dispatch and add a SIP participant to call the phone number"""
    lkapi = api.LiveKitAPI()
    
    # Create agent dispatch
    <http://logger.info|logger.info>(f"Creating dispatch for agent {agent_name} in room {room_name}")
    dispatch = await lkapi.agent_dispatch.create_dispatch(
        api.CreateAgentDispatchRequest(
            agent_name=agent_name, room=room_name, metadata=phone_number
        )
    )
    <http://logger.info|logger.info>(f"Created dispatch: {dispatch}")
    
    # Create SIP participant to make the call
    if not outbound_trunk_id or not outbound_trunk_id.startswith("ST_"):
        logger.error("SIP_OUTBOUND_TRUNK_ID is not set or invalid")
        return
    
    <http://logger.info|logger.info>(f"Dialing {phone_number} to room {room_name}")
    
    try:
        # Create SIP participant to initiate the call
        sip_participant = await lkapi.sip.create_sip_participant(
            api.CreateSIPParticipantRequest(
                room_name=room_name,
                sip_trunk_id=outbound_trunk_id,
                sip_call_to=phone_number,
                participant_identity="phone_user",
            )
        )
        <http://logger.info|logger.info>(f"Created SIP participant: {sip_participant}")
    except Exception as e:
        logger.error(f"Error creating SIP participant: {e}")
    
    # Close API connection
    await lkapi.aclose()

async def main():
    # Replace with the actual phone number including country code
    phone_number = "+1231231231"
    await make_call(phone_number)

if __name__ == "__main__":
    asyncio.run(main())
Environment Configuration Create a
.env
file with the following variables:
Copy code
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_HOST=your_livekit_host
SIP_OUTBOUND_TRUNK_ID=ST_your_trunk_id
I hope this helps you get started! This script is a great way to dial a phone number and bring them into a LiveKit room. If you're scratching your head about anything, just give me a shout – I'm here to help! 😊 Sources: telephony/survey_caller/make_survey_calls.py | agent.py | Agents telephony integration | LiveKit Docs | Making calls using SIP | LiveKit Docs | SIP outbound trunk | LiveKit Docs