Tutorial

How to Track Perplexity Sonar API Credit Usage

Monitor Perplexity Sonar API credit usage and set alerts before credits are exhausted. Prevent surprise credit wipes.

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.

Python
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.

Python
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_cost

Step 3: Set budget alerts

Alert when usage approaches your budget.

Python
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.

Python
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

Python
# Track Sonar usage, alert at 80% budget, failover to Scavio at 100%.
# Prevents surprise credit exhaustion.

JavaScript Example

JavaScript
// Same logging and alert pattern in JS/TS.

Expected Output

JSON
JSONL usage log, budget alerts at 80% and 100%, automatic failover to Scavio when Sonar budget is exceeded.

Related Tutorials

Frequently Asked Questions

Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

Perplexity API key. Python 3.8+. Notification channel (Slack, email, or SMS). A Scavio API key gives you 500 free credits per month.

Yes. The free tier includes 500 credits per month, which is more than enough to complete this tutorial and prototype a working solution.

Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

Start Building

Monitor Perplexity Sonar API credit usage and set alerts before credits are exhausted. Prevent surprise credit wipes.