can we make such a software where small business c...
# ask-ai
h
can we make such a software where small business can configure livekit with our software with out ever going to livekit, something like twilio subaccount ?
t
Thanks for reaching out, Priyanshu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! I’d love to help you understand how LiveKit can fit into your small business software setup. While LiveKit doesn’t currently offer a subaccount system or a full account-level delegation model like Twilio, it’s still quite flexible. Integrations do require some setup and management through your main LiveKit account, but don’t worry—I’m here to guide you through it! One of the easiest ways to minimize direct end-user interaction is by using the embeddable Voice Assistant web component. This neat feature wraps up all the UI and connection logic, letting developers embed LiveKit-powered voice agents right into external websites—think customer support widgets or marketing pages—without your users needing to interact with LiveKit directly. You’ll just need to configure a few parameters like the server URL, token endpoint, and agent name, all tied back to your main account. On top of that, LiveKit offers some great tools like: • SIP integration, which lets phone calls join LiveKit sessions as participants—perfect for customer support or AI agents handling inbound calls. • Webhooks and backend automation, so your systems can trigger actions like dispatching AI agents based on session events. • Custom AI agents built with server-side SDKs (like Go or Python) that can join rooms and automate workflows seamlessly. That said, LiveKit doesn’t currently support subaccount-style delegation, per-tenant billing, or white-label reselling that would let small businesses operate independently without your direct involvement. If you’re thinking about reselling real-time communication services to multiple small businesses, you might want to consider: 1. Self-hosting LiveKit instances for each tenant to keep things isolated, or 2. Checking with LiveKit’s enterprise support to see if they offer custom multi-tenancy solutions that aren’t publicly documented. Are you working on a platform that will serve multiple clients? If so, do you need things like usage isolation, separate billing, or branding autonomy for each? Knowing this will really help us figure out the best way to set things up for you. Sources: LiveKit | Intro to LiveKit | LiveKit Docs | README.md | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki
h
let day i have application where user buy twilio number using twilio subaccount , how can i make such that they configure agent sip integration in my app without going to livekit.
t
I'm glad you're exploring how to let users configure SIP integration for LiveKit agents through your application without needing direct access to LiveKit. You can make this happen by bridging phone calls into LiveKit rooms as SIP participants. Here’s a friendly walkthrough to guide you: 1. Set Up a Third-Party SIP Provider (like Twilio): Start by creating a SIP trunk in Twilio and connect it with LiveKit's SIP URI. Then, link a phone number to this trunk so that calls to that number seamlessly route into LiveKit. 2. Configure LiveKit SIP Trunk and Dispatch Rules: Using the LiveKit Server SDK, you can create an inbound SIP trunk and set dispatch rules that direct incoming calls to specific rooms. For example:
Copy code
const sipClient = new SipClient(LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

// Create SIP inbound trunk
const trunk = await sipClient.createSipInboundTrunk(
  'inbound-trunk',
  [TWILIO_PHONE_NUMBER],
  {
    auth_username: TWILIO_SIP_USERNAME,
    auth_password: TWILIO_SIP_PASSWORD,
  }
);

// Create dispatch rule to route calls to rooms and dispatch agents
await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'call',
  },
  {
    name: 'inbound-dispatch-rule',
    trunkIds: [trunk.sipTrunkId],
  }
);
3. Deploy and Run the LiveKit Agent: Next, implement an agent that listens for rooms matching your dispatch rule. When a call comes in, the SIP call is bridged into a LiveKit room, and the agent joins right away to engage with the caller. 4. Environment Setup: Make sure to define environment variables like
LIVEKIT_URL
,
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
,
TWILIO_PHONE_NUMBER
, and
LIVEKIT_SIP_URI
. These will be essential for your setup scripts and agent logic. 5. Automate Configuration: To save time and reduce manual steps, you can use setup scripts that automate creating SIP trunks and dispatch rules. This approach ensures your users only need to interact via phone calls, while your application gracefully manages all the LiveKit configurations behind the scenes. If you want to dive deeper, feel free to check out the SIP Integration Guide and the LiveKit SIP Agent Example Repository. I'm here if you have any questions along the way! Sources: Agents telephony integration | LiveKit Docs | Create and configure a Twilio SIP trunk | LiveKit Docs | README.md | packages/sip--um-actually/README.md
h
So i have to create a one sip in livekit with variable twilio phone number
t
Absolutely, you can create a single SIP trunk in LiveKit that beautifully handles multiple Twilio phone numbers dynamically. When you're setting up the SIP trunk, you just need to specify a list of phone numbers in the
numbers
field. This way, the trunk will happily accept calls only if the destination number matches one of the numbers in your list. For instance, when you're creating the trunk using the LiveKit Server SDK, you can include several numbers like this:
Copy code
const trunk = await sipClient.createSipInboundTrunk(
  'inbound-trunk',
  [TWILIO_PHONE_NUMBER_1, TWILIO_PHONE_NUMBER_2, TWILIO_PHONE_NUMBER_3],
  {
    auth_username: TWILIO_SIP_USERNAME,
    auth_password: TWILIO_SIP_PASSWORD,
  }
);
Plus, you have the flexibility to update the list of numbers dynamically through the API, which makes routing calls from multiple Twilio numbers through a single LiveKit SIP trunk both easy and scalable. If you'd like, I'm here to help you with the setup or guide you through the API usage—just let me know! Sources: SIP APIs | LiveKit Docs | protobufs/livekit_sip.proto | src/setup-livekit.ts | packages/sip--um-actually/src/setup-livekit.ts | SIP overview | LiveKit Docs
h
but what if new business login to app and by new number using twilio subaccount . how will i handle call for that business.
t
Handling calls for new Twilio subaccount phone numbers dynamically can feel a bit tricky, but don’t worry—I’m here to guide you through it step-by-step! You can create a system that detects new numbers and automatically updates your LiveKit SIP configuration. Here’s a friendly roadmap to get you started: 1. Keep an Eye Out for New Subaccount Phone Numbers: You can use the Twilio API to regularly check the phone numbers across your subaccounts. By comparing these to a list you already know, you’ll spot any new additions. For example:
Copy code
const subaccountNumbers = await client.api.accounts(subaccountSid)
  .incomingPhoneNumbers.list();
2. Set Up Twilio SIP Trunk Automatically: Once you find a new number, you can connect it to an existing SIP trunk or create a new one. The Twilio API lets you link the number with the trunk and set the origination URL to your LiveKit SIP endpoint—making the process smooth and efficient. 3. Keep Your LiveKit Inbound Trunk Updated: You have a couple of options here: ◦ Add the new number to your current LiveKit SIP trunk using the
updateSipInboundTrunk
API. ◦ Or, use a wildcard setup to accept calls from any number on the Twilio SIP trunk, so you won’t need to update for each number individually. 1. Use Dispatch Rules to Route Calls: Set up dispatch rules in LiveKit that route calls to specific rooms based on the phone number (like
call-+1234567890
). This way, agents get dispatched automatically to handle incoming calls smoothly. This method helps ensure that any new phone numbers you add to your Twilio subaccounts get integrated into your LiveKit setup effortlessly—no manual work needed! If you’d like, I’m more than happy to help you implement this workflow or even assist with writing the scripts. Just let me know! Sources: packages/sip--um-actually/README.md | SIP inbound trunk | LiveKit Docs | Inbound calls with Twilio Voice | LiveKit Docs | Create and configure a Twilio SIP trunk | LiveKit Docs | README.md
h
so i have to update sip in livekit, what happen in case when two business have call at same time do sip(we have one sip only) create two room in parallel.
t
Absolutely! A single SIP trunk in LiveKit can comfortably handle multiple simultaneous calls by creating separate rooms for each one. This is made possible through dispatch rules, which help route incoming SIP calls to the right LiveKit rooms. For instance, you can set up an Individual Dispatch rule with a room prefix like
call
. This way, each incoming call will generate its own unique room, such as
call_+1234567890
. This setup ensures every call gets its own space, even when several calls happen at once. If you'd like, I’m here to help you with setting up these dispatch rules or configuring your SIP trunk to make this work smoothly! Sources: Inbound calls with Twilio Voice | LiveKit Docs | SIP overview | LiveKit Docs | protobufs/livekit_sip.proto
h
and one sip can handle call for multiple businesses also
t
Absolutely! A single SIP trunk in LiveKit can comfortably handle calls for multiple businesses and route them to separate rooms. This is made possible through dispatch rules and smart routing logic based on: • Phone Numbers: The trunk can accept calls to multiple numbers, and dispatch rules can route calls based on the called number. • PIN Codes: Calls can be directed to different rooms based on a PIN entered by the caller. • SIP Headers: Custom SIP headers (e.g.,
X-*
) can be mapped to participant attributes and used to route calls to specific workflows or rooms. For instance, you can set up an Individual Dispatch rule that creates a new room for each call, with room names prefixed according to the business (like
business1_call_+1234567890
). This way, a single SIP trunk can serve multiple businesses while keeping their calls nicely separated. If you'd like, I’m here to help you with the configuration—just let me know! Sources: livekit-protocol/src/livekit.rs | Accepting inbound calls | LiveKit Docs | SIP APIs | LiveKit Docs | protobufs/livekit_sip.proto | SIP overview | LiveKit Docs
h
do you support some other telephony provider beside twilio
t
Absolutely! LiveKit does support telephony providers beyond Twilio for SIP integration. Our SIP SDK is built to work smoothly with any SIP-compliant provider, and we've officially tested it with the following: • Twilio • Telnyx • Exotel • Plivo • Wavix If you're thinking about using a different SIP provider, it should still work well as long as it follows SIP standards. Please feel free to reach out if you'd like any guidance or have questions about a specific provider—I’m here to help! Sources: SIP overview | LiveKit Docs | HD voice for SIP | LiveKit Docs
h
How can i create and edit trunks from code in livekit
t
I'm happy to guide you through creating and editing SIP trunks programmatically in LiveKit using the server SDKs. Here's a simple walkthrough to help you get started: Creating SIP Trunks If you'd like to create an inbound SIP trunk, you can use this example:
Copy code
// Node.js Example
await sipClient.createSipInboundTrunk(
  "My Inbound Trunk",
  ["+1234567890"],
  { krispEnabled: true }
);
For outbound SIP trunks, here's how you can do it:
Copy code
// Node.js Example
await sipClient.createSipOutboundTrunk(
  "My Outbound Trunk",
  "sip.provider.com",
  ["+0987654321"]
);
Editing SIP Trunks If you need to update an existing SIP trunk, simply use the update API like this:
Copy code
// Node.js Example
await sipClient.updateSipInboundTrunk(
  "trunk_id",
  {
    name: "Updated Name",
    authUsername: "new_user",
    authPassword: "new_pass"
  }
);
Authentication Just a quick note: all these operations require SIP admin permissions and authentication with your LiveKit API key and secret. If you'd like, I’m here to help with more examples or answer any questions you have, maybe in a specific programming language you prefer. Just let me know! Sources: Creating SIP Inbound Trunks and Dispatch Rules with Python SDK | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki | packages/livekit-server-sdk/src/SipClient.ts | src/main/kotlin/io/livekit/server/SipServiceClient.kt | cmd/lk/sip.go
h
tell me one thing if i add new phone number for each business login in my app , so is there any limit to it . Is there nay way such that i dont need to add number each time .someting dynamics
t
I'm happy to share that there's no set limit on how many phone numbers you can add to a LiveKit SIP inbound trunk. To make things easier and avoid adding a new number every time, LiveKit actually supports a wildcard configuration for SIP routing. By setting the
numbers
field in the SIP trunk to a wildcard (like
*
) or simply leaving it empty, your trunk can accept calls to any phone number without the need to register each one individually. This way, you can enjoy dynamic routing without the hassle of manually adding numbers for every business. If you'd like, I’d be more than happy to guide you through setting up this wildcard configuration or help you manage routing rules dynamically to fit your needs. Just let me know! Sources: livekit-api/src/services/sip.rs | livekit/livekit_sip.pb.go | SIP inbound trunk | LiveKit Docs | SIP outbound trunk | LiveKit Docs
h
so if i go with twilio can you give me step wise setup for everthing twilio and livekit . take a example let say x busienss login
t
I’m excited to guide you through setting up Twilio with LiveKit for SIP calls, including how to enable dynamic routing for new businesses. Let’s take it step-by-step together: Step 1: Environment Configuration First, create a
.env.local
file and add these variables:
Copy code
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret
LIVEKIT_URL=your_livekit_server_url
LIVEKIT_SIP_URI=your_livekit_sip_uri
TWILIO_PHONE_NUMBER=your_twilio_phone_number
TWILIO_ACCOUNT_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_SIP_USERNAME=your_twilio_sip_username
TWILIO_SIP_PASSWORD=your_twilio_sip_password
Step 2: Twilio SIP Trunk Setup 1. Let’s create a SIP trunk in Twilio:
Copy code
trunk = await twilioClient.trunking.v1.trunks.create({
  friendlyName: 'LiveKit SIP trunk',
});
2. Next, configure the trunk with an origination URL that points to your LiveKit SIP URI:
Copy code
originationUrl = await trunk.originationUrls().create({
  weight: 1,
  priority: 1,
  friendlyName: 'LiveKit SIP URI',
  sipUrl: sipUri,
  enabled: true,
});
3. Then, associate your Twilio phone number with this trunk:
Copy code
phoneNumber = await trunk.phoneNumbers().create({
  phoneNumberSid: incomingPhoneNumber.sid,
});
Step 3: LiveKit Inbound Trunk Setup 1. Now, create an inbound SIP trunk in LiveKit:
Copy code
trunk = await sipClient.createSipInboundTrunk(
  'My Inbound Trunk',
  [TWILIO_PHONE_NUMBER],
  {
    auth_username: TWILIO_SIP_USERNAME,
    auth_password: TWILIO_SIP_PASSWORD,
  },
);
2. Then, set up a dispatch rule for dynamic routing:
Copy code
dispatchRule = await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'call',
  },
  {
    name: 'Dynamic Dispatch Rule',
    trunkIds: [trunk.sipTrunkId],
  },
);
Step 4: Dynamic Routing for New Businesses This dispatch rule is a key part—it makes sure every incoming call creates a new room dynamically, with names prefixed like
call_+1234567890
. This way, your routing stays smooth and automatic. Step 5: Run Setup Scripts 1. Go ahead and run the Twilio setup script:
npm run setup:twilio
2. Then run the LiveKit setup:
npm run setup:livekit
Step 6: Start Your Agent Finally, start the SIP agent to handle your calls:
npm run agent
This setup is designed to make your life easier by automating dynamic routing for each business without needing manual steps. If anything feels unclear or you want me to walk you through any part again, just let me know—I’m here to help! Sources: README.md
h
how to give custom information to livekit agent
t
I'm happy to guide you on how to pass custom information to a LiveKit agent during a SIP call. You can do this in a couple of ways: 1. Job Metadata: You can include structured data, like JSON, in the job metadata when dispatching an agent. This metadata is then available in the agent's
entrypoint
function via
job.metadata
. For instance, you might pass user details like this:
{ "userId": "12345", "name": "John Doe" }
2. Participant Attributes: Another option is to attach custom attributes directly to the SIP participant: ◦ Via Dispatch Rules: You can define these attributes right in the SIP dispatch rule configuration. ◦ Using SIP Headers: You can map custom
X-*
SIP headers (like
X-Custom-ID: 12345
) to participant attributes using
headers_to_attributes
. These will then be accessible as
sip.h.x-custom-id
. Once you've passed this data, the agent can easily retrieve it inside the
entrypoint
function. Here's a quick example:
Copy code
const metadata = job.metadata; // Access job metadata
const participantAttributes = participant.attributes; // Access participant attributes
If you'd like, I'm here to help you step-by-step with implementing this. Just let me know! Sources: Job lifecycle | LiveKit Docs | SIP participant | LiveKit Docs | rpc/sip.pb.go | Agent dispatch | LiveKit Docs
h
but we are trying to host single agent for all busienss. so , can we suply that agent with metadata and all such that when agent call particular number it work with single trunk and agent for all business.
t
Absolutely! A single LiveKit agent can definitely manage calls for multiple businesses by using metadata along with a single SIP trunk. Let me walk you through how you can set this up: 1. Use Metadata: You can pass structured metadata (like JSON) when dispatching an agent to identify which business or context each call belongs to. This metadata is available in the agent's
JobContext
and can include important details such as the business ID, name, or any preferences. 2. Single SIP Trunk: By configuring a single SIP trunk to handle all calls, you can simplify things. Then, use dispatch rules to route calls dynamically based on things like phone numbers, PIN codes, or other criteria. 3. Dispatch Rules: These rules help you control how calls are routed to different rooms. For instance, you could route calls from different businesses into separate rooms or workflows, all while using the same trunk. 4. Agent Logic: The agent can use the metadata provided during dispatch to decide how to behave for each business. For example, it might determine which number to call or the best way to handle the interaction based on that information. This approach allows one agent to smartly handle calls for multiple businesses without needing separate trunks or agents. If you'd like, I'm here to help you set this up or answer any questions you have! Sources: Agent dispatch | LiveKit Docs | SIP APIs | LiveKit Docs | SIP overview | LiveKit Docs
h
but suppose certain number call a numer on twilio and sip trunk on twilio is conected to single inbound trunk in livekit , what we have to do such that multiple request at send time is route to sepeprate room and with business individual metadata to agent . explain me in detail what us dispatch rule and its use
t
Hi there! I’d love to help you understand how a dispatch rule in LiveKit works and how it can make managing multiple simultaneous SIP calls easier, especially when you want to include individual metadata for each call. What is a Dispatch Rule? Think of a dispatch rule as the guide that directs incoming SIP calls to the right LiveKit rooms. For instance, a caller dispatch rule (individual) will create a brand new room for each SIP caller. The room name is usually based on the caller's phone number, and you can even add a prefix to keep things neat (like
business1_call_+1234567890
). How to Use Dispatch Rules for Your Scenario: 1. Route Calls to Separate Rooms: By setting the dispatch rule with
type: 'individual'
, each incoming call will dynamically get its own room. This way, calls from different businesses stay nicely separated. 2. Attach Metadata: You can include custom metadata in the dispatch rule for each call, such as business ID or name. This information is then available to the agent when they join the room, making it easier to personalize the experience. 3. Dynamic Room Naming: Using a
roomPrefix
helps keep your rooms organized. For example, calls for Business A could be routed to rooms that start with
businessA_call
. Example Dispatch Rule Configuration:
Copy code
dispatchRule = await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'business_call',
  },
  {
    name: 'Dynamic Dispatch Rule',
    trunkIds: [trunk.sipTrunkId],
  },
);
Agent Metadata: All the metadata you define in the dispatch rule is accessible to the agent through the
JobContext
. This really helps the agent handle calls with the right business-specific details. If you have any questions or want a hand setting up your dispatch rules or metadata, just let me know—I’m here to help! Sources: SIP dispatch rule | LiveKit Docs | protobufs/livekit_sip.proto | livekit-protocol/src/livekit.rs
h
but how to attach aditional information of business to agent .
t
I'm happy to guide you through how you can attach business-specific information to a LiveKit agent during SIP call handling. Here are some friendly ways to do it: 1. Participant Attributes: You can set custom key-value pairs in the
participant_attributes
field of a SIP dispatch rule. These attributes will be inherited by SIP participants and are accessible to the agent. For example:
{ "business_id": "123", "department": "sales" }
2. Participant Metadata: Another option is to attach structured data (like JSON) to the
participant_metadata
field in the dispatch rule. This metadata is stored on the participant and can provide detailed business context. 3. Job Metadata: When you dispatch an agent explicitly, you can pass job metadata (such as JSON) to the agent’s
JobContext
. This is great for sharing session-specific or business-specific information. 4. SIP Headers to Attributes Mapping: You can also configure your SIP trunk to map custom
X-*
SIP headers to participant attributes. For instance, a header like
X-Business-Unit: sales
can be mapped to
sip.h.x-business-unit
. Accessing the Data: When you’re working on the agent’s side, you can retrieve: • Job Metadata: Via
JobContext.Metadata
. • Participant Attributes: Through the participant object in the room. If you’d like, I’m here to help you implement any of these methods or answer any questions you might have! Sources: Agent dispatch | LiveKit Docs | SIP participant | LiveKit Docs | SIP dispatch rule | LiveKit Docs | Job lifecycle | LiveKit Docs | rpc/sip.pb.go
h
so we use attached metadata in diapatch rule to get informeation at agent level
t
Absolutely, you can use metadata attached in the dispatch rule to share important information at the agent level. This metadata can include structured data like JSON with business-specific details, and the agent will have access to it during execution. Here’s how you can set this up: 1. Attach Metadata in Dispatch Rule: You’ll want to define the metadata within the dispatch rule configuration. For example:
Copy code
dispatchRule = await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'business_call',
    metadata: JSON.stringify({ business_id: '123', department: 'sales' })
  },
  {
    name: 'Business Dispatch Rule',
    trunkIds: [trunk.sipTrunkId],
  },
);
2. Access Metadata in the Agent: Then, in your agent’s code, you can retrieve the metadata from the
JobContext
while the call is running:
Copy code
const metadata = job.metadata; // Access metadata passed via dispatch rule
console.log(metadata.business_id); // Example usage
This way, your agent will have all the relevant business details needed to handle the call smoothly. If you have any questions or need a hand with anything else, just let me know—I’m here to help!
h
no but i am talking about large infromation which agent may need to answer on call questiona
t
I'm glad you're looking to provide large business-specific information to a LiveKit agent to help answer call questions! Here are some friendly approaches you can consider: 1. Retrieval-Augmented Generation (RAG): This method lets the agent search a private knowledge base in real time and pull out the most relevant information dynamically. It works wonderfully for large datasets like FAQs or product details. ◦ Steps: i. Start by preparing your business data as text documents or paragraphs. ii. Next, convert that data into embeddings using a model like
text-embedding-3-small
. iii. Then, store those embeddings in an Annoy index file and save the metadata in a pickled file. iv. Finally, load the RAG handler in the agent so it can retrieve the right info during calls. ◦ Example:
Copy code
rag_handler = RAGHandler(
    index_path="vdb_data",
    data_path="business_info.pkl",
    thinking_style="message"
)
rag_handler.start(agent)
1. Direct Large Context Loading: If your dataset is smaller, you might find it easier to load the information directly into the agent’s instructions. ◦ Steps: i. Save your business data in a text file. ii. Read that file and include its content when initializing the agent. iii. For better handling, use a large-context LLM like Google Gemini 2.0 Flash. ◦ Example:
Copy code
with open("business_handbook.txt", "r", encoding="utf-8") as f:
    handbook_text = f.read()

agent = Agent(
    instructions=f"""
        You are a customer support assistant.
        Use the following company handbook to answer questions:

        {handbook_text}
    """,
    llm=google.LLM(model="gemini-2.0-flash")
)
1. Session-Specific Metadata: You can also pass dynamic data like user profiles or order history at the start of each session using job metadata, room metadata, or participant attributes. This helps tailor the experience even more. Best Practices: If you'd like, I’d be more than happy to help you implement RAG or direct context loading for your business data. Just let me know! Sources: pipeline-llm/large_context.py | agent_extensions/agent_extensions/rag/handler.py | External data and RAG | LiveKit Docs
h
no but i am asking in case of one agent only for all business , we need sum metadata in dispatch rule such that we can map important data at agent level . we can send all the detaial and stuff if bussiness in dispatch rulw
t
Absolutely, you can use metadata in the dispatch rule to share important business-specific details with a single agent handling calls for all your businesses. This metadata can include structured information (like JSON) about each business, which the agent can easily access during execution. Here’s how you can set it up: 1. Attach Metadata in the Dispatch Rule: Start by defining the metadata right in your dispatch rule configuration. For example:
Copy code
dispatchRule = await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'business_call',
    metadata: JSON.stringify({
      business_id: '123',
      business_name: 'ABC Corp',
      support_info: 'Contact support@abccorp.com for details',
      faq: '<BUSINESS_FAQ_URL>'
    })
  },
  {
    name: 'Business Dispatch Rule',
    trunkIds: [trunk.sipTrunkId],
  },
);
2. Access Metadata in the Agent: Then, in your agent’s code, you can retrieve this metadata from the
JobContext
during execution like this:
Copy code
const metadata = job.metadata; // Access metadata passed via dispatch rule
console.log(metadata.business_name); // Example usage
This method lets you smoothly pass all the key business details to your agent, so it’s fully equipped to handle calls for each business accurately. If you’d like, I’m here to help you through any part of this setup—just let me know!
h
ok so we can access metadata in agent and use it to fetch adtional data from database
t
Absolutely! You can definitely access the metadata within the agent and use it to fetch additional data from a database. The metadata you pass through the dispatch rule can include important identifiers like
business_id
or other relevant details, which the agent can then use to query a database or API for more information. Here’s a friendly example workflow to guide you: 1. Pass Metadata in Dispatch Rule: Include key identifiers in the metadata, such as:
Copy code
metadata: JSON.stringify({
  business_id: '123',
  business_name: 'ABC Corp'
})
2. Access Metadata in the Agent: You can retrieve the metadata in the agent’s
JobContext
like this:
Copy code
const metadata = job.metadata;
const businessId = metadata.business_id;
3. Fetch Additional Data: Then, use that metadata to query a database or API for more details:
Copy code
const businessDetails = await database.getBusinessDetails(businessId);
console.log(businessDetails);
This method helps keep your dispatch rule metadata light while giving your agent the flexibility to dynamically fetch and use extra data whenever needed. If you’d like, I’m here to help you set up the database queries or API integration—just let me know!
h
so if livekit trunk can accept all the call , how will dispatch rule know from which name twilio is calling or trying to connect
t
LiveKit helps you identify the source of calls over a single Twilio SIP trunk by using SIP INVITE metadata, Twilio-specific attributes, and dispatch rule configurations. Let me walk you through how this works: 1. Trunk Matching: When a call comes in, LiveKit matches it to a trunk by checking: ◦ Called Number: It looks for numbers you've set up in the trunk’s
numbers
list. ◦ Source IP Address: It matches IPs listed in the trunk’s
allowed_addresses
(like Twilio’s IP range). 1. Dispatch Rule Application: After matching the trunk, dispatch rules help decide how the call gets routed. These rules can use: ◦ Called Number: To route calls based on the number dialed. ◦ Custom SIP Headers: You can map headers (like
X-Call-Source
) to participant attributes for more tailored routing. ◦ Twilio-Specific Attributes: Attributes such as
sip.twilio.callSid
and
sip.twilio.accountSid
are available automatically. 1. Custom Header Mapping: You have the option to configure the trunk to map custom SIP headers to participant attributes. For example:
Copy code
{
  "headers_to_attributes": {
    "X-Call-Source": "source_label",
    "X-Department-ID": "caller.department"
  }
}
Example: If your single trunk handles multiple numbers, you can set up dispatch rules to route calls dynamically like this: • Calls to
+1234567890
are directed to a support room. • Calls to
+1234567891
create new sales rooms with a prefix like
sales-
. This way, even with just one trunk, LiveKit can clearly distinguish and route calls based on where they come from, their context, and the metadata. If you’d like, I’m here to help you set this up or answer any questions you have! Sources: SIP dispatch rule | LiveKit Docs | protobufs/livekit_sip.proto | pkg/service/ioservice_sip.go | SIP inbound trunk | LiveKit Docs | SIP participant | LiveKit Docs
h
but we are creating only one trunk for all busienss so that trunk will not have any specified number
t
I'm glad you're exploring how to use a single SIP trunk for all your businesses without specifying numbers! You can definitely route calls dynamically using dispatch rules and metadata. Let me walk you through it: 1. Wildcard Trunk Configuration: You can configure your SIP trunk to accept calls to any number by simply leaving the
numbers
field empty or using a wildcard (
*
). This way, your trunk will be ready to handle all incoming calls, no matter the dialed number. 2. Custom SIP Headers: With Twilio, you have the flexibility to send custom SIP headers like
X-Business-ID
or
X-Source
with each call. These headers can then be mapped to participant attributes in your trunk configuration:
Copy code
{
  "headers_to_attributes": {
    "X-Business-ID": "business_id",
    "X-Source": "source_label"
  }
}
3. Dispatch Rules: Next, you can set up dispatch rules that dynamically route calls based on those mapped attributes. For instance, you might route calls to rooms that start with the business ID:
Copy code
dispatchRule = await sipClient.createSipDispatchRule(
  {
    type: 'individual',
    roomPrefix: 'business_',
    metadata: JSON.stringify({
      routing_info: 'Dynamic routing based on business ID'
    })
  },
  {
    name: 'Dynamic Business Routing',
    trunkIds: [trunk.sipTrunkId],
  },
);
4. Agent Access: Your agents will be able to access the metadata and participant attributes, helping them understand the business context and handle each call just right. This setup is a wonderful way to have a single trunk smoothly manage calls for multiple businesses, even without predefined numbers. If you have any questions or want me to clarify anything, please don’t hesitate to ask—I’m here to help!
h
can livekit automatically know which number is calling , how will twilio know about business_id and all
t
Hi there! I wanted to share how LiveKit can automatically identify the calling number from the SIP INVITE request, which includes the caller's number in the
from.User
field. That’s super handy! However, for any additional business-specific information like
business_id
, Twilio will need to provide this data explicitly. Here’s how Twilio can share that business information with you: 1. Custom SIP Headers: Twilio can send custom headers (like
X-Business-ID
) with each call. These headers can carry business-specific details such as
business_id
,
department
, or anything else you might need. You can then configure LiveKit to map these headers to participant attributes using the
headers_to_attributes
field in your trunk configuration. 2. Mapping Example:
Copy code
{
  "headers_to_attributes": {
    "X-Business-ID": "business_id",
    "X-Department": "department"
  }
}
3. Dynamic Routing: Once you’ve mapped the headers, you can use dispatch rules to route calls dynamically or pass that information along to your agents for even better handling. This way, Twilio provides the important business context, and LiveKit can use it to make routing and agent interactions smoother. If you'd like, I’m here to help you set up those custom headers or guide you through mapping them in LiveKit—just let me know!
h
but how will twilio know business_id
t
Twilio can help identify the
business_id
based on the phone number the caller dials. Each business can have its own unique Twilio phone number, so when a call comes in to that number, Twilio can connect it to the right
business_id
. Here’s a simple way to set this up: 1. Assign Unique Numbers: Give each business in your application a unique Twilio phone number. 2. Set Up Twilio Webhooks: Configure Twilio to send a webhook whenever a call is received. This webhook will include the dialed number (
To
) and other important call details. 3. Map Numbers to Business IDs: In your webhook handler, match the dialed number to the correct
business_id
using your database or a configuration file. 4. Send Custom SIP Headers: When you forward the call to LiveKit through the SIP trunk, include the
business_id
as a custom SIP header (for example,
X-Business-ID
). Here’s how it could work: A caller dials
+1234567890
→ Twilio’s webhook recognizes this number belongs to Business A → Twilio adds
X-Business-ID: A
to the SIP headers → LiveKit uses this info to route the call and connect the right agent. If you’d like, I’m here to help you with setting up the Twilio webhook or mapping those numbers to business IDs. Just let me know!
h
is there any alternative way
t
If assigning unique phone numbers to each business isn’t quite doable right now, no worries! Here are some friendly alternatives to help you associate a
business_id
with incoming calls: 1. Use a Single Twilio Number with IVR: You can set up an Interactive Voice Response (IVR) system in Twilio. When someone calls, they’ll be able to choose their business or department by pressing keys. That choice can then be linked to a
business_id
and sent to LiveKit as a custom SIP header. 2. Caller-Specific Identification: If you already know the caller’s phone number, you could keep a handy database that matches caller numbers to their
business_id
. When a call comes in, Twilio can check the number and include the right
business_id
in the SIP headers. 3. Dynamic Input via Twilio Studio: Twilio Studio lets you create a flow where callers enter a unique identifier—like an account number or business code—using their keypad or voice. This identifier can then be tied to a
business_id
and sent along to LiveKit. 4. Custom Twilio Application: You might also consider developing a custom Twilio app that figures out the
business_id
based on the call’s context—like the time of day, location, or other info—and includes it in the SIP headers. These options give you flexible ways to connect calls to a
business_id
without needing a unique phone number for each business. If you’d like, I’m here to help with more details on any of these ideas!
h
how can i make such that the agent voice matches my voice
t
I'm happy to help you customize a LiveKit agent's voice to match exactly what you're looking for! You have two great options: using default voices or going for custom voices through external TTS providers. Let’s walk through both together: 1. Default Voices: LiveKit offers some wonderful predefined voices from providers like Cartesia, ElevenLabs, and Rime. You can easily pick a voice by specifying its ID in the TTS configuration. Here’s a simple example:
Copy code
from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-2",
    voice="f786b574-daa5-4673-aa0c-cbe3e8534c02"  # Voice ID
)
2. Custom Voices: If you’re interested in voice cloning or creating a truly unique voice, you can use a provider-specific plugin (like Cartesia or ElevenLabs) with your own API account. This way, you can create or use cloned voices tailored just for you. Here’s how you can get started:Here’s a quick example to guide you:
Copy code
import requests
import os

headers = {
    "X-API-Key": os.getenv("CARTESIA_API_KEY"),
    "Content-Type": "application/json",
}
response = requests.get("https://api.cartesia.ai/voices", headers=headers)
if response.status_code == 200:
    voices = response.json()
    custom_voice = voices[0]["embedding"]
    tts = cartesia.TTS(model="sonic-2", voice=custom_voice)
◦ Create an account with your chosen TTS provider (for example, Cartesia or ElevenLabs). ◦ Install the plugin you need (for example,
pip install livekit-plugins-cartesia
). ◦ Authenticate with your API key and retrieve your custom voices. If you’d like, I’m here to walk you through setting up voice cloning or help you pick the perfect voice. Just let me know how I can assist! Sources: Cartesia TTS | LiveKit docs | ElevenLabs TTS | LiveKit Docs | pipeline-tts/tts_comparison/README.md | Text-to-speech (TTS) models | LiveKit Docs
h
why am i getting this error ₹₹₹ [Tool Loader] ✓ Loaded tool: delete_calendar_event [Tool Loader] Successfully loaded 4 tools for business ykkHtIq4UyasU16IU6X1hZnxQtBC9gtr Loaded 4 tools for business ykkHtIq4UyasU16IU6X1hZnxQtBC9gtr Available tools: get_calendar_events, create_calendar_event, update_calendar_event, delete_calendar_event ==================== === TTS CONFIGURATION === Using TTS model: cartesia/sonic-2:c9ed5cbe-97fb-48f5-99e1-9388cf5df17e Voice source: Cloned voice ======================== [AgentStateChanged] listening [185427.146] INFO (79831): participantValue.trackPublications participantValue: "test-user-1764077060960" trackPublications: [ { "info": { "sid": "TR_AMHuecZwewGac7", "name": "", "kind": "KIND_AUDIO", "source": "SOURCE_MICROPHONE", "simulcasted": false, "width": 0, "height": 0, "mimeType": "audio/opus", "muted": false, "remote": true, "encryptionType": "NONE", "audioFeatures": [ "TF_NO_DTX", "TF_AUTO_GAIN_CONTROL", "TF_ECHO_CANCELLATION", "TF_NOISE_SUPPRESSION" ] }, "ffiHandle": {}, "subscribed": true, "track": { "info": { "sid": "TR_AMHuecZwewGac7", "name": "", "kind": "KIND_AUDIO", "streamState": "STATE_ACTIVE", "muted": false, "remote": true }, "ffi_handle": {} } } ] lengthOfTrackPublications: 1 [185427.905] WARN (79831): failed to recognize speech, retrying in 0.1s tts: "inference.STT" attempt: 1 error: { "body": null, "retryable": true, "name": "APIConnectionError" } [185428.009] WARN (79831): failed to recognize speech, retrying in 2000s tts: "inference.STT" attempt: 2 error: { "body": null, "retryable": true, "name": "APIConnectionError" } [185430.117] WARN (79831): failed to recognize speech, retrying in 2000s tts: "inference.STT" attempt: 3 error: { "body": null, "retryable": true, "name": "APIConnectionError" } [AgentSessionError] APIConnectionError: Error connecting to LiveKit WebSocket at WebSocket.onError (/Users/priyanshutiwari/Desktop/mission/saas/agent-starter-node/node_modules/@livekit/agents/src/inference/utils.ts4816) at Object.onceWrapper (nodeevents639:26) at WebSocket.emit (nodeevents524:28) at emitErrorAndClose (/Users/priyanshutiwari/Desktop/mission/saas/agent-starter-node/node_modules/ws/lib/websocket.js104113) at process.processTicksAndRejections (nodeinternal/process/task queues82:21) { body: null, retryable: true } [185432.201] ERROR (79831): AgentSession is closing due to unrecoverable error type: "stt_error" label: "inference.STT" recoverable: false error: { "body": null, "retryable": true, "name": "APIConnectionError" } [185432.202] INFO (79831): mainTask: draining and no more speech tasks [185432.202] INFO (79831): AgentActivity mainTask: exiting [185432.206] INFO (79831): AgentSession closed reason: "error" error: { "type": "stt_error", "timestamp": 1764077072199, "label": "inference.STT", "error": { "body": null, "retryable": true, "name": "APIConnectionError" }, "recoverable": false } [185432.206] ERROR (79831): failed to recognize speech after 4 attempts jobID: "AJ_xAeGb72pQSWG" err: { "type": "APIConnectionError", "message": "failed to recognize speech after 4 attempts", "stack": APIConnectionError: failed to recognize speech after 4 attempts at SpeechStream.mainTask (/Users/priyanshutiwari/Desktop/mission/saas/agent-starter-node/node_modules/@livekit/agents/src/stt/stt.ts20619) at process.processTicksAndRejections (nodeinternal/process/task queues95:5) "body": null, "retryable": false, "name": "APIConnectionError" } ₹₹₹
t
The
APIConnectionError
in LiveKit STT inference typically occurs due to network or connection issues when establishing a WebSocket connection to the LiveKit server. Here are the common causes and resolutions: Causes: • Network connectivity problems: Unstable or interrupted internet connection. • WebSocket connection failure: Issues during the WebSocket handshake or setup. • Invalid URL scheme: Malformed or inaccessible
base_url
. • DNS resolution failures: The server may be unreachable due to DNS or network issues. Resolutions: 1. Verify network connectivity: Ensure stable internet access and that the LiveKit server is reachable. 2. Check API credentials: Confirm that the
api_key
and
api_secret
are valid. 3. Validate base URL: Ensure the
base_url
is correct (e.g., `wss://agent-gateway.livekit.cloud/v1`). 4. Retry logic: Implement retry attempts with exponential backoff to handle transient network issues. 5. Firewall or proxy settings: Ensure WebSocket traffic (port 443 or WSS port) is allowed through firewalls. Let me know if you need help troubleshooting further or implementing these fixes! Sources: agents/src/inference/utils.ts | AI Service Plugin Ecosystem | livekit/livekit_composite | DeepWiki | livekit-agents/livekit/agents/inference/tts.py
h
I have a telephony voice agent , it already have metadata fetching. Now i want to add Rag in it such that agent can search larges docs. can someone suggest good option live what to use langchain, llamaindex or something other, and which vector db and embedding model to use .
t
To add Retrieval-Augmented Generation (RAG) to your LiveKit telephony voice agent, here are the best options for frameworks, vector databases, and embedding models: 1. Frameworks: ◦ LlamaIndex: Recommended for RAG implementations in LiveKit. It supports flexible retrieval workflows, including chat engines and custom query functions. ◦ LangChain: Use the LangChain plugin to integrate LangGraph workflows into your agent. This enables advanced RAG workflows with stateful agents and external data retrieval. 1. Vector Databases: ◦ Annoy: Efficient for similarity search and supported natively in LiveKit examples. ◦ Other options like Pinecone or Weaviate can be integrated via custom code if needed. 1. Embedding Models: ◦ OpenAI Embeddings: Use
text-embedding-3-small
for semantic embeddings (dimension 1536). ◦ Other models compatible with LangChain or LlamaIndex can also be used. 1. RAG Implementation: ◦ Preprocess your data into embeddings and store it in a vector database (e.g., Annoy). ◦ Query the database during inference to retrieve relevant context and inject it into the agent’s responses. Example Workflow: Use LlamaIndex to preprocess data and query it dynamically:
Copy code
builder = RAGBuilder(index_path="vdb_data", data_path="my_data.pkl")
await builder.build_from_file("raw_data.txt")
Let me know if you need help setting up RAG with any of these tools! Sources: examples/voice_agents/llamaindex-rag/README.md | LangChain integration guide | LiveKit docs | docs/examples/rag/README.md | agent_extensions/agent_extensions/rag/builder.py | External data and RAG | LiveKit docs
h
can i use chromadb
t
ChromaDB is not explicitly mentioned in LiveKit's documentation or examples, but you can use it as a vector database for RAG in your telephony voice agent. LiveKit supports integrating external Python packages and custom logic, so ChromaDB can be implemented as a custom vector store. Steps to Use ChromaDB: 1. Install ChromaDB: Add the ChromaDB package to your environment:
pip install chromadb
2. Build a ChromaDB Collection: Index your documents with embeddings (e.g., OpenAI embeddings):
Copy code
import chromadb
from chromadb.config import Settings

client = chromadb.Client(Settings())
collection = client.create_collection("my_collection")

# Add documents with embeddings
collection.add(
    documents=["Document 1", "Document 2"],
    metadatas=[{"id": 1}, {"id": 2}],
    embeddings=[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]
)
3. Query the Collection: Retrieve relevant context during inference:
Copy code
results = collection.query(
    query_embeddings=[[0.1, 0.2, 0.3]],
    n_results=1
)
print(results)
4. Integrate with LiveKit: Use the retrieved context in your agent’s pipeline, either via a function tool or the
on_user_turn_completed
hook. Let me know if you’d like detailed guidance on integrating ChromaDB with your LiveKit agent! Sources: docs/examples/rag/rag_db_builder.py | External data and RAG | LiveKit docs
h
[Tool Loader] Error loading tools: module 'livekit.agents.llm' has no attribute 'ai_callable' Loaded 0 tools for business ykkHtIq4UyasU16IU6X1hZnxQtBC9gtr
t
The error
module 'livekit.agents.llm' has no attribute 'ai_callable'
occurs because the
ai_callable
decorator is not a publicly exported attribute in the current version of the LiveKit Agents SDK. Instead, you should use the
@function_tool
decorator to define callable functions for your tools. Resolution: 1. Replace
@ai_callable
with `@function_tool`:
Update your code to use the correct decorator. For example:
Copy code
from livekit.agents import function_tool

@function_tool()
def get_weather(location: str) -> dict:
    """Get the current weather in a given location.
    
    Args:
        location: The city and state, e.g. San Francisco, CA
    """
    # Implementation here
    return {"weather": "sunny", "temperature": 70}
2. Ensure SDK is Up-to-Date: Update to the latest version of the LiveKit Agents SDK to ensure compatibility with current features and practices. Let me know if you need further assistance with updating your tools or resolving this issue! Sources: livekit-agents/livekit/agents/voice/generation.py | Tool definition and use | LiveKit docs