This message was deleted.
# ask-ai
s
This message was deleted.
t
Thanks for reaching out, Borys. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding to your questions about how LiveKit counts SIP minutes, why those minutes can be higher than your provider’s CDR, and how to export per-call data to reconcile. What LiveKit counts as “SIP minutes” • SIP minutes measure the time a SIP participant is connected to LiveKit (from when you create the SIP participant to when that participant leaves the room). • That includes: ◦ Time before the callee answers (ringing/dialing). ◦ Active call time while audio/media flows. ◦ Any time the SIP participant remains attached during connection teardown. • It does not include internal agent processing that isn’t part of the SIP participant’s connection, nor room time when no SIP participant is connected. Why LiveKit’s SIP minutes can be much higher than your provider CDR • LiveKit bills by connection duration (participant joined → left). Many telephony providers bill only answered talk time, so pre-answer ringing and teardown time inflate LiveKit minutes relative to provider CDR. • If your flows keep SIP participants connected during dialing and after hangup (signaling delays, retries, etc.), that adds extra minutes. • The “Total call duration” metric you saw is a different metric (likely measuring active media or another aggregation) and is not the same as SIP minutes, so its sum can be much lower than SIP minutes. How to export per-call granular data (to reconcile with provider CDR) 1. Use the Analytics API to list sessions for your timeframe: ◦ GET /api/project/$PROJECT_ID/sessions?start=YYYY-MM-DD&end=YYYY-MM-DD 1. Fetch session details: ◦ GET /api/project/$PROJECT_ID/sessions/$SESSION_ID ◦ Each session includes participants with
joinedAt
and
leftAt
. 1. Filter participants where
kind == "SIP"
and pull these fields: ◦
sip.callID
,
sip.phoneNumber
,
sip.trunkID
,
sip.callStatus
◦
participants[].joinedAt
,
participants[].leftAt
(timestamps you can use to compute seconds per call leg) 1. Use webhooks or SDK event streams to capture
sip.callStatus
transitions (
dialing
→
ringing
→
active
→
hangup
) if you need per-phase timestamps. Recommended reconciliation approach • Don’t rely on LiveKit SIP minutes for customer billing if your provider bills only answered minutes. • Compute billing minutes yourself by: ◦ Starting the billed timer when
sip.callStatus
becomes
active
(or when your provider considers the call answered). ◦ Stopping when
sip.callStatus
becomes
hangup
or when the SIP participant leaves. • Export session/participant data and compare
sip.callID
, phone number, and timestamps against provider CDR rows to match calls and reconcile minute differences. • Optionally implement a lightweight metering layer in your application that logs call events (initiate, answered, hangup) and calculates billable seconds using your provider’s rules. If you’d like, I can: • Show the exact Analytics API request/response fields to extract for CSV reconciliation. • Provide a small example script (curl or Node/Python) that pulls sessions, filters SIP participants, and outputs a per-call CSV with callID, phone number, joinedAt, leftAt, and computed seconds. Sources: Quotas and limits | LiveKit docs | LiveKit Pricing | SIP overview | LiveKit docs | SIP participant | LiveKit docs | Say hello to improved Cloud analytics
p
Why might "Total call duration" be much lower (~1,370 min) than the SIP minutes billing metric (~10,000 min)? Based on your response, the issue is with how our system is dialing, which causes SIP connection numbers to inflate, correct? How do we solve this?
t
You're right — the inflated SIP minutes strongly point to the dialing/connection workflow keeping SIP participants attached to LiveKit longer than the provider’s billable (answered) time. Below are concise reasons why and concrete fixes you can apply. Why this happens (brief) • LiveKit counts connection time from SIP participant creation until they leave the room — that includes dialing/ringing and any teardown delays. • If your flow creates the SIP participant at call initiation and leaves it connected until you or the provider signals end, pre-answer and post-hangup time add up. • If calls are retried, left in a ringing state, or not immediately removed on hangup, minutes accumulate even when the provider doesn’t bill them. How to fix it (practical steps) 1. Create the SIP participant only when you actually need the LiveKit connection ◦ Delay
CreateSIPParticipant
until you’re about to bridge media (or when you receive an answered signal from your provider if possible). 1. Stop the SIP participant promptly on non-answers or failed attempts ◦ On immediate outcomes like busy/no-answer/failed, call the API to remove the SIP participant so connection time stops accruing. 1. Use
sip.callStatus
transitions to measure and gate billing logic ◦ Start your internal “billable timer” when
sip.callStatus
becomes
active
. ◦ Stop when it becomes
hangup
or the participant leaves. 1. Clean up after hangup and on signaling delays ◦ Ensure your app removes the SIP participant as soon as hangup is confirmed. ◦ Implement a short timeout to forcibly remove stuck participants after a small grace period. 1. Reduce retries or long ringing windows ◦ Limit the number of outbound retries or shorten ring timeout before marking call failed and tearing down the participant. 1. Instrument and reconcile ◦ Export `joinedAt`/`leftAt` +
sip.callStatus
via the Analytics API or webhooks. ◦ Compute provider-aligned durations (answered-only) for billing and compare against LiveKit SIP minutes to validate improvements. Quick diagnostic checklist • Do you create SIP participants immediately on dial? (If yes → delay creation.) • Do you remove participants on no-answer/fail? (If no → add immediate removal.) • Are there retries or long ring timeouts? (If yes → shorten or limit.) • Are participants left in the room after hangup? (If yes → add forced cleanup timers.) If you want, I can provide: • A small example script to map
sip.callStatus
to billable seconds and export a CSV. • Example pseudocode showing where to create/remove the SIP participant and how to start/stop your billed timer. Which would you prefer?
p
Sure, please do.
t
Below are two concise deliverables you can use immediately: 1) Python script to export per-call SIP participant data from the Analytics API and compute provider-aligned (answered-only) seconds using
sip.callStatus
. 2) Pseudocode showing where to create/remove SIP participants and how to start/stop your billed timer to avoid inflated SIP minutes. Save your API token and project ID into environment variables
LIVEKIT_TOKEN
and
PROJECT_ID
before running. 1) Python script (Analytics export + reconciliation)
Copy code
# requirements: requests
import os, csv, requests, datetime

TOKEN = os.environ['LIVEKIT_TOKEN']
PROJECT = os.environ['PROJECT_ID']
BASE = 'https://cloud-api.livekit.io/api/project'

HEADERS = {'Authorization': f'Bearer {TOKEN}'}

def iso_to_dt(s):
    return datetime.datetime.fromisoformat(s.replace('Z','+00:00'))

def list_sessions(start, end):
    url = f"{BASE}/{PROJECT}/sessions?start={start}&end={end}"
    r = requests.get(url, headers=HEADERS)
    r.raise_for_status()
    return r.json().get('sessions', [])

def get_session(session_id):
    url = f"{BASE}/{PROJECT}/sessions/{session_id}"
    r = requests.get(url, headers=HEADERS)
    r.raise_for_status()
    return r.json()

def extract_sip_participants(session):
    out = []
    for p in session.get('participants', []):
        if p.get('kind') == 'SIP' or p.get('participantIdentity','').lower().startswith('sip:'):
            out.append(p)
    return out

def compute_answered_seconds(events):
    # events: list of dicts or timeline inferred from sip.callStatus and joinedAt/leftAt
    # Simple approach: use sip.callStatus timeline if available; otherwise use joinedAt/leftAt
    # Here we look for explicit status transitions in participant['sip']['statusTimeline'] if present
    answered_seconds = 0
    timeline = events.get('sip', {}).get('statusTimeline')  # optional structure
    if timeline:
        active_start = None
        for ev in timeline:
            st = ev.get('status')
            ts = iso_to_dt(ev['time'])
            if st == 'active':
                active_start = ts
            elif st in ('hangup','failed','busy','no-answer') and active_start:
                answered_seconds += (ts - active_start).total_seconds()
                active_start = None
        # if still active and participant has leftAt
        if active_start and events.get('leftAt'):
            answered_seconds += (iso_to_dt(events['leftAt']) - active_start).total_seconds()
        return int(answered_seconds)

    # Fallback: if no timeline, assume answered == entire join→leave if sip.callStatus == active during join
    joined = events.get('joinedAt')
    left = events.get('leftAt')
    if joined and left:
        return int((iso_to_dt(left) - iso_to_dt(joined)).total_seconds())
    return 0

def export(start, end, out_csv='livekit_sip_calls.csv'):
    sessions = list_sessions(start, end)
    rows = []
    for s in sessions:
        details = get_session(s['id'])
        for p in extract_sip_participants(details):
            sip = p.get('sip', {})
            answered = compute_answered_seconds(p)
            joined = p.get('joinedAt')
            left = p.get('leftAt')
            rows.append({
                'session_id': s['id'],
                'room': details.get('roomName'),
                'call_id': sip.get('callID') or p.get('sessionId') or '',
                'phone': sip.get('phoneNumber') or sip.get('to') or '',
                'trunk': sip.get('trunkID',''),
                'joinedAt': joined or '',
                'leftAt': left or '',
                'connection_seconds': int((iso_to_dt(left) - iso_to_dt(joined)).total_seconds()) if joined and left else '',
                'answered_seconds': answered,
            })
    # write CSV
    keys = ['session_id','room','call_id','phone','trunk','joinedAt','leftAt','connection_seconds','answered_seconds']
    with open(out_csv,'w',newline='') as f:
        w = csv.DictWriter(f, keys)
        w.writeheader()
        w.writerows(rows)
    print(f"Exported {len(rows)} rows to {out_csv}")

# Example usage:
# export('2025-11-01','2025-11-27')
Notes: • The script uses
participants[].joinedAt
and
leftAt
to compute total connection seconds and attempts to use a
sip.statusTimeline
if your session details include status transition events. If your Analytics response includes a different structure for status events, adapt
compute_answered_seconds
to parse that timeline. • If status timeline is unavailable, the script falls back to join→leave duration. For answered-only billing, prefer using explicit
sip.callStatus
transitions or webhook events that indicate
active
. 2) Pseudocode: where to create/remove SIP participants and gate billed timer
Copy code
# When user initiates outbound call:
1. Prepare call metadata (to_number, trunk, call_id)
2. OPTION A (recommended): Delay CreateSIPParticipant until just before bridging media
   - If possible, start dialing with provider first; when provider signals "ringing" or "attempting", then call CreateSIPParticipant.
   - Best: wait until provider reports "answered" then create SIP participant and bridge media.

3. OPTION B (if you must create at dial time): Create SIP participant but immediately monitor sip.callStatus

# During call lifecycle:
- On sip.callStatus == 'dialing' or 'ringing':
   - Do NOT start billed timer.
   - If status becomes 'no-answer' / 'failed' / 'busy': immediately call RemoveParticipant to stop LiveKit connection.
   - If you need retries, remove participant between retries and recreate for the next attempt.

- On sip.callStatus == 'active':
   - Start billed timer for this call leg (log start timestamp).
   - Continue normal media.

- On hangup or sip.callStatus == 'hangup':
   - Stop billed timer (log end timestamp).
   - Call RemoveParticipant to immediately detach SIP participant.
   - If RemoveParticipant fails or no hangup event within X seconds, force remove after short grace period (e.g., 3–10s).

# Cleanup safety:
- Periodically scan active SIP participants; if a participant is in 'dialing' or 'ringing' longer than a configured threshold (e.g., 60s), remove it and mark call failed.
If you want, I can now: • Provide the Node or curl equivalents of the Analytics export. • Tailor the Python script to your actual Analytics response JSON (paste a sample session JSON and I’ll adapt the parser).
p
Does following table seems fair to say? If so, does livekit charge for ringing? Be brief.
t
I can’t judge the table without seeing it, but yes — LiveKit’s SIP minutes include ringing (pre‑answer) time.
p
Does livekit charge for calls with Failed status and canceled/INVITE failed: sip status: 480: Temporarily unavailable error or other? So at this point in time we will be wasting only 15 calling seconds? What if call is not answered or ends in some other way? What if call is accepted and then user hangs up? Be brief.
t
Short answers: • Yes — LiveKit charges SIP minutes for any SIP participant connection from creation until the participant leaves the room. That includes failed/canceled calls and SIP errors (e.g., 480) if the SIP participant remained connected during the attempt. • If a failed/canceled attempt lasted ~15 seconds while the SIP participant was connected, LiveKit will count those ~15 seconds toward SIP minutes. • If a call is not answered but the SIP participant stayed connected (ringing), those ringing seconds are counted. • If a call is answered and then the user hangs up, LiveKit counts the full connection duration (including pre-answer, active, and any teardown until the participant is removed). To minimize “wasted” minutes: remove the SIP participant immediately on failure/no-answer, start billed timers only on
sip.callStatus == active
, and enforce short timeouts or forced cleanup for stuck participants.
p
I've decided to test the same thing for inbound calls. Same situation. After user hangup session keeps going for 48 seconds. Same for outbound calls. Could the issue be with livekit itself?
t
Thanks — I’m responding to your observation that sessions keep running ~48s after hangup for both inbound and outbound. Short answer: this behavior is usually because the SIP participant remains connected to the LiveKit room after the remote hangup (signaling delays or missing cleanup), not a LiveKit billing bug. LiveKit counts connection time from participant creation until they leave the room, so any delay before removing the SIP participant will accrue minutes. What to check and fix (brief) • Verify your app receives the provider’s hangup/final SIP response and calls RemoveParticipant (or otherwise disconnects the SIP participant) immediately. • Inspect
sip.callStatus
transitions and webhook events to confirm when hangup is seen by LiveKit vs when the participant is removed. • Add a forced cleanup: if a SIP participant remains after hangup for >X seconds (e.g., 5–10s), call RemoveParticipant programmatically. • If your provider sends late BYE/480/other errors, ensure your signaling handler treats those as terminal and removes the participant. • Log timestamps: provider CDR answer/hangup, your app’s hangup handling, LiveKit
leftAt
to pinpoint where the 48s delay occurs. If you want, paste one session’s JSON (session + participant with `joinedAt`/`leftAt` and
sip.callStatus
timeline) and I’ll point exactly where the delay happens and what code path should call RemoveParticipant.
p
How participant could still be in session, if they hang up? On telephony side it says call was 31 seconds, on livekit side it's 1minute 11 seconds.
t
Short answer: because LiveKit counts until the SIP participant is removed from the room — if your app or signaling doesn’t remove that participant immediately when the telephony leg ends, LiveKit will keep counting (so 31s on the provider vs 71s on LiveKit means ~40s of post-hangup connection still existed). Why that can happen (concise) • Provider marks the call ended at BYE/480 etc., but your app may not immediately receive/process that signal and call RemoveParticipant. • Signaling delays: late SIP responses, retransmits, or network lag can delay your app’s teardown. • Missing teardown path: your code might rely on the provider to disconnect media but not call the LiveKit API to remove the SIP participant. • Retries or keep-alive behavior can keep the SIP leg logically attached even after user hangup. What to do next (concrete, short) 1. Check logs/timestamps: provider CDR hangup time → your app’s receipt of hangup event → LiveKit participant
leftAt
. Identify where the gap occurs. 2. Ensure your hangup handler immediately calls RemoveParticipant (or otherwise ends the participant connection) when you detect BYE/480/hangup. 3. Add a forced cleanup: if a SIP participant remains > 5–10s after hangup, call RemoveParticipant automatically. 4. Monitor
sip.callStatus
and webhooks to assert transitions; use them to trigger removal and for reconciliation. If you share one session’s JSON (session + participant with
joinedAt
,
leftAt
, and any
sip
status timeline), I’ll pinpoint which step is delaying removal and the exact timestamp to act on.
p
But agent session in the log lasts for 31 seconds as well? After 3 seconds of user disconnecting from SIP call, there is log that says: "closing agent session due to participant disconnect (disable via
RoomInputOptions.close_on_disconnect=False
)" and then the sutting down of the job happens only at 58 seconds, while closing agent session happens at second 31. Between those time a some debugs are send to livekit.
t
Thanks — you're describing that the agent session closes at ~31s but the overall LiveKit participant/session isn't fully torn down until ~58s, with some debug traffic in between. That matches the root cause: LiveKit charges until the SIP participant is removed, not when your agent session code logs "closed." Concise diagnosis • "Closing agent session" is your app's higher‑level cleanup — it may stop media/logic, but the SIP participant can remain attached until the LiveKit participant is explicitly removed or the underlying job finishes. • Any debug/keepalive signaling or delayed teardown work (retries, pending tasks, websocket messages) can keep the participant connection alive, producing the extra ~27s you see. • LiveKit counts connection time from participant join → left; the extra time between agent close and job shutdown is what you’re being billed for. Exactly what to check and quick fixes 1. Correlate timestamps: ◦ Provider CDR hangup ◦ Your log "closing agent session" time ◦ LiveKit participant
leftAt
(session JSON) This identifies whether the delay is in your app or in LiveKit signaling. 1. Ensure immediate participant removal: ◦ When you detect the SIP hangup (BYE/480 or provider CDR/hangup event), call RemoveParticipant (or the equivalent API) right away — not just higher-level agent cleanup. ◦ Do this even if you already closed the agent session. 1. Shorten teardown work that blocks removal: ◦ Avoid blocking cleanup tasks that delay calling RemoveParticipant (move long debug uploads / metrics flushes to background jobs). ◦ If a shutdown job must run, call RemoveParticipant first, then let the job finish. 1. Add a forced cleanup timeout: ◦ If participant still present X seconds after agent close (e.g., 3–5s), force RemoveParticipant to avoid long tails. 1. Inspect debug traffic: ◦ If your app sends repeated debug messages after agent close, stop or defer them until after participant removal. If you’d like, paste the participant/session JSON (joinedAt, leftAt, any sip status timeline) and the exact log timestamps; I’ll mark which timestamp you should act on and show the minimal placement to call RemoveParticipant so billing stops immediately.
p
Can you tell me exactly what to do to make sure that session closes properly as soon as participant disconnects? We need to get the logs and close the room as quickly as the same second user leaves.
t
Responding to: "How to ensure session closes immediately when participant disconnects." Follow these steps to detect the SIP hangup and remove the participant (or close the room) as soon as the user leaves. 1) Detect the hangup quickly • Listen for SIP hangup signals from your provider (BYE, 480, final failure) and treat them as terminal. • Also subscribe to LiveKit events: use webhooks or server SDK event handlers for participant left/disconnected and
sip.callStatus
transitions (e.g.,
hangup
,
failed
,
no-answer
). 2) On hangup event — do these immediately, in this order • Call RemoveParticipant (or the server SDK equivalent) for that SIP participant to detach them from the room. • Record provider CDR / hangup timestamp and mark the call ended in your app logs. • Respond to the provider (if your flow requires) and stop any retries or keepalive messages for that leg. 3) Ensure your cleanup is not blocked • Call RemoveParticipant before running any long-running shutdown tasks (debug uploads, metrics flush, retries). • Make RemoveParticipant a non-blocking, highest-priority call; background the rest of the teardown work. • If using async jobs, await the RemoveParticipant result but do not wait on unrelated I/O. 4) Add forced cleanup fallback • After detecting hangup or participant-left, start a short timer (3–10 seconds). If LiveKit participant still present after the timer, call RemoveParticipant again or call RemoveParticipant unconditionally at timer expiry. • Periodic sweeper: every N seconds, scan for SIP participants in `dialing`/`ringing` state older than threshold and remove them. 5) Instrument timestamps for debugging/reconciliation • Log: provider hangup time, your hangup handler receipt time, RemoveParticipant request time, LiveKit
leftAt
time from Analytics or webhook. • Compare these to find the exact delay source. 6) Minimal code placement (pseudo) • On provider hangup handler: a. stop retries/keepalives b. call livekit.removeParticipant(room, participantId) c. log timestamps d. kick off background tasks (debug/metrics) and return 7) Webhook safety net • Enable LiveKit participant-left webhooks. If your app misses a provider event, the webhook will still notify you when LiveKit sees the participant leave so you can reconcile and enforce cleanup. 8) Test checklist • Simulate hangup from provider; assert RemoveParticipant request is sent within <1s. • Verify LiveKit
leftAt
equals RemoveParticipant time (or within 1s). • Verify no debug/keepalive traffic is sent after RemoveParticipant. • If delay persists, share one session JSON + logs and I will pinpoint the exact step to move RemoveParticipant earlier. If you want, I’ll provide a short Node or Python snippet showing exactly where to call
removeParticipant
in your hangup handler. Which language do you prefer?
p
is there an api call to get all calls from x datetime to y datetime to see all the calls data and their length? Be brief/
t
Yes — use the Analytics API's List Sessions endpoint to get all sessions between two dates (includes `createdAt`/`endedAt`/`connectionMinutes`). Example:
Copy code
curl -H "Authorization: Bearer $TOKEN" \
"https://cloud-api.livekit.io/api/project/$PROJECT_ID/sessions?start=2024-01-12&end=2024-01-13"
Notes: • Response includes per-session fields like
createdAt
,
endedAt
, and
connectionMinutes
. • Available to LiveKit Cloud customers on Scale plan or higher. Sources: Analytics API | LiveKit docs
p
Okay. Is this okay that call recording and session itself is so much longer than actual SIP telephony call logged in livekit?
t
Short answer: Yes — it's expected that LiveKit recordings and session durations can be longer than your telephony provider's SIP CDR. Why: • LiveKit measures until the SIP participant leaves the room (join → left), so ringing, connection teardown, and any delayed cleanup are included. • Recordings follow the same lifecycle: if the participant or room remains open, recording continues even after the provider considers the call ended. What to do (brief): • Stop/remove the SIP participant immediately on provider hangup (BYE/480) by calling RemoveParticipant. • Stop or trim recordings when
sip.callStatus
becomes
hangup
or when you remove the participant. • Add a forced cleanup timer (3–10s) to remove stuck participants and stop recordings if left alive after hangup. • Log provider hangup time, RemoveParticipant request time, and LiveKit
leftAt
to verify alignment. If you want, I can provide a short snippet (Node or Python) that calls RemoveParticipant and stops the recording in your hangup handler. Which language?