steep-balloon-41261
11/27/2025, 3:12 PMtall-airline-16756
11/27/2025, 3:12 PMtall-airline-16756
11/27/2025, 3:12 PMjoinedAt 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 analyticspurple-engine-50957
11/27/2025, 3:17 PMtall-airline-16756
11/27/2025, 3:17 PMCreateSIPParticipant 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?purple-engine-50957
11/27/2025, 3:22 PMtall-airline-16756
11/27/2025, 3:22 PMsip.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)
# 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
# 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).purple-engine-50957
11/27/2025, 3:57 PMtall-airline-16756
11/27/2025, 3:57 PMpurple-engine-50957
11/27/2025, 4:07 PMtall-airline-16756
11/27/2025, 4:08 PMsip.callStatus == active, and enforce short timeouts or forced cleanup for stuck participants.purple-engine-50957
11/27/2025, 4:29 PMtall-airline-16756
11/27/2025, 4:29 PMsip.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.purple-engine-50957
11/27/2025, 4:30 PMtall-airline-16756
11/27/2025, 4:30 PMleftAt. 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.purple-engine-50957
11/27/2025, 4:38 PMRoomInputOptions.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.tall-airline-16756
11/27/2025, 4:39 PMleftAt (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.purple-engine-50957
11/27/2025, 4:46 PMtall-airline-16756
11/27/2025, 4:46 PMsip.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?purple-engine-50957
11/27/2025, 5:38 PMtall-airline-16756
11/27/2025, 5:38 PMcurl -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 docspurple-engine-50957
11/27/2025, 6:04 PMtall-airline-16756
11/27/2025, 6:04 PMsip.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?