How do I set a max call duration.
# ask-ai
d
How do I set a max call duration.
t
Thanks for reaching out, Billy. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to set a max call duration — do you want that limit applied to a trunk (all calls on that trunk) or to a single SIP call/participant? Also, are you using SIP trunks/participants? Sources: Quotas and limits | LiveKit docs | SIP APIs | LiveKit docs
d
SIP/ Trunks. For example client calls inbound...LiveKit AI answers... and client says nothing... how can i set a max call duration so the call doesnt run forever
t
Good — since you’re using SIP trunks for inbound calls, set
max_call_duration
on the inbound trunk (or on the specific SIP participant when creating the call). That will automatically terminate the call when the time limit is reached. Options: • Set on the inbound trunk (applies to all calls on that trunk)
Copy code
{
  "name": "My Inbound Trunk",
  "numbers": [
    "+15105550100"
  ],
  "max_call_duration": "1800s"
}
• Or set per call when creating a SIP participant (applies to that single call)
Copy code
{
  "sip_trunk_id": "trunk-id",
  "sip_call_to": "+1234567890",
  "room_name": "my-room",
  "max_call_duration": "1800s"
}
Notes: • Use Google Protobuf Duration format (e.g.,
"1800s"
= 30 minutes,
"3600s"
= 1 hour). • When the limit is reached the call ends with status LIMIT_REACHED. Would you like the equivalent example in Python or another SDK?
d
Im using python... so i set max_call_duration in the metadata? then use in the entry point code?. can you provide an example please
t
You're correct — do NOT put
max_call_duration
in metadata. Set it on the inbound trunk (or per-call when creating a SIP participant). Below are two concise Python examples: 1) create/update an inbound trunk with a max duration; 2) create a SIP participant with a per-call max duration. 1) Create inbound trunk with max_call_duration (applies to all calls on that trunk)
Copy code
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def create_inbound_trunk():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(1800)  # 30 minutes

    req = api.CreateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            name="My Inbound Trunk",
            numbers=["+15105550100"],
            max_call_duration=d,
            krisp_enabled=True,
        )
    )

    trunk = await client.sip.create_sip_inbound_trunk(request=req)
    print("Created trunk:", trunk)

if __name__ == "__main__":
    asyncio.run(create_inbound_trunk())
2) Create a SIP participant with a per-call max_call_duration
Copy code
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def create_sip_participant():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(600)  # 10 minutes for this specific call

    req = api.CreateSIPParticipantRequest(
        sip_trunk_id="your-trunk-id",
        sip_call_to="+1234567890",
        room_name="my-room",
        max_call_duration=d,
    )

    participant = await client.sip.create_sip_participant(request=req)
    print("Created participant:", participant)

if __name__ == "__main__":
    asyncio.run(create_sip_participant())
Would you like help updating an existing trunk, or a short snippet to implement an in-agent timer to end calls early (in addition to the trunk limit)? Sources: SIP APIs | LiveKit docs | SIP inbound trunk | LiveKit docs | Operational Best Practices | livekit/livekit_composite | DeepWiki
d
My code uses async def entrypoint(ctx:JobContext): and also uses 'session = AgentSession( stt= llm= tts= )
t
You're on the right track — set
max_call_duration
via the LiveKit SIP API (trunk or per-call), not in
metadata
. Below are two focused examples showing how to: • create/update an inbound trunk with
max_call_duration
, and • additionally run a safety timer inside your
entrypoint
that ends the call early if needed. Both examples fit into an async
entrypoint(ctx: JobContext)
+
AgentSession
flow. 1) Create or update the inbound trunk (one-time API call; not inside every entrypoint)
Copy code
# trunk_setup.py
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def ensure_inbound_trunk():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(1800)  # 30 minutes

    req = api.CreateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            name="My Inbound Trunk",
            numbers=["+15105550100"],
            max_call_duration=d,
            krisp_enabled=True,
        )
    )

    trunk = await client.sip.create_sip_inbound_trunk(request=req)
    print("Created trunk:", trunk)

if __name__ == "__main__":
    asyncio.run(ensure_inbound_trunk())
Call this once (or update an existing trunk) to apply the hard cap to all inbound calls. 2) Optional: Safety timer inside your agent entrypoint (ends call early if you want additional control)
Copy code
# agent_entrypoint.py
import asyncio
from livekit.agents import JobContext, get_job_context  # adjust imports to your SDK layout

async def end_call_gracefully(ctx: JobContext, seconds: int):
    await asyncio.sleep(seconds)
    # End the LiveKit room to hang up
    await ctx.api.room.delete_room(room=ctx.room.name)

async def entrypoint(ctx: JobContext):
    # create your AgentSession as you already do
    session = AgentSession(
        stt=...,
        llm=...,
        tts=...,
        # other config
    )

    # start a background safety task to end call after 10 minutes
    asyncio.create_task(end_call_gracefully(ctx, 600))

    # normal agent logic follows
    await session.run(ctx)
Key points: •
max_call_duration
is a trunk- or per-call API property (use
CreateSIPInboundTrunkRequest
or
CreateSIPParticipantRequest
). • The inbound trunk limit enforces a hard cap and will terminate calls with status LIMIT_REACHED. • The in-agent timer is optional and useful for extra control (e.g., detect silence and hang up earlier). Would you like a snippet showing how to create a per-call
CreateSIPParticipantRequest
with
max_call_duration
instead of trunk-level setup, or help integrating the safety timer with silence detection?
d
im using twilio sip
t
Set the max call duration on the LiveKit SIP trunk (or per-call when creating a SIP participant). This applies even when your trunk ingests calls from Twilio — Twilio handles SIP transport, LiveKit enforces the call lifecycle. Quick points: • Do NOT put
max_call_duration
in metadata. Set it on the inbound trunk or when creating a SIP participant. • Use
google.protobuf.Duration
in the Python SDK (or a `timedelta`/Duration object). • Twilio trunk settings are separate — you still configure the limit in LiveKit, not in Twilio. Example: create/update inbound trunk with a 20-minute hard cap
Copy code
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def ensure_inbound_trunk():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(20 * 60)  # 20 minutes

    req = api.CreateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            name="Twilio Inbound",
            numbers=["+15105550100"],
            max_call_duration=d,
        )
    )

    trunk = await client.sip.create_sip_inbound_trunk(request=req)
    print("Created/updated trunk:", trunk)

asyncio.run(ensure_inbound_trunk())
If you prefer a per-call limit instead of trunk-wide:
Copy code
from google.protobuf.duration_pb2 import Duration
req = api.CreateSIPParticipantRequest(
    sip_trunk_id="your-trunk-id",
    sip_call_to="+1234567890",
    room_name="my-room",
    max_call_duration=Duration(seconds=600),  # 10 minutes
)
Optional safety in your agent entrypoint (ends call early from inside the agent)
Copy code
import asyncio
async def end_call_gracefully(ctx, seconds):
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(room=ctx.room.name)

async def entrypoint(ctx):
    asyncio.create_task(end_call_gracefully(ctx, 600))  # 10-min safety
    session = AgentSession(stt=..., llm=..., tts=...)
    await session.run(ctx)
Would you like a short snippet showing how to update an existing trunk (instead of creating a new one), or help confirming your Twilio SIP->LiveKit routing so the trunk setting will apply?
d
Copy code
async def entrypoint(ctx: JobContext):
    """Main entry point for the telephony voice agent."""
    await ctx.connect()
my entry point code
t
You're already calling
await ctx.connect()
in your
entrypoint
. Add a background safety task there and ensure the trunk has
max_call_duration
set via the LiveKit SIP API (not metadata). Below are two minimal, ready-to-drop snippets that match your style. 1) Ensure inbound trunk has a hard cap (one-time admin call; not in entrypoint)
Copy code
# trunk_setup.py
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def ensure_inbound_trunk():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")
    d = Duration()
    d.FromSeconds(20 * 60)  # 20 minutes
    req = api.CreateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            name="Twilio Inbound",
            numbers=["+15105550100"],
            max_call_duration=d,
        )
    )
    await client.sip.create_sip_inbound_trunk(request=req)

# run once (or use update API to change an existing trunk)
asyncio.run(ensure_inbound_trunk())
2) Add an in-agent safety timer inside your existing entrypoint to end calls early if desired
Copy code
import asyncio
from livekit.agents import JobContext  # adjust import path to your SDK

async def _end_call_after(ctx: JobContext, seconds: int):
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(room=ctx.room.name)

async def entrypoint(ctx: JobContext):
    """Main entry point for the telephony voice agent."""
    await ctx.connect()

    # safety: hang up after 10 minutes (600s) in case trunk limit isn't enough or you want earlier hangup
    asyncio.create_task(_end_call_after(ctx, 600))

    # your existing AgentSession logic
    session = AgentSession(stt=..., llm=..., tts=...)
    await session.run(ctx)
Would you like a snippet to update an existing trunk instead of creating one, or help wiring this to your Twilio SIP routing?
d
IM USING AGENT SESSION. NOT CREATE SIPINBOUNDTRUNKREQUEST
t
Thanks — understood you’re using AgentSession and don’t want to call CreateSIPInboundTrunkRequest. Two practical options that fit your setup: Option A — Recommended (set trunk limit once outside the agent) •
max_call_duration
is a trunk property. If you can update the existing inbound trunk (one-time admin action), set
max_call_duration
on that trunk and LiveKit will enforce the hard cap for all calls your AgentSession handles. If you want, I can show a short snippet to update an existing trunk if you give the trunk ID. Option B — In-agent safety timer (no trunk changes required) • Add a background task in your
entrypoint(ctx: JobContext)
to hang up after N seconds. This enforces a per-call cap from inside the agent. Minimal drop-in example matching your entrypoint style:
Copy code
import asyncio
from livekit.agents import JobContext

async def _end_call_after(ctx: JobContext, seconds: int):
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(room=ctx.room.name)

async def entrypoint(ctx: JobContext):
    await ctx.connect()
    # safety: hang up after 10 minutes
    asyncio.create_task(_end_call_after(ctx, 600))

    session = AgentSession(stt=..., llm=..., tts=...)
    await session.run(ctx)
Which do you prefer — I can: • provide the exact snippet to update an existing trunk (need trunk ID), or • show how to combine silence detection with the safety timer in your AgentSession?
d
Set the max_call_duration in JSON?
t
You can set
max_call_duration
in the trunk or per-call JSON using Google Protobuf Duration (e.g., "1800s"). Do NOT put it in metadata — it belongs on the SIP trunk or
CreateSIPParticipant
payload. Example — inbound trunk (JSON):
Copy code
{
  "name": "Twilio Inbound",
  "numbers": [
    "+15105550100"
  ],
  "max_call_duration": "1800s"
}
Example — per-call when creating a SIP participant (JSON):
Copy code
{
  "sip_trunk_id": "trunk-id",
  "sip_call_to": "+1234567890",
  "room_name": "my-room",
  "max_call_duration": "600s"
}
Notes: • Values are durations in seconds with an "s" suffix (e.g., "3600s" = 1 hour). • Trunk-level setting applies to all inbound calls on that trunk; per-call overrides apply only to that call. • For your AgentSession flow, set the trunk once via the API/console, or create the SIP participant with
max_call_duration
when starting a call. If you want an in-agent safety timer instead, I can provide that snippet. Which would you prefer?
d
Can you just provide documentation that I can read over. This is wasting time
t
For official docs, read these LiveKit pages covering SIP trunks, SIP participant creation, and the max_call_duration field: • SIP API reference (includes CreateSIPParticipant): https://docs.livekit.io/sip/api/#createsipparticipant • SIP trunk configuration reference (shows trunk JSON including
max_call_duration
): https://docs.livekit.io/sip/api/#createsipinboundtrunk Quick note:
max_call_duration
uses Google Protobuf Duration (e.g., "1800s").
d
Copy code
Quick note: max_call_duration uses Google Protobuf Duration (e.g., "1800s").
why does this matter? WIll it work or not?
t
Good question — the Google Protobuf Duration format matters because LiveKit expects that specific type for
max_call_duration
. If you send the value in that format (e.g., "1800s"), LiveKit will accept it and enforce the limit; if you send a plain number or a non-duration string, the API may reject it or ignore the value. What to use: • JSON payload (trunk or CreateSIPParticipant):
"max_call_duration": "1800s"
(works) • Python SDK: pass a
google.protobuf.duration_pb2.Duration
(or build from
timedelta
) as shown earlier (works) If you want, I can: • show a one-line example to update your existing trunk JSON, or • give the exact Python line to build the Duration object to use in your AgentSession flow. Which do you prefer?
d
When i try adding max-call duration to my JSON editor inbound it doesnt save
t
Thanks — quick checklist and next steps so you can save this ASAP. 1) How are you editing the inbound trunk? • In the LiveKit web UI JSON editor — that editor may not accept or expose
max_call_duration
. • Via API/CLI — this will work reliably. 2) What to use exactly • Field name:
max_call_duration
(snake_case). • Value: Google Protobuf Duration string, e.g.
"1800s"
for 30 minutes. 3) Two reliable ways to save it Option A — Update via API (recommended) • Send a create/update request with the trunk JSON including
max_call_duration
. Example PATCH-style JSON body you can send to the SIP trunk API:
Copy code
{
  "trunk": {
    "name": "Twilio Inbound",
    "numbers": [
      "+15105550100"
    ],
    "max_call_duration": "1800s"
  }
}
Use the Create/Update SIP Inbound Trunk endpoints in the SIP API. This will persist the field. Option B — Python SDK • Build a
google.protobuf.duration_pb2.Duration
and call the create/update method:
Copy code
from google.protobuf.duration_pb2 import Duration
d = Duration()
d.FromSeconds(1800)
req = api.UpdateSIPInboundTrunkRequest(
    trunk=api.SIPInboundTrunkInfo(
        id="your-trunk-id",
        max_call_duration=d,
    )
)
await client.sip.update_sip_inbound_trunk(request=req)
4) If the web UI JSON editor still refuses to save • Likely the UI doesn't accept that field — use the API/SDK approach above. • Also ensure your account role has permission to edit trunks. If you want, tell me: • whether you’re using the web UI or calling the API, • and the trunk ID (if API/SDK), and I’ll provide the exact API request or a ready-to-run Python snippet.
Got it — you’re using AgentSession and want a direct, minimal solution that fits your entrypoint. Short answers: • Setting
max_call_duration
must be done on the SIP trunk or per-call via the SIP API/SDK (not in job metadata). • If the UI JSON editor won’t save the field, use the API/SDK to update the trunk. • Meanwhile you can add an in-agent safety timer inside your
entrypoint
to force a hangup after N seconds. Drop-in safety timer for your code (adds minimal changes):
Copy code
import asyncio
from google.protobuf.duration_pb2 import Duration  # only needed if you update trunk via SDK

# add this helper near top of file
async def _end_call_after(ctx, seconds: int):
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(room=ctx.room.name)

# in your existing entrypoint, after await ctx.connect()
    # safety: hang up after 10 minutes (600s)
    asyncio.create_task(_end_call_after(ctx, 600))

    session = AgentSession[HelperSessionInfo](...)
    await session.start(agent=agent, room=ctx.room)
If you want the API/SDK snippet to update an existing inbound trunk (so LiveKit enforces the hard cap), tell me the trunk ID and I’ll provide the exact Update request. Which do you want next — update trunk via API or just use the in-agent timer?
d
just show me with a faux trunkID
t
Below are two minimal examples updating an existing inbound trunk with a faux trunk ID. 1) Python SDK (update existing trunk)
Copy code
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def update_trunk_max_duration():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(1800)  # 30 minutes

    req = api.UpdateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            id="trunk-1234-abcd",       # <--- faux trunk ID
            name="Twilio Inbound",
            max_call_duration=d,
        )
    )

    resp = await client.sip.update_sip_inbound_trunk(request=req)
    print("Updated trunk:", resp)

if __name__ == "__main__":
    asyncio.run(update_trunk_max_duration())
2) Equivalent JSON payload for the API request body
Copy code
{
  "trunk": {
    "id": "trunk-1234-abcd",
    "name": "Twilio Inbound",
    "max_call_duration": "1800s"
  }
}
Notes: • Field name is
max_call_duration
and value uses Protobuf Duration format (e.g., "1800s"). • If the web UI editor refuses to save, use the API/SDK call above. • Want me to produce a curl example for the REST API?
d
Copy code
async def _end_call_after(ctx, seconds: int):
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(room=ctx.room.name)


async def entrypoint(ctx: JobContext):
    """Main entry point for the telephony voice agent."""
    await ctx.connect()
    asyncio.create_task(_end_call_after(ctx, 10))
Does not work. Just tried it. Call went on for 30s
t
Thanks — I understand the timer didn't stop the call. Quick facts and a reliable next step. Why your background task may not have ended the call • Deleting the LiveKit room (
ctx.api.room.delete_room
) doesn't necessarily end the SIP call immediately in every flow; the SIP lifecycle is enforced by the trunk settings. An in-agent sleep+delete is a fallback and can be racey depending on when the agent is connected and how the SIP gateway handles hangups. What will reliably enforce a hard cap • Set
max_call_duration
on the inbound SIP trunk (or per-call via
CreateSIPParticipant
) — LiveKit enforces that and will terminate the call with status LIMIT_REACHED. Working options for you now 1) Update trunk (recommended, reliable) • Use this Python SDK snippet with a faux trunk ID:
Copy code
import asyncio
from livekit import api
from google.protobuf.duration_pb2 import Duration

async def update_trunk_max_duration():
    client = api.LiveKitAPI(url="https://your-livekit-url", api_key="KEY", api_secret="SECRET")

    d = Duration()
    d.FromSeconds(600)  # 10 minutes

    req = api.UpdateSIPInboundTrunkRequest(
        trunk=api.SIPInboundTrunkInfo(
            id="trunk-1234-abcd",       # <- faux trunk ID
            name="Twilio Inbound",
            max_call_duration=d,
        )
    )

    resp = await client.sip.update_sip_inbound_trunk(request=req)
    print("Updated trunk:", resp)

asyncio.run(update_trunk_max_duration())
Or the equivalent API JSON body:
Copy code
{
  "trunk": {
    "id": "trunk-1234-abcd",
    "name": "Twilio Inbound",
    "max_call_duration": "600s"
  }
}
2) Better in-agent fallback (if you can’t update trunk right now) • Instead of deleting the room, delete the SIP participant (more direct hangup). Use the job context to find the participant ID and call the delete SIP participant API. Minimal pattern:
Copy code
import asyncio

async def _end_call_after(ctx, seconds: int):
    await asyncio.sleep(seconds)
    # if you have participant_id in ctx or session, use it:
    await ctx.api.sip.delete_sip_participant(request=api.DeleteSIPParticipantRequest(sid="participant-123"))
If you don't have the participant ID, deleting the room can be attempted but is less reliable. Next step • Do you want me to: ◦ produce a ready-to-run snippet that updates your existing trunk (replace the faux ID with your trunk ID), or ◦ show how to reliably obtain the SIP participant ID from `ctx`/AgentSession and call DeleteSIPParticipant from inside your agent?
d
Figured it out...
thanks
g
@dazzling-truck-32153 were you able to figure it out for inbound calls?
t
Great — glad you figured it out. Yes, the guidance applies to inbound calls: set
max_call_duration
on the inbound trunk (or per-call via
CreateSIPParticipant
) and LiveKit will enforce the hard cap. If you want, I can: • give the exact API/SDK snippet using your real trunk ID, or • show how to reliably hang up from inside the agent by deleting the SIP participant (if you prefer an in-agent fallback). Which would you like?
d
@glamorous-oil-12326 Hey, yeah! Here's what I did:
Copy code
async def _end_call_after(ctx: JobContext, seconds: int):
    logger.info("app entrypoint alive")
    await asyncio.sleep(seconds)
    await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))


async def entrypoint(ctx: JobContext):
    """Main entry point for the telephony voice agent."""
    await ctx.connect()
    asyncio.create_task(_end_call_after(ctx, 600))
In my entrypoint of the main.py or whatever your main file is named. There's no logic, it just terminates the call. You can test with 30 instead of 600. Cheers!
🙌 1
t
Nice work and thanks for sharing your solution — that exact pattern will terminate inbound calls reliably from inside the agent. Two quick best-practice notes: • Trunk-level
max_call_duration
is still the most reliable hard cap (set via the SIP API/SDK). Your in-agent timer is a good fallback or quicker rollback. • Use short test values (e.g., 30s) when validating, then raise to production values (e.g., 600s). If you'd like, I can: • produce the UpdateTrunk snippet with your real trunk ID, or • show how to delete the SIP participant directly (more direct hangup) instead of deleting the room. Which would you prefer?
g
thanks!