LiveKit SIP With Twilio or Telnyx: Trunks, Dispatch Rules and a Phone Agent

14 min read

LiveKit SIP With Twilio or Telnyx: Trunks, Dispatch Rules and a Phone Agent

The problem

You have a voice agent that works in a browser. Now it has to answer a real phone number, and maybe call people too. Between the phone network and your agent sit two pieces of config that are easy to get subtly wrong: the SIP trunk at your carrier, and the matching trunk and routing objects inside LiveKit. When they disagree, the call fails with a terse SIP code, or it connects and nobody hears anything.

This post walks through the LiveKit side and the carrier side in the order you would set them up, using the current docs.livekit.io pages (all fetched on 26 Nov 2026). Every snippet below is an example taken from or adapted from a named doc page. I have not run this setup myself, so treat it as a map of what the docs say, not a field report.

If SIP, RTP and trunks are new to you, start with how a phone call reaches an AI voice agent. Short version: SIP (Session Initiation Protocol) is the signaling that sets up and ends calls, RTP (Real-time Transport Protocol) carries the audio, and a SIP trunk is the connection between your system and a carrier that owns phone numbers.

This is part 12 of the Voice AI over SIP series. If a term is new to you, the glossary defines it in plain language and links to the part that covers it.

What LiveKit SIP is

LiveKit's telephony intro page describes three moving parts: a phone number (a DID, Direct Inward Dialing number) from LiveKit Phone Numbers or a third-party SIP provider, the LiveKit server that manages trunks and dispatch rules and creates rooms, and LiveKit SIP, the service that answers SIP requests, checks trunk authentication and matches dispatch rules.

A caller becomes a SIP participant: an ordinary room participant with extra SIP attributes. For inbound calls LiveKit creates it automatically. For outbound calls you create it with the CreateSIPParticipant API.

There are two ways to run it:

  • LiveKit Cloud. The intro page says LiveKit SIP is ready to use with your project without any extra configuration. Your project gets a SIP URI.
  • Self-hosted. The SIP service is a separate open source server, livekit/sip (Apache-2.0), that you deploy next to your own LiveKit server. Its README says it talks to the LiveKit server over Redis, which also stores session state, and that it needs a public IP.

The same page lists what is supported: SIP over UDP, TCP and TLS, DTMF (RFC 2833 / RFC 4733), cold transfer with REFER, warm transfer, SIP OPTIONS and SRTP. SIP REGISTER is listed as not supported. That last point matters when choosing a carrier: a trunk that only works by having your side register to it, like a softphone, does not fit. You want a trunk that sends calls to a fixed address (an "origination URI") and accepts calls from you by IP or digest credentials.

Step 1: find your LiveKit SIP endpoint

From the SIP trunk setup page: your SIP endpoint is your project's SIP URI without the sip: prefix. The CLI shows your project ID with lk project list --json. A project ID like p_vjnxecm0tjk gives the URI sip:vjnxecm0tjk.sip.livekit.cloud, so the endpoint is vjnxecm0tjk.sip.livekit.cloud.

That endpoint is global. The region pinning page describes a regional form, {sip_subdomain}.{region_name}.sip.livekit.cloud, where the region name is one of eu, india, sa, us, japan, aus or canada. A regional endpoint sends traffic only to nodes in that region. We come back to this in the India section.

Step 2: point the carrier at LiveKit

Every carrier has its own word for "where do I send inbound calls". On Twilio Elastic SIP Trunking it is the origination URL. The LiveKit Twilio page gives the Twilio CLI version:

shell
twilio api trunking v1 trunks create \
  --friendly-name "My test trunk" \
  --domain-name "my-test-trunk.pstn.twilio.com"

twilio api trunking v1 trunks origination-urls create \
  --trunk-sid <twilio_trunk_sid> \
  --friendly-name "LiveKit SIP URI" \
  --sip-url "sip:<your SIP endpoint>;transport=tcp" \
  --weight 1 --priority 1 --enabled

The domain name must end in pstn.twilio.com. You then attach your number with twilio api trunking v1 trunks phone-numbers create --trunk-sid ... --phone-number-sid .... If you add a second origination URL as a fallback, the page explains that the lower priority value is tried first, and weight only spreads load between URLs with the same priority.

For outbound calls through Twilio, the same page has you create a credential list and attach it under Termination, Authentication, Credential Lists. Those username and password values must match what you later put on the LiveKit outbound trunk.

On Telnyx, the LiveKit Telnyx page (which notes you need a paid Telnyx account) uses the Telnyx API to create an FQDN connection with fields such as "ani_number_format": "+E.164", "dnis_number_format": "+e164", "transport_protocol": "TCP" and "anchorsite_override": "Latency", then an FQDN entry for your LiveKit endpoint with "port": 5060 and "dns_record_type": "a", and an outbound voice profile with "traffic_type": "conversational". The page recommends TCP.

Step 3: the inbound trunk

The inbound trunk tells LiveKit which incoming calls belong to you. The simplest version from the Inbound trunk page is a JSON file:

json
{
  "trunk": {
    "name": "My trunk",
    "numbers": ["+15105550100"]
  }
}

created with:

shell
lk sip inbound create inbound-trunk.json

Things the docs call out:

  • Number format. numbers takes E.164 numbers (a plus sign, country code, then the number) or a SIP username. A full SIP URI never matches. For Telnyx, the leading + only matches if the connection's destination number format is set to +E.164, which is why the FQDN connection above sets it.
  • Restricting callers. allowed_numbers limits which caller numbers are accepted, for example "allowed_numbers": ["+13105550100", "+17145550100"].
  • Restricting source IPs. allowed_addresses takes plain IPs or CIDR ranges such as 192.0.2.10 or 192.0.2.0/24. The page warns that this has to be enabled for your project by LiveKit support. Until then the list is saved but not enforced. Check this before you rely on it.
  • An empty numbers list is allowed only if you also set a username and password or allowed_addresses. The CLI reference says the same: a trunk must set numbers, allowed_addresses, or both auth_username and auth_password.
  • Auth depends on the carrier. The page notes Twilio Elastic SIP Trunking does not support username and password for inbound calls to you (TwiML does). With Twilio, inbound matching is by number.
  • Trunks are long-lived. In Cloud, changes take a few seconds to propagate, so do not create a trunk per call, and update a trunk rather than deleting and recreating it. The CLI reference adds that an update with a request file replaces the whole resource.

One optional field is worth knowing. ringing_timeout rejects the call with 486 Busy Here when it expires, and ringing_timeout_status lets you choose a different 4xx to 6xx code. For what each code means on the wire, use the SIP response code chart rather than a table here.

Step 4: the dispatch rule

A trunk accepts the call. A dispatch rule decides which room it lands in and which agent joins. The Dispatch rule page describes three rule types.

Individual gives every caller a new room. This is the example from the page, including the part that matters most for agents, room_config.agents:

json
{
  "dispatch_rule": {
    "rule": {
      "dispatch_rule_individual": {
        "room_prefix": "call-"
      }
    },
    "name": "My dispatch rule",
    "room_config": {
      "agents": [
        {
          "agent_name": "inbound-agent",
          "metadata": "job dispatch metadata"
        }
      ]
    }
  }
}
shell
lk sip dispatch create dispatch-rule.json

The page warns that individual room names include the caller's phone number, which is personal data, and that it is not removed by PII redaction. Keep that in mind for logs and dashboards.

Direct sends every caller to one named room:

json
{
  "dispatch_rule": {
    "rule": {
      "dispatch_rule_direct": {
        "room_name": "open-room"
      }
    },
    "name": "My dispatch rule"
  }
}

It can take an optional pin, which the caller types followed by #. The page is blunt about the catch: with a static room, unrelated callers end up in the same room and hear each other. For an agent that talks to one caller at a time, use individual rules (or callee rules, dispatch_rule_callee, which name rooms by the number dialled) in production.

Two more details. If you leave out trunk_ids, the rule is a wildcard that applies to every trunk. And room_config.agents entries take agent_name (required), metadata and deployment. Your agent reads the metadata as ctx.job.metadata.

sequenceDiagram
    autonumber
    participant C as Caller
    participant K as Carrier
    participant L as LiveKit SIP
    participant R as Room
    participant A as Agent
    C->>K: dials your number (DID)
    K->>L: INVITE to origination URI
    Note over L: Inbound trunk: numbers, auth or allowed_addresses
    Note over L: Dispatch rule: individual, room prefix call-
    L->>R: create room, caller joins as SIP participant
    alt agent_name matches a running agent
        R->>A: dispatch inbound-agent (metadata)
        A->>R: joins and greets the caller
        R-->>C: agent audio
    else agent not running or name mismatch
        L-->>K: 486 Busy Here
    end

Diagram: Inbound: the trunk accepts the call, the dispatch rule picks the room, and agent_name decides which agent joins.

Step 5: a minimal agent that answers

The agent_name in the dispatch rule has to match the name your agent registers with. The Agent dispatch page explains why this matters: setting agent_name on @server.rtc_session switches the agent to explicit dispatch, so it joins only rooms it is dispatched to. The page recommends explicit dispatch for SIP inbound because it lets several agents live in one project. It also gives a maximum dispatch time of under 150 ms.

Here is the quickstart agent from the Voice AI quickstart page, cut down. I changed agent_name from the doc's "my-agent" to "inbound-agent" to match the rule above, and removed the noise cancellation plugin from room_options to keep it short:

python
from dotenv import load_dotenv

from livekit import agents
from livekit.agents import AgentServer, AgentSession, Agent, inference, TurnHandlingOptions

load_dotenv(".env.local")


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(instructions="You are a helpful voice AI assistant.")


server = AgentServer()


@server.rtc_session(agent_name="inbound-agent")
async def my_agent(ctx: agents.JobContext):
    session = AgentSession(
        stt=inference.STT(model="assemblyai/assemblyai-stt-3-7-realtime-agent"),
        llm=inference.LLM(model="google/gemma-4-31b-it"),
        tts=inference.TTS(
            model="fishaudio/s2.1-pro",
            voice="fa4c9eb3dccc4806b382b40d61c6b10a",
        ),
        turn_handling=TurnHandlingOptions(
            turn_detection=inference.TurnDetector(),
        ),
    )

    await session.start(room=ctx.room, agent=Assistant())

    await session.generate_reply(
        instructions="Greet the user and offer your assistance."
    )


if __name__ == "__main__":
    agents.cli.run_app(server)

The quickstart flow around it is lk cloud auth, lk agent init my-agent --template agent-starter-python, lk agent dev to run locally, and lk agent create to deploy to LiveKit Cloud. Which models you pick changes the latency a caller feels; the latency budget post covers that.

If inbound calls fail with 486, the troubleshooting page lists three causes: the agent is not running, it is not dispatched, or agent_name does not match.

Step 6: the outbound trunk

To call out, LiveKit needs to know where to send the INVITE (the SIP request that starts a call) and how to authenticate. The Outbound trunk page shows the address for each provider:

  • Twilio: "address": "<my-trunk>.pstn.twilio.com"
  • Telnyx: "address": "sip.telnyx.com", with a note to use a regional Telnyx signaling address
  • Plivo: "<trunk-id>.zt.plivo.com"

A trunk file with an address and numbers is created with credentials passed on the command line, per the same page:

shell
lk sip outbound create outbound-trunk.json \
  --auth-user "$SIP_AUTH_USERNAME" \
  --auth-pass "$SIP_AUTH_PASSWORD"

The output prints SIPTrunkID: <your-trunk-id>, which you need for every call.

From the CLI reference: an outbound trunk requires an address and at least one number. --transport takes auto, udp, tcp or tls (default auto). --numbers with * allows any caller ID, and then you set sip_number on each call. The Outbound trunk page also says you can skip stored trunks and pass the trunk inline with each call.

Telnyx needs one extra field. The Telnyx page explains that Telnyx uses digest authentication with a 407 challenge, and that without the username on the first INVITE, Telnyx may match the call against a different customer's IP-based connection. The fix it gives is to add "headers_to_attributes": {"X-Telnyx-Username": "<username>"} on the outbound trunk.

Region pinning for outbound. By default, the region pinning page says, outbound calls start from the region where you called CreateSIPParticipant. Setting destination_country on the trunk makes them originate from a server in that country. The page's example is a Twilio trunk with "destination_country": "in". If the code does not match a supported region, it has no effect, and if the region is down the call starts from a nearby region.

Step 7: place a call with CreateSIPParticipant

The Outbound calls page has a request file:

json
{
  "sip_trunk_id": "<your-trunk-id>",
  "sip_call_to": "<phone-number-to-dial>",
  "room_name": "my-sip-room",
  "participant_identity": "sip-test",
  "participant_name": "Test Caller",
  "wait_until_answered": true
}
shell
lk sip participant create sip-participant.json

When the callee picks up, the participant's sip.callStatus attribute changes to active. In Python the same page uses CreateSIPParticipantRequest from livekit.protocol.sip and calls livekit_api.sip.create_sip_participant(request). The CLI flag form (--trunk, --call, --room and others) has a --timeout that defaults to 1m20s, per the CLI reference.

For your agent to talk on that call, dispatch it to the same room. The Agent dispatch page shows the CLI form:

shell
lk dispatch create --agent-name test-agent --room my-room --metadata '{"user_id": "12345"}'

Dispatch metadata is limited to 512 KiB, per that page. Answering machine detection, DTMF and transfers on outbound calls are in the outbound and inbound post.

sequenceDiagram
    autonumber
    participant App as Your code
    participant L as LiveKit SIP
    participant K as Carrier
    participant X as Callee
    App->>L: CreateSIPParticipant (trunk, number, room)
    L->>K: INVITE to the outbound trunk address
    opt Telnyx digest auth
        K-->>L: 407 challenge
        L->>K: INVITE with credentials
    end
    K->>X: rings the phone
    X-->>K: answers
    K-->>L: 200 OK
    L->>K: ACK
    L-->>App: sip.callStatus = active
    App->>L: dispatch the agent to the same room

Diagram: Outbound: CreateSIPParticipant sends the INVITE, Telnyx may challenge with 407, and callStatus turns active on answer.

Self-hosting the SIP service

If you run LiveKit yourself, the SIP server page gives a Docker Compose start:

shell
wget https://raw.githubusercontent.com/livekit/sip/main/docker-compose.yaml
docker compose up

and a config file for running the binary directly with livekit-sip --config=config.yaml:

yaml
api_key: <your-api-key>
api_secret: <your-api-secret>
ws_url: ws://localhost:7880
redis:
  address: localhost:6379
sip_port: 5060
rtp_port: 10000-20000
use_external_ip: true
logging:
  level: debug

Your SIP URI is then <public-ip-address>:5060, and that is what goes in the carrier's origination URI instead of the Cloud endpoint.

Ports, from the Ports and firewall page:

  • SIP signaling: UDP and TCP 5060 (sip_port), TLS 5061 (tls.port)
  • SIP media: RTP over UDP 10000 to 20000 (rtp_port)

The SIP server page says 5060 and the 10000 to 20000 range must be reachable from the Internet. The LiveKit server's own ports (7880 for the API and others) are listed separately on that page.

use_external_ip: true matters more than it looks. The troubleshooting page says one-way audio comes from a private IP address in the SDP (the session description that tells the other side where to send audio), and its fix for self-hosted setups is exactly this setting.

Two pitfalls from the livekit/sip README. First, if you run it with plain docker run, the README uses --network host because the RTP port range is hard for Docker to map. Second, the README's "Using the SIP service" section still shows the older livekit-cli create-sip-trunk command and inbound_addresses field. The docs.livekit.io pages use lk sip inbound create and allowed_addresses, so follow the docs site.

When it does not work

The troubleshooting page suggests starting in the Telephony section of the LiveKit Cloud dashboard, in the Calls view, and asking three questions in order: did LiveKit record an INVITE, what response did it send, and did media flow. Then look at the packet capture.

A few entries from that page that map directly to the config above:

  • 404 with twirp error unknown: object cannot be found: wrong trunk ID in your request.
  • 403: an authentication mismatch, or "403 - Domestic Anchored Terms Not Met", which the page says appears where rules require calls to stay inside a country. The fix it gives is region pinning.
  • No audio: check the SDP for c=IN IP4 0.0.0.0 or m=audio 0, and check that both sides share a codec; no common codec gives a 488.
  • Silence then hang-up: by default the media timeout is 30 seconds with no RTP after setup and 15 seconds after the last packet. media_timeout can be raised, for example to "60s", up to 10 minutes.

For the full set of codes see the SIP response code chart, and for one-way audio and other production failures see the reliability post. If you are bridging through Asterisk instead of going carrier to LiveKit directly, the Asterisk reference chart has the PJSIP side.

flowchart TD
    A[Call failed: open Telephony, Calls view] --> B{Did LiveKit record an INVITE?}
    B -->|No| B1[Check carrier origination URI, then the capture]
    B -->|Yes| C{What response did LiveKit send?}
    C -->|404 twirp not found| C1[Wrong trunk ID in your request]
    C -->|403| C2[Auth mismatch, or domestic anchoring: use region pinning]
    C -->|486| C3[Agent not running, not dispatched, or agent_name mismatch]
    C -->|488| C4[No common codec]
    C -->|200 OK| D{Did media flow?}
    D -->|No| D1[SDP shows 0.0.0.0, m=audio 0 or a private IP]
    D1 --> D2[Self-hosted: set use_external_ip true]
    D -->|Silence then hang-up| D3[Media timeout: raise media_timeout]

Diagram: The troubleshooting order from the docs: was there an INVITE, what was the response, did media flow.

What changes with an Indian carrier

LiveKit documents the pieces an India deployment would use:

  • Inbound region endpoint. <your SIP subdomain>.india.sip.livekit.cloud, from the region pinning page, keeps inbound calls on India nodes.
  • Outbound country. destination_country: "in". The regions and endpoints page lists Hyderabad and Mumbai as the in locations.
  • Static IP ranges. The same page lists India among the regions with static IPs, with the blocks 143.223.88.0/21, 161.115.160.0/19 and 153.57.128.0/18, covering SIP signaling and media. The page uses the same three blocks for every listed region. These are what you would give a carrier that authenticates by source IP. The Outbound trunk page adds that if your provider needs IPs and you cannot use the static ranges, the fallback is 0.0.0.0/0.
  • Agents near the calls. The same page lists ap-south (Mumbai) as an agent deployment region.

What is not publicly documented: I found no LiveKit page, and no Tata Communications or Tata Tele Business Services (TTBS) page, that shows either company's trunk wired to LiveKit. There is no published origination format, SBC address, codec list or auth scheme for that pairing. One relevant public fact: the Smartflo changelog for July 2026 says TTBS's Smartflo SIP Trunking is generally available with "inbound call delivery and outbound PSTN termination" and supports UDP/TCP and TLS. Because LiveKit does not support SIP REGISTER, the first question for either Tata company is whether the trunk can use IP authentication or digest credentials with a fixed origination address. Ask for it in writing.

What each Tata company publishes, and where they differ, is in the Tata comparison post. The wider provider picture is in SIP trunk providers for voice AI in India compared, the regulatory side (number series, consent, data) is in India rules for AI phone calls, and per-minute costs are in voice AI cost per minute, India vs US.

Sources