PE

perplexity-cost-tuning

Provides strategies to reduce Perplexity billing by routing queries to appropriate models, implementing caching, and monitoring token usage.

Install

mkdir -p .claude/skills/perplexity-cost-tuning && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/9044" && unzip -o skill.zip -d .claude/skills/perplexity-cost-tuning && rm skill.zip

Installs to .claude/skills/perplexity-cost-tuning

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Optimize Perplexity costs through model routing, caching, token limits,
71 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Route queries to appropriate model tiers based on complexity
  • Limit output tokens to reduce per-request costs
  • Implement LRU caching to eliminate duplicate search fees
  • Filter search domains to reduce content processing
  • Track token usage for budget monitoring

How it works

The skill provides patterns for model routing, token limiting, and caching to minimize API costs. It uses logic to distinguish between simple factual queries and complex research tasks to select the most cost-effective model.

Inputs & outputs

You give it
User query string and model selection
You get back
API response with cost-optimized token usage

When to use perplexity-cost-tuning

  • Route simple queries to cheaper sonar models
  • Implement caching to reduce redundant search fees
  • Analyze usage trends to forecast monthly bills
  • Set up budget alerts for API spend

About this skill

Perplexity Cost Tuning

Overview

Reduce Perplexity Sonar API costs. Perplexity charges per-token (input + output) plus a per-request fee that varies by search context size. The biggest cost lever is model selection: sonar-pro costs 3-15x more than sonar per request.

Pricing Reference

ModelInput $/M tokensOutput $/M tokensRequest Fee
sonar$1$1$5 per 1K requests
sonar-pro$3$15$5 per 1K requests
sonar-reasoning-pro$3$15$5 per 1K requests
sonar-deep-research$2$8$5 per 1K searches

Search context size (Low/Medium/High) affects the request fee. More context = higher fee.

Prerequisites

  • Perplexity API account with usage dashboard
  • Understanding of query patterns in your application
  • Cache infrastructure for search results

Instructions

Step 1: Route Queries to the Right Model

// 60-70% of queries can use sonar, saving 3-15x per query
function selectModel(query: string): "sonar" | "sonar-pro" {
  const simplePatterns = [
    /^what is/i, /^define/i, /^who is/i, /^when did/i,
    /current price/i, /^how many/i, /^is it true/i,
  ];
  if (simplePatterns.some((p) => p.test(query))) return "sonar";

  const complexPatterns = [
    /compare.*vs/i, /analysis of/i, /comprehensive/i,
    /pros and cons/i, /in-depth/i, /research/i,
  ];
  if (complexPatterns.some((p) => p.test(query))) return "sonar-pro";

  return "sonar"; // Default to cheapest
}

Step 2: Limit Output Tokens

set -euo pipefail
# Factual queries need ~100 tokens, not 4096
# Setting max_tokens dramatically reduces output costs

# Simple fact: 100 tokens = $0.0001 output
curl -X POST https://api.perplexity.ai/chat/completions \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sonar",
    "messages": [{"role": "user", "content": "Current population of Tokyo"}],
    "max_tokens": 100
  }'

# Research query: keep at 2048 only when needed
curl -X POST https://api.perplexity.ai/chat/completions \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sonar-pro",
    "messages": [{"role": "user", "content": "Compare React vs Vue in 2025 for enterprise apps"}],
    "max_tokens": 2048
  }'

Step 3: Cache to Eliminate Duplicate Queries

import { LRUCache } from "lru-cache";
import { createHash } from "crypto";

const searchCache = new LRUCache<string, any>({
  max: 10000,
  ttl: 4 * 3600_000, // 4-hour default TTL
});

async function cachedQuery(query: string, model: string) {
  const key = createHash("sha256")
    .update(`${model}:${query.toLowerCase().trim()}`)
    .digest("hex");

  const cached = searchCache.get(key);
  if (cached) return cached; // $0 cost

  const result = await perplexity.chat.completions.create({
    model,
    messages: [{ role: "user", content: query }],
  });
  searchCache.set(key, result);
  return result;
}

// Track cache effectiveness
function cacheStats() {
  return {
    size: searchCache.size,
    hitRate: `${((searchCache as any).hits / ((searchCache as any).hits + (searchCache as any).misses) * 100).toFixed(1)}%`,
  };
}

Step 4: Use Domain Filters to Reduce Search Cost

set -euo pipefail
# Restricting search domains = less content to process = lower request fee
curl -X POST https://api.perplexity.ai/chat/completions \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sonar",
    "messages": [{"role": "user", "content": "Python 3.13 release notes"}],
    "search_domain_filter": ["python.org", "docs.python.org"],
    "max_tokens": 500
  }'

Step 5: Track and Budget

class CostTracker {
  private costs: Array<{ model: string; tokens: number; timestamp: Date }> = [];

  record(model: string, usage: { total_tokens: number }) {
    this.costs.push({
      model,
      tokens: usage.total_tokens,
      timestamp: new Date(),
    });
  }

  dailySummary() {
    const today = this.costs.filter(
      (c) => c.timestamp.toDateString() === new Date().toDateString()
    );
    const sonarTokens = today.filter((c) => c.model === "sonar").reduce((s, c) => s + c.tokens, 0);
    const proTokens = today.filter((c) => c.model === "sonar-pro").reduce((s, c) => s + c.tokens, 0);

    return {
      queries: today.length,
      estimatedCost: (sonarTokens * 0.000001) + (proTokens * 0.000009), // rough estimate
      sonarQueries: today.filter((c) => c.model === "sonar").length,
      proQueries: today.filter((c) => c.model === "sonar-pro").length,
    };
  }
}

Cost Optimization Checklist

  • Default model is sonar (not sonar-pro)
  • max_tokens set on every request
  • Caching enabled for repeated queries
  • Model routing by query complexity
  • Domain filter used where applicable
  • Monthly budget cap set on API key
  • Cost tracking in production monitoring

Error Handling

IssueCauseSolution
High cost per queryUsing sonar-pro for everythingRoute simple queries to sonar
Low cache hit rateQueries too uniqueNormalize queries before hashing
Budget exhausted earlyNo spending capsSet monthly budget on API key
Unexpectedly high billNo max_tokens limitsSet max_tokens on all requests

Output

  • Model routing saving 60-70% on simple queries
  • Token limiting reducing output costs
  • Caching eliminating duplicate query costs
  • Cost tracking for budget monitoring

Resources

Next Steps

For architecture patterns, see perplexity-reference-architecture.

Prerequisites

Perplexity API account with usage dashboardCache infrastructure for search results

Limitations

  • Requires cache infrastructure for search results
  • Dependent on query normalization for effective caching

How it compares

This approach proactively manages costs through programmatic routing and caching rather than relying on default API settings.

Compared to similar skills

perplexity-cost-tuning side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
perplexity-cost-tuning (this skill)027dReviewIntermediate
nextjs-developer3282moNo flagsAdvanced
angular1004moReviewAdvanced
chrome-devtools417moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

nextjs-developer

zenobi-us

Expert Next.js developer mastering Next.js 14+ with App Router and full-stack features. Specializes in server components, server actions, performance optimization, and production deployment with focus on building fast, SEO-friendly applications.

328531

angular

sickn33

Modern Angular (v20+) expert with deep knowledge of Signals, Standalone Components, Zoneless applications, SSR/Hydration, and reactive patterns. Use PROACTIVELY for Angular development, component architecture, state management, performance optimization, and migration to modern patterns.

100129

chrome-devtools

mrgoonie

Browser automation, debugging, and performance analysis using Puppeteer CLI scripts. Use for automating browsers, taking screenshots, analyzing performance, monitoring network traffic, web scraping, form automation, and JavaScript debugging.

41157

flutter-expert

sickn33

Master Flutter development with Dart 3, advanced widgets, and multi-platform deployment. Handles state management, animations, testing, and performance optimization for mobile, web, desktop, and embedded platforms. Use PROACTIVELY for Flutter architecture, UI implementation, or cross-platform features.

73125

bullmq-specialist

davila7

BullMQ expert for Redis-backed job queues, background processing, and reliable async execution in Node.js/TypeScript applications. Use when: bullmq, bull queue, redis queue, background job, job queue.

2595

reviewing-nextjs-16-patterns

djankies

Review code for Next.js 16 compliance - security patterns, caching, breaking changes. Use when reviewing Next.js code, preparing for migration, or auditing for violations.

11106

Search skills

Search the agent skills registry