exa-cost-tuning

0
0
Source

Optimize Exa costs through tier selection, sampling, and usage monitoring. Use when analyzing Exa billing, reducing API costs, or implementing usage monitoring and budget alerts. Trigger with phrases like "exa cost", "exa billing", "reduce exa costs", "exa pricing", "exa expensive", "exa budget".

Install

mkdir -p .claude/skills/exa-cost-tuning && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8153" && unzip -o skill.zip -d .claude/skills/exa-cost-tuning && rm skill.zip

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

About this skill

Exa Cost Tuning

Overview

Reduce Exa API costs through strategic search type selection, result caching, query deduplication, and usage monitoring. Exa charges per search request with costs varying by search type and content retrieval options.

Cost Drivers

FactorHigher CostLower Cost
Search typedeep-reasoning > deep > neuralkeyword < fast < instant
numResults10-100 results3-5 results
Content retrievalFull text + highlights + summaryMetadata only (no content)
Content lengthmaxCharacters: 5000maxCharacters: 500
Live crawlinglivecrawl: "always"Cached content (default)

Instructions

Step 1: Match Search Config to Use Case

import Exa from "exa-js";

const exa = new Exa(process.env.EXA_API_KEY);

// Define cost tiers per use case
const SEARCH_PROFILES = {
  // Cheapest: metadata-only keyword search
  "autocomplete": { type: "instant" as const, numResults: 3 },

  // Low cost: fast search with minimal content
  "quick-lookup": { type: "fast" as const, numResults: 3 },

  // Medium: balanced search for RAG
  "rag-context": {
    type: "auto" as const,
    numResults: 5,
    text: { maxCharacters: 1000 },
  },

  // Higher cost: deep research
  "deep-research": {
    type: "neural" as const,
    numResults: 10,
    text: { maxCharacters: 3000 },
    highlights: { maxCharacters: 500 },
  },
};

async function costAwareSearch(
  query: string,
  profile: keyof typeof SEARCH_PROFILES
) {
  const config = SEARCH_PROFILES[profile];
  if ("text" in config || "highlights" in config) {
    return exa.searchAndContents(query, config);
  }
  return exa.search(query, config);
}

Step 2: Query-Level Caching (40-60% Cost Reduction)

import { LRUCache } from "lru-cache";

const searchCache = new LRUCache<string, any>({
  max: 5000,
  ttl: 3600 * 1000, // 1-hour TTL
});

async function cachedSearch(query: string, opts: any) {
  const key = `${query.toLowerCase().trim()}:${opts.type}:${opts.numResults}`;
  const cached = searchCache.get(key);
  if (cached) return cached;

  const results = await exa.searchAndContents(query, opts);
  searchCache.set(key, results);
  return results;
}
// Typical RAG cache hit rate: 40-60%, directly cutting costs in half

Step 3: Query Deduplication for Batch Jobs

function deduplicateQueries(queries: string[]): string[] {
  const seen = new Set<string>();
  return queries.filter(q => {
    const normalized = q.toLowerCase().trim().replace(/\s+/g, " ");
    if (seen.has(normalized)) return false;
    seen.add(normalized);
    return true;
  });
}

// Before batch processing, deduplicate
const uniqueQueries = deduplicateQueries(allQueries);
console.log(`Deduped: ${allQueries.length} → ${uniqueQueries.length} queries`);
// Typical dedup rate: 20-40% for batch processing

Step 4: Use Keyword Search When Appropriate

// Neural search: best for semantic/conceptual queries (more expensive)
// Keyword search: best for specific terms/names (cheaper, faster)

function selectCostEffectiveType(query: string): "neural" | "keyword" | "auto" {
  // Use keyword for exact lookups
  if (query.match(/^https?:\/\//)) return "keyword";     // URL lookup
  if (query.match(/^[A-Z][a-z]+ [A-Z]/)) return "keyword"; // Proper nouns
  if (query.includes('"')) return "keyword";               // Quoted terms

  // Use neural for conceptual queries
  if (query.split(" ").length > 5) return "neural";
  return "auto"; // Let Exa decide for ambiguous queries
}

Step 5: Monitor Usage and Set Budget Alerts

set -euo pipefail
# Check API key usage
curl -s https://api.exa.ai/v1/usage \
  -H "x-api-key: $EXA_API_KEY" | \
  python3 -c "
import json, sys
d = json.load(sys.stdin)
print(f'Searches today: {d.get(\"searches_today\", \"N/A\")}')
print(f'Monthly total: {d.get(\"searches_this_month\", \"N/A\")}')
print(f'Monthly limit: {d.get(\"monthly_limit\", \"N/A\")}')
" 2>/dev/null || echo "Usage endpoint not available"
// Application-level budget tracking
class ExaBudgetTracker {
  private searchCount = 0;
  private dailyLimit: number;

  constructor(dailyLimit = 1000) {
    this.dailyLimit = dailyLimit;
  }

  async search(exa: Exa, query: string, opts: any) {
    if (this.searchCount >= this.dailyLimit) {
      throw new Error(`Daily Exa budget exceeded (${this.dailyLimit} searches)`);
    }
    this.searchCount++;
    return exa.search(query, opts);
  }

  getUsage() {
    return {
      used: this.searchCount,
      remaining: this.dailyLimit - this.searchCount,
      utilization: `${((this.searchCount / this.dailyLimit) * 100).toFixed(1)}%`,
    };
  }
}

Cost Optimization Checklist

  • Use keyword or fast for exact lookups instead of neural
  • Reduce numResults to 3-5 for most use cases (default is 10)
  • Use highlights instead of full text when snippets suffice
  • Implement query-level caching (LRU or Redis)
  • Deduplicate queries in batch pipelines
  • Set application-level budget limits
  • Monitor daily/monthly usage against budget

Error Handling

IssueCauseSolution
Monthly limit hit earlyUncached batch queriesAdd caching (40%+ savings)
High cost per resultnumResults too highReduce to 3-5 for most use cases
Budget spike from batchNo deduplicationDeduplicate before batch execution
402 NO_MORE_CREDITSAccount balance exhaustedTop up at dashboard.exa.ai

Resources

Next Steps

For performance optimization, see exa-performance-tuning. For reliability, see exa-reliability-patterns.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571700

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.