Goal: Setup inbound calling, i have a third party ...
# ask-ai
f
Goal: Setup inbound calling, i have a third party SIP provider that i have used and purchased a telephony number. I have already setup the SIP trunk and dispatch rule, can you tell me how to activate this in my agent.py file?
t
Thanks for reaching out, Viren. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you’ve already done the SIP trunk + dispatch rule. To activate inbound calls in your
agent.py
, you don’t change SIP settings there — instead ensure your agent is configured for explicit dispatch and can join and handle the room LiveKit creates when a call arrives. A few targeted steps and a quick question: 1) Make your agent a named, explicitly-dispatched agent • Use the agent decorator with a name so LiveKit will start it only when the dispatch rule triggers:
Copy code
from livekit import agents
from livekit.agents import JobContext

server = agents.JobContext()

@server.agent(name="my-telephony-agent")
@server.task(name="inbound-call-handler")
async def inbound_agent(ctx: JobContext):
    await ctx.connect()
    # greet, listen, respond
    await ctx.generate_reply(instructions="Greet caller and offer assistance.")
2) Ensure your dispatch rule references that agent name • Your dispatch rule’s
roomConfig.agents
must include
agentName: "my-telephony-agent"
so the inbound trunk/dispatch will spawn this agent into the room created for the call. 3) Handle the call session inside the agent • When dispatched, treat the SIP caller as a room participant (kind=SIP): connect, subscribe to audio, generate replies (LLM/TTS) and end the session when done. Use
ctx.room
and
ctx.generate_reply(...)
for interaction. Quick checklist: • Agent name in
agent.py
matches
agentName
in dispatch rule. • Agent uses
await ctx.connect()
and session-handling logic (greet, listen, respond). • No SIP details need to be referenced in
agent.py
— LiveKit injects the SIP participant into the room. One question to confirm: are you running this agent as a serverless job (LiveKit Agents framework) or as a long-running worker process? If you share your current
agent.py
(or tell me which pattern you’re using), I’ll give a concrete patch/example tailored to it. Sources: SIP overview | LiveKit docs | Agents telephony integration | LiveKit docs | sip | livekit/livekit_composite | DeepWiki | Accepting inbound calls | LiveKit docs | Examples | livekit/livekit_composite | DeepWiki
f
Can u confirm if this is correct? # SIP Inbound: { "sipTrunkId": "ST_***********", "name": "botverse_sip", "numbers": [ "+91*********" ] } # Dispatch Inbound rule { "sipDispatchRuleId": "SDR_********", "rule": { "dispatchRuleIndividual": { "roomPrefix": "call-" } }, "name": "My dispatch rule" } # agent.py i am not using SIP id or any name
t
Thanks — you’re almost there. I’ll confirm what’s correct and what needs a small change. 1) SIP inbound JSON • That shape is fine. Ensure
sipTrunkId
is the actual trunk ID and the phone number is E.164 (e.g. "+919240904637"). No other changes needed in agent.py for SIP IDs. 2) Dispatch rule JSON • Your rule needs a
roomConfig.agents
entry that references the agent name you’ll use in
agent.py
. Example addition:
Copy code
"roomConfig": {
  "agents": [
    {
      "agentName": "my-telephony-agent",
      "metadata": "inbound-call"
    }
  ]
}
Without that, LiveKit won’t dispatch your agent into the created room. 3) agent.py • You must give the agent the same name used in the dispatch rule. Example:
Copy code
@server.agent(name="my-telephony-agent")
@server.task(name="inbound-call-handler")
async def inbound_agent(ctx: JobContext):
    await ctx.connect()
    await ctx.generate_reply(instructions="Greet caller and offer assistance.")
• Do not include SIP IDs or trunk names in
agent.py
— the platform injects the SIP participant into the room. If you’d like, paste your exact agent.py and I’ll show the minimal edit to match your dispatch rule name.
f
# agent.py # Log participant connections (useful for SIP debugging) @ctx.room.on("participant_connected") def on_participant_connected(participant: rtc.RemoteParticipant): """Log when participants (including SIP callers) join the room""" participant_kind = str(participant.kind) if participant.kind else "unknown" logger.info(f"📞 Participant joined: {participant.identity} (kind={participant_kind})") print(f"📞 Participant joined: {participant.identity} (kind={participant_kind})") # Check if this is a SIP participant (handle both string and enum comparisons) if participant_kind.lower() == "sip" or "sip" in participant_kind.lower(): logger.info("✅ SIP participant detected - inbound call connected") print("✅ SIP participant detected - inbound call connected") @ctx.room.on("participant_disconnected") def on_participant_disconnected(participant: rtc.RemoteParticipant): """Log when participants disconnect""" participant_kind = str(participant.kind) if participant.kind else "unknown" logger.info(f"📞 Participant disconnected: {participant.identity} (kind={participant_kind})") print(f"📞 Participant disconnected: {participant.identity} (kind={participant_kind})") try: sip_participant = await asyncio.wait_for( ctx.wait_for_participant(kind="sip"), timeout=30.0 ) except asyncio.TimeoutError: pass except Exception as e: pass await session.start( agent=bot, room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), audio_sample_rate=16000, audio_num_channels=1, ), room_output_options=RoomOutputOptions( audio_enabled=True, ) ) logger.info("✅ Session ended") # Ensure backend is notified of session end (in case shutdown callback didn't fire) try: await asyncio.wait_for(notify_session_end(), timeout=30.0) logger.info("✅ Backend notified of session end") except asyncio.TimeoutError: logger.warning("⚠️ Backend notification timed out, continuing") except Exception as e: logger.warning(f"Failed to notify backend: {e}, continuing")
t
Thanks — this is close. Two required fixes and a few suggestions to make inbound SIP work reliably. Required fixes 1. Agent must be named and decorated so LiveKit can dispatch it. Add the
@server.agent(name="my-telephony-agent")
and
@server.task(...)
decorators above your main async handler that runs the session. The name must match the
agentName
in your dispatch rule. 2. The participant event handlers must be defined on an async-capable handler context and registered before awaiting the SIP participant. Use async functions for any handler that does awaits, and register them on
ctx.room
inside your agent after
await ctx.connect()
. Minimal example pattern to follow
Copy code
@server.agent(name="my-telephony-agent")
@server.task(name="inbound-call-handler")
async def inbound_agent(ctx: JobContext):
    await ctx.connect()

    @ctx.room.on("participant_connected")
    async def on_participant_connected(participant: rtc.RemoteParticipant):
        kind = str(participant.kind) if participant.kind else "unknown"
        logger.info(f"📞 Participant joined: {participant.identity} (kind={kind})")
        if "sip" in kind.lower():
            logger.info("✅ SIP participant detected - inbound call connected")

    @ctx.room.on("participant_disconnected")
    async def on_participant_disconnected(participant: rtc.RemoteParticipant):
        kind = str(participant.kind) if participant.kind else "unknown"
        logger.info(f"📞 Participant disconnected: {participant.identity} (kind={kind})")

    try:
        sip_participant = await asyncio.wait_for(ctx.wait_for_participant(kind="sip"), timeout=30.0)
    except asyncio.TimeoutError:
        logger.info("No SIP participant joined within timeout")
        return

    await session.start(
        agent=bot,
        room=ctx.room,
        room_input_options=RoomInputOptions(...),
        room_output_options=RoomOutputOptions(audio_enabled=True),
    )

    # notify backend etc...
Suggestions / gotchas • Ensure the
agentName
in your dispatch rule matches
"my-telephony-agent"
. • Use E.164 for numbers (you already are using +919240904637). • Keep handlers async if you call
await
inside them. • Log both identity and kind for easier SIP debugging. • Gracefully return if no SIP participant joins (avoid hanging the job). If you paste your current full
agent.py
, I’ll patch it to the minimal runnable version with the exact decorator name you want. Which agent name would you like me to use in the example?
f
also for testing do i run python agent.py dev from terminal to test inbound calling?
t
Yes — run the agent locally with the development runner: use uv run agent.py dev Make sure of these before testing: • Your
agent.py
has the
@server.agent(name="MY_AGENT_NAME")
decorator and the name matches
agentName
in your dispatch rule. • The agent calls
await ctx.connect()
and registers the
@ctx.room.on(...)
handlers after connect. • Environment variables required by the Agents framework (API key/URL, any LiveKit config) are set in your shell before you run the command. Testing flow: 1. Start the agent locally with
uv run agent.py dev
. 2. Trigger an inbound call to the SIP number (from your SIP provider). 3. Watch logs for the SIP participant joining (kind=sip) and the agent handling the session. If you want, paste the exact command/environment you plan to use and I’ll confirm any variables you need to set. Sources: SIP inbound trunk | LiveKit docs | SIP dispatch rule | LiveKit docs | Voice AI quickstart | LiveKit docs
f
so what should be final dispatch rule strucutre in json?? current version is: { "sipDispatchRuleId": "SDR_*******", "rule": { "dispatchRuleIndividual": { "roomPrefix": "call-" } }, "name": "My dispatch rule" }
t
You need to add a
roomConfig.agents
block that references the agent name your
agent.py
uses. Final dispatch rule example:
Copy code
{
  "sipDispatchRuleId": "SDR_********",
  "rule": {
    "dispatchRuleIndividual": {
      "roomPrefix": "call-"
    }
  },
  "name": "My dispatch rule",
  "roomConfig": {
    "agents": [
      {
        "agentName": "my-telephony-agent",
        "metadata": "inbound-call"
      }
    ]
  }
}
• Ensure
"agentName"
exactly matches the name you set in
agent.py
with
@server.agent(name="my-telephony-agent")
. •
roomPrefix
creates rooms like
call-<id>
for each inbound call. •
metadata
is optional and can hold any string you want for identification. If you tell me the exact agent name you want to use, I’ll paste the JSON with that name.
f
what is @breezy-insurance-66772.task(name="inbound-call-handler") but the name is not mentoined anywhere in dispatch rule
t
Good question — short answer: the
@server.task(name="...")
name is just an internal task identifier and does not need to appear in the dispatch rule. Quick details: •
@server.agent(name="...")
— This name must match
agentName
in your dispatch rule. LiveKit uses this to dispatch the correct agent into the room. •
@server.task(name="inbound-call-handler")
— This is an internal label for the agent’s task (used for logging/metrics/organization). It does not affect dispatching and does not need to be referenced in the dispatch rule. • Dispatch rule only needs the
roomConfig.agents[].agentName
to match the
@server.agent
name. If you want, tell me the exact agent name you plan to use and I’ll show the final
agent.py
decorator lines plus the matching dispatch JSON.
f
why do i need to import server in code: Server.agent(name="my-telephony-agent")
t
Good question — here’s why you need the
server
object and which decorator to use. • The
server
instance (e.g.,
AgentServer()
or
agents.AgentServer()
) is the agent runtime that registers your session handler and exposes the decorator you use to define the agent entrypoint. You must create and import it so your function is registered with the Agents framework. • Use the
@server.rtc_session(agent_name="my-telephony-agent")
decorator (not
@server.agent(...)
). Example minimal pattern:
Copy code
from livekit.agents import AgentServer, JobContext

server = AgentServer()

@server.rtc_session(agent_name="my-telephony-agent")
async def inbound_agent(ctx: JobContext):
    await ctx.connect()
    # register handlers and run session
    ...
•
agent_name
is the name LiveKit uses to dispatch this exact agent via your dispatch rule.
@server.rtc_session
registers the handler; you still can provide a
name
for telemetry/logs but that name is not required in the dispatch rule. If you want, paste your current imports and I’ll show the exact minimal edits to make your file use
AgentServer
+
@server.rtc_session(...)
. Sources: Agent dispatch | LiveKit docs | Agent server options | LiveKit docs | Agents telephony integration | LiveKit docs
f
ImportError: cannot import name 'AgentServer' from 'livekit.agents'
t
You're seeing that ImportError because your installed livekit-agents package doesn't expose
AgentServer
at that import path/version. What to do next (pick one): • Easiest — use the current pattern (no AgentServer):
Copy code
from livekit.agents import JobContext, cli, WorkerOptions

async def entrypoint(ctx: JobContext):
    await ctx.connect()
    # register handlers, wait for SIP participant, start session...

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
This is the recommended pattern for recent versions. • If you prefer the server-style API, import from the server module (may exist in some versions):
Copy code
from livekit.agents.server import AgentServer
server = AgentServer()

@server.rtc_session(agent_name="my-telephony-agent")
async def inbound_agent(ctx: JobContext):
    ...
If that still errors, your package build likely doesn't include the server APIs. Also verify your installation: • pip install livekit-agents • Or install extras if needed: uv add "livekit-agents[silero,turn-detector]~=1.2" Tell me which pattern you want (modern WorkerOptions entrypoint or server.rtc_session) and I’ll give a minimal, copy-paste
agent.py
tailored to it. Sources: Agents v0.x migration guide - Python | LiveKit docs | Voice AI quickstart | LiveKit docs | Agent server options | LiveKit docs | Using Wavix to accept and make calls | LiveKit docs | Agents telephony integration | LiveKit docs
f
first pattern for inbound calling in agent session, also in dispatch rule should i keep Inbound routing as All numbers and trunks or connect my sip_trunk? i need to understand what this means: Inbound routing Configure origination by setting up how inbound calls will be dispatched to LiveKit rooms by matching phone numbers and specific trunks. If no number or trunk is selected, the rule will be applied to all.
t
Good choices — here’s concise guidance for the first (WorkerOptions/entrypoint) pattern and how to set Inbound routing. 1) Agent pattern (minimal runnable skeleton)
Copy code
from livekit.agents import JobContext, cli, WorkerOptions
import asyncio

async def entrypoint(ctx: JobContext):
    await ctx.connect()

    @ctx.room.on("participant_connected")
    async def on_participant_connected(participant):
        kind = str(participant.kind) if participant.kind else "unknown"
        ctx.logger.info(f"📞 joined: {participant.identity} (kind={kind})")
        if "sip" in kind.lower():
            ctx.logger.info("✅ SIP participant detected")

    try:
        sip_participant = await asyncio.wait_for(ctx.wait_for_participant(kind="sip"), timeout=30.0)
    except asyncio.TimeoutError:
        ctx.logger.info("No SIP participant joined; exiting")
        return

    # start your agent session logic (e.g., create AgentSession / VoicePipelineAgent and start)
    # await session.start(...)

    await ctx.job.wait_for_cancel()

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
• Run locally with: uv run agent.py dev • Ensure env vars (LiveKit URL/API key etc.) are set before running. • Use async handlers (as shown) and register them after
await ctx.connect()
. 2) Dispatch rule — which trunks/numbers to match • If you leave trunks/numbers blank, the rule applies to all inbound calls. • Best practice: explicitly target your SIP trunk (trunkIds or select trunk in dashboard) so only calls on that trunk trigger this rule. • Example minimal JSON (include matching agentName):
Copy code
{
  "sipDispatchRuleId": "SDR_********",
  "rule": {
    "dispatchRuleIndividual": {
      "roomPrefix": "call-"
    }
  },
  "name": "My dispatch rule",
  "roomConfig": {
    "agents": [
      {
        "agentName": "inbound-agent",
        "metadata": "inbound-call"
      }
    ]
  },
  "trunkIds": [
    "ST_XXXXXXXX"
  ]
}
• Make sure
"agentName"
exactly matches the agent name your dispatch expects (for WorkerOptions pattern the agent name is the one LiveKit will target; include it in your rule). 3) Which option to pick: All vs specific trunk • Use "All numbers and trunks" if you want the rule to apply globally (simple demos). • Use a specific trunk (recommended) if you have multiple trunks/numbers or want precise routing and to avoid accidental triggers. 4) Quick checklist before testing • Dispatch rule includes
roomConfig.agents[].agentName
that matches your agent registration. • Trunk/number selection set per your needs (recommended: set
trunkIds
to your SIP trunk). • Start agent locally: uv run agent.py dev • Make an inbound call to your SIP number and watch logs for participant kind="sip" and agent behavior. If you want, tell me the exact agent name you want to use and I’ll paste a copy-paste agent.py that includes the matching name and a short session-start placeholder. Sources: Agent session | LiveKit docs | Agents telephony integration | LiveKit docs | SIP dispatch rule | LiveKit docs | Accepting inbound calls | LiveKit docs | SIP inbound trunk | LiveKit docs