elegant-magician-80782
12/08/2025, 12:06 PMtall-airline-16756
12/08/2025, 12:06 PMtall-airline-16756
12/08/2025, 12:06 PMroomList grant). That API reports usage data but does not report the overall trial time left.
To proceed I can:
• Show how to call the Analytics API to pull current session minutes and connection time so you can compute usage yourself, or
• Help design a simple server-side tracker that sums Analytics API metrics into a “remaining trial time” value for your account.
Which would you like me to walk through?
Sources: Mini tutorial: setting up a LiveKit Cloud project | LiveKit Cloud billing | LiveKit docs | Agent Builder | LiveKit docs | Analytics API | LiveKit docselegant-magician-80782
12/08/2025, 12:07 PMtall-airline-16756
12/08/2025, 12:08 PMroomList grant (server-side).
◦ Example Node.js:
import { AccessToken } from 'livekit-server-sdk';
const at = new AccessToken(apiKey, apiSecret, { ttl: 60*60*24 });
at.addGrant({ roomList: true });
const token = at.toJwt();
1. List sessions for a date range:
◦ GET /api/project/{PROJECT_ID}/sessions?start=YYYY-MM-01&end=YYYY-MM-DD&limit=100
◦ Include header: Authorization: Bearer {TOKEN}
1. Important fields in the response to use:
◦ connectionMinutes — billable participant minutes per session (sum these to get total minutes)
◦ bandwidthOut — bytes sent (sum to get downstream data)
◦ createdAt, endedAt, numParticipants
1. Fetch session details for per-participant timing:
◦ GET /api/project/{PROJECT_ID}/sessions/{SESSION_ID}
◦ Use connectionDuration or participant timestamps to compute granular usage.
1. Pagination: request limit and page to iterate all sessions in the range.
2. Use a rolling date range (start = 1st of month, end = today) to calculate month-to-date usage.
B) Server-side tracker to compute remaining trial time
1. Decide which quota to track (e.g., WebRTC participant minutes: 5,000/month; agent minutes: 1,000/month).
2. Scheduler:
◦ Run a daily job (cron) that calls the Analytics API for the current month and updates your stored totals.
1. Aggregation logic (example in Node.js):
// Pseudocode
const sessions = await fetchSessions(projectId, token, startDate, endDate);
const totalMinutes = sessions.reduce((s, sess) => s + sess.connectionMinutes, 0);
const totalBytes = sessions.reduce((s, sess) => s + (sess.bandwidthOut||0), 0);
// Compare to quotas
const remainingMinutes = 5000 - totalMinutes;
const remainingGB = 50 - (totalBytes / (1024**3));
1. Alerts & thresholds:
◦ Send alerts at 75%, 90%, and 100% of quota.
◦ Optionally expose an endpoint /trial-status that returns current usage and remaining quota.
1. Handling accuracy:
◦ Reconcile overlaps or late session reporting by re-querying the last N days when the cron runs.
◦ Store session IDs you've already counted to avoid double-counting if you prefer idempotency.
1. Edge cases:
◦ If you need agent-specific minutes, filter sessions by agent identity prefix (if you use one) or by participant metadata; otherwise sum all and maintain separate counters where possible.
Notes and limitations
• There is no API to return a free-trial end date or an official "remaining trial time" value. You must compute remaining time by aggregating usage and comparing to the free quotas for your plan (e.g., 5,000 minutes, 50 GB) or reference your billing cycle.
• Use month-to-date ranges to match monthly quotas that reset on the 1st.
Would you like:
• a runnable Node.js script that implements the Analytics calls + monthly aggregation, or
• the same in Python, or
• a minimal /trial-status endpoint example to return remaining minutes and GB? Sources: Analytics API | LiveKit docs | LiveKit Cloud billing | LiveKit docs | Quotas and limits | LiveKit docselegant-magician-80782
12/08/2025, 12:08 PMtall-airline-16756
12/08/2025, 12:09 PMconnectionMinutes and bandwidthOut,
• Computes remaining minutes/GB against free quotas,
• Exposes a minimal Flask /trial-status endpoint that returns current usage and remaining quota.
Adjust PROJECT_ID, API token generation (server SDK), and quota values as needed.
1) Install dependencies
• pip install requests flask python-dotenv
2) Save this as app.py and set environment variables in a .env file:
• LIVEKIT_PROJECT_ID
• LIVEKIT_API_TOKEN (a token with roomList grant)
app.py
import os
import math
from datetime import datetime, timezone
from dotenv import load_dotenv
import requests
from flask import Flask, jsonify, request
load_dotenv()
PROJECT_ID = os.getenv("LIVEKIT_PROJECT_ID")
TOKEN = os.getenv("LIVEKIT_API_TOKEN")
# Free quotas (adjust if your plan differs)
QUOTA_MINUTES = 5000 # participant minutes per month
QUOTA_GB = 50 # downstream GB per month
API_BASE = "https://cloud-api.livekit.io/api/project"
app = Flask(__name__)
def iso_date(dt):
return dt.strftime("%Y-%m-%d")
def fetch_sessions(start_date: str, end_date: str, limit=100):
sessions = []
page = 0
headers = {"Authorization": f"Bearer {TOKEN}"}
while True:
url = f"{API_BASE}/{PROJECT_ID}/sessions?start={start_date}&end={end_date}&limit={limit}&page={page}"
resp = requests.get(url, headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
batch = data.get("sessions", [])
sessions.extend(batch)
# pagination: stop if fewer than limit returned
if len(batch) < limit:
break
page += 1
return sessions
def aggregate_month_to_date():
now = datetime.now(timezone.utc)
start = datetime(now.year, now.month, 1, tzinfo=timezone.utc)
start_s = iso_date(start)
end_s = iso_date(now)
sessions = fetch_sessions(start_s, end_s)
total_minutes = 0.0
total_bytes = 0
seen_ids = set()
for s in sessions:
sid = s.get("sessionId") or s.get("id") or s.get("session_id")
if sid and sid in seen_ids:
continue
seen_ids.add(sid)
cm = s.get("connectionMinutes") or 0
bo = s.get("bandwidthOut") or 0
# ensure numeric
try:
total_minutes += float(cm)
except Exception:
pass
try:
total_bytes += int(bo)
except Exception:
pass
total_gb = total_bytes / (1024 ** 3)
remaining_minutes = max(0, QUOTA_MINUTES - total_minutes)
remaining_gb = max(0, QUOTA_GB - total_gb)
pct_minutes = min(100, (total_minutes / QUOTA_MINUTES) * 100) if QUOTA_MINUTES else 0
pct_gb = min(100, (total_gb / QUOTA_GB) * 100) if QUOTA_GB else 0
return {
"period_start": start_s,
"period_end": end_s,
"used_minutes": round(total_minutes, 2),
"used_gb": round(total_gb, 3),
"remaining_minutes": round(remaining_minutes, 2),
"remaining_gb": round(remaining_gb, 3),
"percent_minutes_used": round(pct_minutes, 1),
"percent_gb_used": round(pct_gb, 1),
"sessions_counted": len(seen_ids),
}
@app.route("/trial-status", methods=["GET"])
def trial_status():
try:
data = aggregate_month_to_date()
return jsonify({"ok": True, "data": data})
except requests.HTTPError as e:
return jsonify({"ok": False, "error": f"API error: {e}"}), 502
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Notes, limitations, and recommended improvements
• Token generation: create LIVEKIT_API_TOKEN server-side using the LiveKit server SDK with the roomList grant and rotate regularly.
• This script sums connectionMinutes and bandwidthOut from session objects returned by the Analytics API. LiveKit does not provide a direct API for free-trial end date, so remaining time is computed by comparing usage to quotas.
• For accuracy:
◦ Re-query recent days in each run to handle late-arriving session records.
◦ Optionally store counted session IDs in a persistent DB to prevent double-counting.
• Add alerts (email/Slack) at thresholds (75%, 90%, 100%) as needed.
Would you like this packaged as a container image or with persistent storage examples (Redis/Postgres) for idempotent counting?