An r/Perplexity user reported Sonar API credits being wiped without warning. This tutorial builds a simple monitoring layer to track usage and alert before exhaustion.
Prerequisites
- Perplexity API key
- Python 3.8+
- Notification channel (Slack, email, or SMS)
Walkthrough
Step 1: Log every API call
Wrap the Sonar API call with usage logging.
import requests, json, datetime
def log_usage(model, tokens_in, tokens_out, cost):
with open('sonar_usage.jsonl', 'a') as f:
f.write(json.dumps({
'ts': datetime.datetime.now().isoformat(),
'model': model, 'tokens_in': tokens_in,
'tokens_out': tokens_out, 'cost': cost
}) + '\n')Step 2: Calculate running cost
Sonar pricing: $1/M tokens in/out + $5/1K requests.
def running_cost(log_file='sonar_usage.jsonl'):
total = 0
requests_count = 0
with open(log_file) as f:
for line in f:
entry = json.loads(line)
total += (entry['tokens_in'] + entry['tokens_out']) / 1e6
requests_count += 1
request_cost = (requests_count / 1000) * 5
return total + request_costStep 3: Set budget alerts
Alert when usage approaches your budget.
def check_budget(budget=50):
cost = running_cost()
if cost > budget * 0.8:
send_alert(f'Sonar API at {cost:.2f}/{budget} ({cost/budget*100:.0f}%)')
if cost > budget:
send_alert(f'OVER BUDGET: Sonar API at {cost:.2f}/{budget}')Step 4: Build a migration trigger
Auto-switch to backup API when budget exceeded.
def search(query, budget_exceeded=False):
if budget_exceeded:
# Failover to Scavio
return requests.post('https://api.scavio.dev/api/v1/search',
headers={'x-api-key': os.environ['SCAVIO_API_KEY']},
json={'platform': 'google', 'query': query}).json()
return sonar_search(query)Python Example
# Track Sonar usage, alert at 80% budget, failover to Scavio at 100%.
# Prevents surprise credit exhaustion.JavaScript Example
// Same logging and alert pattern in JS/TS.Expected Output
JSONL usage log, budget alerts at 80% and 100%, automatic failover to Scavio when Sonar budget is exceeded.