一位 r/Perplexity 用户报告 Sonar API 积分在没有警告的情况下被擦除。本教程构建了一个简单的监控层来跟踪使用情况并在耗尽之前发出警报。
前置条件
- 困惑 API 密钥
- Python 3.8+
- 通知渠道(Slack、电子邮件或短信)
操作指南
步骤 1: 记录每个 API 调用
使用使用日志记录 Sonar API 调用。
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')步骤 2: 计算运行成本
Sonar 定价:$1/M 代币输入/输出 + $5/1K 请求。
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步骤 3: 设置预算提醒
当使用量接近您的预算时发出警报。
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}')步骤 4: 构建迁移触发器
超出预算时自动切换到备份 API。
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 示例
Python
# Track Sonar usage, alert at 80% budget, failover to Scavio at 100%.
# Prevents surprise credit exhaustion.JavaScript 示例
JavaScript
// Same logging and alert pattern in JS/TS.预期输出
JSON
JSONL usage log, budget alerts at 80% and 100%, automatic failover to Scavio when Sonar budget is exceeded.