exa-pack
Complete Exa integration skill pack with 30 skills covering neural search, semantic retrieval, web search API, and AI-powered discovery. Flagship+ tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install exa-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> 30 Claude Code skills for Exa neural search API integration — from first query to production RAG pipelines
Exa is a neural search API at api.exa.ai that retrieves web content using semantic similarity. Unlike traditional search engines, Exa understands query meaning and returns contextually relevant results with full text, highlights, and AI-generated summaries.
SDK: exa-js (npm) / exa-py (PyPI) | Auth: x-api-key header | Rate limit: 10 QPS default
Skills (30) plugin-local skills
Apply advanced debugging techniques for hard-to-diagnose Exa issues.
Exa Advanced Troubleshooting
Prerequisites
- A bounded non-sensitive reproduction, affected environment/version, expected behavior, and redaction policy.
- Authority to inspect aggregate diagnostics and a named owner for escalation.
Output
- A minimal redacted root-cause record with evidence, remediation, owner, and verification result.
- A safe vendor/internal escalation packet without raw sensitive queries, result content, or API keys.
Examples
Reproduce a retrieval-quality issue with a sanitized query and approved domain filter, compare response metadata and aggregate timing to the expected contract, then test one scoped configuration fix. If unresolved, submit only the redacted request category/options/correlation evidence through the approved support channel.
Overview
Deep debugging for complex Exa issues: latency spikes, intermittent failures, result quality degradation, and content retrieval failures. All Exa error responses include a requestId — always capture it.
Instructions
Step 1: Layer-by-Layer Diagnostics
import Exa from "exa-js";
interface DiagnosticResult {
layer: string;
success: boolean;
latencyMs: number;
details: string;
}
async function diagnoseExa(): Promise<DiagnosticResult[]> {
const results: DiagnosticResult[] = [];
const exa = new Exa(process.env.EXA_API_KEY);
// Layer 1: DNS + Network
let start = performance.now();
try {
const resp = await fetch("https://api.exa.ai", { method: "HEAD" });
results.push({
layer: "network",
success: true,
latencyMs: performance.now() - start,
details: `HTTP ${resp.status}`,
});
} catch (err: any) {
results.push({
layer: "network",
success: false,
latencyMs: performance.now() - start,
details: err.message,
});
return results; // No point continuing if network fails
}
// Layer 2: Authentication
start = performance.now();
try {
await exa.search("auth test", { numResults: 1 });
results.push({
layer: "auth",
success: true,
latencyMs: performance.now() - start,
details: "API key valid",
});
} catch (err: any) {
results.push({
layer: "auth",
success: false,
latencyMs: performance.now() - start,
details: `${err.status}: ${err.message}`,
});
if (err.status === 401 || err.status === 402) return results;
}
// Layer 3: Neural search
start = performance.now();
try {
const r = await exa.search("test neural search quality", {
type: "neural",
numResults: 3,
});
results.push({
layer: "neural-search",
success: true,
latencyMs: performance.now() - start,
details: `${r.results.length}Choose and implement Exa architecture patterns at different scales: direct search, cached search, and RAG pipeline.
Exa Architecture Variants
Prerequisites
- A defined use case, data/policy classification, owner, source/citation requirements, and fallback decision.
- A non-sensitive evaluation set and review for any automation or architecture change.
Output
- A documented architecture choice tied to retrieval quality, latency, cost, policy, ownership, and rollback implications.
Examples
Compare a direct-search and a review-gated retrieval architecture using sanitized evaluation queries, score citation support and latency, and record the selected variant plus fallback. Do not choose an autonomous action path without explicit policy controls and human review for consequential decisions.
Overview
Three deployment architectures for Exa neural search at different scales. Each uses real Exa SDK methods: search, searchAndContents, findSimilar, getContents, and answer.
Decision Matrix
| Factor | Direct Search | Cached Search | RAG Pipeline |
|---|---|---|---|
| Volume | < 1K/day | 1K-50K/day | Any volume |
| Latency | 500-2000ms | ~50ms (cached) | 3-8s total |
| Use Case | Simple search UI | Content aggregation | AI answers with citations |
| Complexity | Low | Medium | High |
| Cache Required | No | Yes (Redis/LRU) | Yes |
| Exa Methods | searchAndContents |
searchAndContents + cache |
All methods |
Instructions
Variant 1: Direct Search Integration
Best for: Adding search to an existing app, < 1K queries/day.
import Exa from "exa-js";
import express from "express";
const app = express();
const exa = new Exa(process.env.EXA_API_KEY);
// Simple search endpoint
app.get("/api/search", async (req, res) => {
const query = req.query.q as string;
if (!query) return res.status(400).json({ error: "q required" });
try {
const results = await exa.searchAndContents(query, {
type: "auto",
numResults: 5,
text: { maxCharacters: 500 },
highlights: { maxCharacters: 300, query },
});
res.json(results.results.map(r => ({
title: r.title,
url: r.url,
snippet: r.highlights?.join(" ") || r.text?.substring(0, 200),
score: r.score,
})));
} catch (err: any) {
res.status(err.status || 500).json({ error: err.message });
}
});
Variant 2: Cached Search with Category Profiles
Best for: High-traffic search, 1K-50K queries/day, content discovery.
<Configure Exa CI/CD integration with GitHub Actions and automated testing.
Exa CI Integration
Output
- A credential-free pull-request lane for unit/schema/policy checks and a trusted scoped integration lane.
- A redacted CI receipt with validation result, failure classification, and safe retry path.
Examples
Run mocked request/policy tests on every pull request using sanitized fixtures, then execute one protected-branch development integration check with a scoped secret. If it fails, retain correlation/status metadata and back off; never give forked code an Exa key or private query set.
Overview
Set up CI/CD pipelines for Exa integrations with unit tests (mocked), integration tests (real API), and health checks. Uses GitHub Actions with secrets for API key management.
Prerequisites
- GitHub repository with Actions enabled
- Exa API key for testing
- npm/pnpm project with vitest or jest
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/exa-tests.yml
name: Exa Integration Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- run: npm ci
- run: npm run test:unit
# Unit tests use mocked Exa — no API key needed
integration-tests:
runs-on: ubuntu-latest
# Only run if API key is available (not on forks)
if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository
env:
EXA_API_KEY: ${{ secrets.EXA_API_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- run: npm ci
- run: npm run test:integration
timeout-minutes: 5
exa-health-check:
runs-on: ubuntu-latest
env:
EXA_API_KEY: ${{ secrets.EXA_API_KEY }}
steps:
- name: Verify Exa API connectivity
run: |
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-X POST https://api.exa.ai/search \
-H "x-api-key: $EXA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"CI health check","numResults":1}')
echo "Exa API status: $HTTP_CODE"
[ "$HTTP_CODE" = "200" ] || exit 1
Step 2: Configure Secrets
# Add API key as repository secret
gh secret set EXA_API_KEY --body "your-exa-api-key"
# For staging/production deployments
gh secret set EXA_API_KEY_STAGING --body "staging-key" --env staging
gh secret set EXA_API_KEY_PROD --body "prod-key" --env productioDiagnose and fix Exa API errors by HTTP code and error tag.
Exa Common Errors
Prerequisites
- A bounded non-sensitive reproduction, environment/version, expected behavior, and redaction rule for diagnostics.
Output
- A classified Exa failure with redacted evidence and a verified bounded remediation or escalation.
Error Handling
| Condition | Safe response |
|---|---|
| Authentication fails | Verify the scoped secret reference/environment; revoke/rotate if exposure is suspected. |
| Result is unexpected | Inspect supported sources, date, options, and citations with a sanitized query before changing policy. |
| Throttling occurs | Apply documented backoff and reduce concurrency; do not bulk retry. |
| Request includes sensitive data | Stop, sanitize/use an approved path, and follow exposure policy. |
Examples
For a failing request, record correlation ID, environment, status class, latency, and sanitized request category, then validate credentials and options against a non-sensitive fixture. Escalate with redacted evidence rather than full query/result content.
Overview
Quick reference for Exa API errors by HTTP status code and error tag. All error responses include a requestId field — include it when contacting Exa support at hello@exa.ai.
Error Reference
400 — Bad Request
| Error Tag | Cause | Solution |
|---|---|---|
INVALID_REQUEST_BODY |
Malformed JSON or missing required fields | Validate JSON structure and required query field |
INVALID_REQUEST |
Conflicting parameters | Remove contradictory options (e.g., date filters with company category) |
INVALID_URLS |
Malformed URLs in getContents |
Ensure URLs have https:// protocol |
INVALID_NUM_RESULTS |
numResults > 100 with highlights | Reduce to <= 100 or remove highlights |
INVALID_JSON_SCHEMA |
Bad schema in summary.schema |
Validate JSON schema syntax |
NUM_RESULTS_EXCEEDED |
Exceeds plan limit | Check your plan's max results |
NO_CONTENT_FOUND |
No content at provided URLs | Verify URLs are accessible |
401 — Unauthorized
# Verify your API key is set and valid
echo "Key set: ${EXA_API_KEY:+yes}"
# Test with curl
curl -s -o /dev/null -w "%{http_code}" \
-X POST https://api.exa.ai/search \
-H "x-api-key: $EXA_API_KEY" \
-H "Content-Type: application/jExecute Exa neural search with contents, date filters, and domain scoping.
Exa Core Workflow A — Neural Search
Overview
Primary workflow for Exa: semantic web search using search() and searchAndContents(). Exa's neural search understands query meaning rather than matching keywords, making it ideal for research, RAG pipelines, and content discovery. This skill covers search types, content extraction, filtering, and categories.
Prerequisites
exa-jsinstalled andEXA_API_KEYconfigured- Understanding of neural vs keyword search tradeoffs
Search Types
| Type | Latency | Best For |
|---|---|---|
auto (default) |
300-1500ms | General queries; Exa picks best approach |
neural |
500-2000ms | Conceptual/semantic queries |
keyword |
200-500ms | Exact terms, names, URLs |
fast |
p50 < 425ms | Speed-critical applications |
instant |
< 150ms | Real-time autocomplete |
deep |
2-5s | Maximum quality, light deep search |
deep-reasoning |
5-15s | Complex research questions |
Instructions
Step 1: Basic Neural Search
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Neural search: phrase your query as a statement, not a question
const results = await exa.search(
"comprehensive guide to building production RAG systems",
{
type: "neural",
numResults: 10, // max 100 for neural/deep
}
);
for (const r of results.results) {
console.log(`[${r.score.toFixed(2)}] ${r.title} — ${r.url}`);
console.log(` Published: ${r.publishedDate || "unknown"}`);
}
Step 2: Search with Content Extraction
// searchAndContents returns page text, highlights, and/or summaries
const results = await exa.searchAndContents(
"best practices for vector database selection",
{
type: "auto",
numResults: 5,
// Text: full page content as markdown
text: { maxCharacters: 2000 },
// Highlights: key excerpts relevant to a custom query
highlights: {
maxCharacters: 500,
query: "comparison of vector databases",
},
// Summary: LLM-generated summary tailored to a query
summary: { query: "which vector database should I choose?" },
}
);
for (const r of results.results) {
console.log(`## ${r.title}`);
console.log(`Summary: ${r.summary}`);
console.log(`Highlights: ${r.highlights?.join(" ... ")}`);
console.log(`Full text: ${r.text?.substring(0, 300)}...`);
}
Step 3: Da
Execute Exa findSimilar, getContents, answer, and streaming answer workflows.
Exa Core Workflow B — Similarity, Contents & Answer
Overview
Secondary Exa workflow covering three endpoints beyond search: findSimilar (discover pages semantically related to a URL), getContents (retrieve text/highlights for known URLs), and answer (get AI-generated answers with web citations). These complement the primary search workflow in exa-core-workflow-a.
Prerequisites
exa-jsinstalled andEXA_API_KEYconfigured- Familiarity with
exa-core-workflow-asearch patterns
Instructions
Step 1: Find Similar Pages
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// findSimilar takes a URL (not a query string) and returns
// pages with semantically similar content
const similar = await exa.findSimilar(
"https://openai.com/research/gpt-4",
{
numResults: 10,
excludeSourceDomain: true, // exclude openai.com from results
startPublishedDate: "2024-01-01T00:00:00.000Z",
excludeDomains: ["reddit.com", "twitter.com"],
}
);
for (const r of similar.results) {
console.log(`${r.title} — ${r.url}`);
}
Step 2: Find Similar with Contents
// findSimilarAndContents combines similarity search + content extraction
const results = await exa.findSimilarAndContents(
"https://huggingface.co/blog/llama3",
{
numResults: 5,
text: { maxCharacters: 2000 },
highlights: { maxCharacters: 500, query: "open source LLM" },
excludeSourceDomain: true,
}
);
for (const r of results.results) {
console.log(`## ${r.title}`);
console.log(`URL: ${r.url}`);
console.log(`Highlights: ${r.highlights?.join(" | ")}`);
console.log(`Text preview: ${r.text?.substring(0, 300)}...\n`);
}
Step 3: Get Contents for Known URLs
// getContents retrieves page content for a list of URLs you already have
// Useful when you have URLs from a previous search or external source
const contents = await exa.getContents(
[
"https://arxiv.org/abs/2401.00001",
"https://arxiv.org/abs/2401.00002",
"https://blog.example.com/article",
],
{
text: { maxCharacters: 3000 },
highlights: { maxCharacters: 500 },
summary: { query: "key findings and methodology" },
livecrawl: "preferred", // try fresh, fall back to cache
livecrawlTimeout: 15000, // 15s timeout
// Subpage crawling: retrieve linked pages from each URL
subpages: 3, // crawl up to 3 subpages per URL
subpageTarget: "documentation", // find subpages matching this term
}
);
for (const r of contents.results) {
console.log(`${r.title}: ${r.text?.length || 0} charOptimize Exa costs through search type selection, caching, and usage monitoring.
Exa Cost Tuning
Prerequisites
- An aggregate usage/cost baseline, budget owner, approved data policy, and quality/latency SLO.
- Sanitized evaluation queries and a reversible change record.
Output
- A measured cost optimization with owner, policy/quality guardrails, and rollback threshold.
Examples
Compare aggregate request volume, model/search options, latency, quality, and error data in staging, change one approved caching or request-shaping parameter, and observe the result. Revert on quality, policy, or reliability regression; do not reduce privacy, citation, or source-validation safeguards merely to lower spend.
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
| Factor | Higher Cost | Lower Cost |
|---|---|---|
| Search type | deep-reasoning > deep > neural |
keyword < fast < instant |
| numResults | 10-100 results | 3-5 results |
| Content retrieval | Full text + highlights + summary | Metadata only (no content) |
| Content length | maxCharacters: 5000 |
maxCharacters: 500 |
| Live crawling | livecrawl: "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)
Implement Exa search result processing, content extraction, caching, and RAG context management.
Exa Data Handling
Output
- A policy-bound search/research data flow with classification, retention, access, redaction, and owner decisions.
- A verified boundary that keeps private queries, results, identifiers, and credentials out of unsafe logs, fixtures, and exports.
Overview
Manage search result data from Exa's neural search API. Covers content extraction scope control (text vs highlights vs summary), result caching with TTL, citation deduplication, token budget management for LLM context windows, and structured summary extraction.
Prerequisites
exa-jsSDK installed and configured- Optional:
lru-cachefor in-memory caching,ioredisfor Redis - Understanding of Exa content options (text, highlights, summary)
Instructions
Step 1: Control Content Extraction Scope
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Tier 1: Metadata only (cheapest, fastest)
async function searchMetadataOnly(query: string) {
return exa.search(query, {
type: "auto",
numResults: 10,
// No content options — returns URLs, titles, scores only
});
}
// Tier 2: Highlights only (balanced cost/value)
async function searchWithHighlights(query: string) {
return exa.searchAndContents(query, {
numResults: 10,
highlights: {
maxCharacters: 500,
query: query, // focus highlights on the original query
},
});
}
// Tier 3: Full text with character limit
async function searchWithText(query: string, maxChars = 2000) {
return exa.searchAndContents(query, {
numResults: 5,
text: { maxCharacters: maxChars },
highlights: { maxCharacters: 300 },
});
}
// Tier 4: Structured summary (LLM-generated per result)
async function searchWithSummary(query: string) {
return exa.searchAndContents(query, {
numResults: 5,
summary: { query: query },
// summary returns a concise LLM-generated summary per result
});
}
Step 2: Result Caching with TTL
import { LRUCache } from "lru-cache";
import { createHash } from "crypto";
const searchCache = new LRUCache<string, any>({
max: 500,
ttl: 1000 * 60 * 60, // 1 hour default
});
function cacheKey(query: string, options: any): string {
return createHash("sha256")
.update(JSON.stringify({ query, ...options }))
.digest("hex");
}
async function cachedSearch(query: string, options: any = {}, ttlMs?: number) {
const key = cacheKey(query, options);
const cached = searchCache.get(key);
if (cached) return cached;
const results = await exa.searchAndContents(query, options);
searchCache.set(key, results, { ttl: ttlMs });
return results;
}
Step 3: Token Budget Management for RAG
exa-debug-bundle
View full skill →
Collect Exa debug evidence for support tickets and troubleshooting.
ReadBash(grep:*)Bash(curl:*)Bash(tar:*)Bash(node:*)Grep
Exa Debug Bundle
Prerequisites
- An issue owner, affected environment, approved support/incident destination, and redaction rules.
- Permission to collect only the minimum diagnostic metadata; no raw tokens, secrets, customer queries, or full result content.
Examples
For an unexpected search result, collect opaque correlation ID, environment, API/SDK version, query category (not text), request options, status class, latency, and timestamp. Reproduce with a sanitized query, review the bundle for tokens or private content, then share only through the approved channel.
Current State
!node --version 2>/dev/null || echo 'N/A' !npm list exa-js 2>/dev/null | grep exa-js || echo 'exa-js not installed' !echo "EXA_API_KEY: ${EXA_API_KEY:+SET (${#EXA_API_KEY} chars)}"
Overview
Collect all necessary diagnostic information for Exa support tickets. Exa error responses include a requestId field — always include it when contacting support at hello@exa.ai.
Instructions
Step 1: Quick Connectivity Test
set -euo pipefail
echo "=== Exa Connectivity Test ==="
echo "API Key: ${EXA_API_KEY:+SET (${#EXA_API_KEY} chars)}"
echo ""
# Test basic search endpoint
HTTP_CODE=$(curl -s -o /tmp/exa-debug.json -w "%{http_code}" \
-X POST https://api.exa.ai/search \
-H "x-api-key: $EXA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"debug connectivity test","numResults":1}')
echo "HTTP Status: $HTTP_CODE"
if [ "$HTTP_CODE" = "200" ]; then
echo "Status: HEALTHY"
python3 -c "import json; d=json.load(open('/tmp/exa-debug.json')); print(f'Results: {len(d.get(\"results\",[]))}')" 2>/dev/null
else
echo "Status: UNHEALTHY"
echo "Response:"
cat /tmp/exa-debug.json | python3 -m json.tool 2>/dev/null || cat /tmp/exa-debug.json
fi
Step 2: Capture Request/Response Details
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
async function debugSearch(query: string) {
const startTime = performance.now();
try {
const result = await exa.searchAndContents(query, {
numResults: 3,
text: { maxCharacters: 500 },
});
const duration = performance.now() - startTime;
console.log("=== Debug Info ===");
console.log(`Query: "${query}"`);
console.log(`Duration: ${duration.toFixed(0)}ms`);
console.log(`Results: ${result.results.length}`);
console.log(`Has autoprompt: ${!!result.autopromptString}`);
for (const r of result.results) {
console.log(` [${r.score.toFixed(3)}] ${r.title} (${r.url})`);
Deploy Exa integrations to Vercel, Docker, and Cloud Run platforms.
Exa Deploy Integration
Output
- A versioned staged deployment with scoped credentials, policy/configuration evidence, owner approval, and rollback reference.
- A protected path that prevents unreviewed retrieval/automation changes from affecting production.
Examples
Deploy a versioned integration to staging with sanitized queries and a scoped secret reference, verify health, guardrails, redacted metrics, and rollback, then promote an approved canary. Halt and restore on policy, quality, or error regression; do not deploy keys or private query fixtures in manifests.
Overview
Deploy applications using Exa's neural search API to production. Covers API endpoint creation, secret management per platform, caching for production traffic, and health check endpoints.
Prerequisites
- Exa API key stored in
EXA_API_KEYenvironment variable - Application using
exa-jsSDK - Platform CLI installed (vercel, docker, or gcloud)
Instructions
Step 1: Vercel Edge Function
// api/search.ts — Vercel API route
import Exa from "exa-js";
export const config = { runtime: "edge" };
export default async function handler(req: Request) {
if (req.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
const exa = new Exa(process.env.EXA_API_KEY!);
const { query, numResults = 5 } = await req.json();
if (!query || typeof query !== "string") {
return Response.json({ error: "query is required" }, { status: 400 });
}
try {
const results = await exa.searchAndContents(query, {
type: "auto",
numResults: Math.min(numResults, 20),
text: { maxCharacters: 1000 },
highlights: { maxCharacters: 300, query },
});
return Response.json({
results: results.results.map(r => ({
title: r.title,
url: r.url,
score: r.score,
snippet: r.text?.substring(0, 300),
highlights: r.highlights,
})),
});
} catch (err: any) {
const status = err.status || 500;
return Response.json(
{ error: err.message, requestId: err.requestId },
{ status }
);
}
}
# Deploy to Vercel
vercel env add EXA_API_KEY production
vercel --prod
Step 2: Docker Deployment
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/index.js"]
// src/server.ts — Express search API
import express from "express";
import Exa from "exa-js";
const app = express();
app.use(express.json());
const exa = new Exa(process.env.EXA_API_KEY!);
app.post(&Manage Exa API key scoping, team access controls, and domain restrictions.
Exa Enterprise RBAC
Output
- A least-privilege Exa project/credential role configuration with named owners, review evidence, and a tested revocation path.
- Verified separation between development, staging, and production access scopes.
Examples
Grant a development service identity only the search/research capability it needs, verify it against a non-sensitive query, and confirm it cannot use production credentials or administrative actions. Record ownership and access-review date; revoke broad roles and correct group mappings before continuing.
Overview
Manage access to Exa search API through API key scoping and application-level controls. Exa is API-key-based (no built-in RBAC), so access control is implemented through multiple API keys per use case, application-layer permission enforcement, domain restrictions per team, and per-key usage monitoring.
Prerequisites
- Exa API account with team/enterprise plan
- Dashboard access at dashboard.exa.ai
- Multiple API keys for key isolation
Instructions
Step 1: Key-Per-Use-Case Architecture
// config/exa-keys.ts
import Exa from "exa-js";
// Create separate clients for each use case
const exaClients = {
// High-volume RAG pipeline — production key with higher limits
ragPipeline: new Exa(process.env.EXA_KEY_RAG!),
// Internal research tool — lower volume key
researchTool: new Exa(process.env.EXA_KEY_RESEARCH!),
// Customer-facing search — separate key for isolation
customerSearch: new Exa(process.env.EXA_KEY_CUSTOMER!),
};
export function getExaForUseCase(
useCase: keyof typeof exaClients
): Exa {
const client = exaClients[useCase];
if (!client) throw new Error(`No Exa client for use case: ${useCase}`);
return client;
}
Step 2: Application-Level Permission Enforcement
// middleware/exa-permissions.ts
interface ExaPermissions {
maxResults: number;
allowedTypes: ("auto" | "neural" | "keyword" | "fast" | "deep")[];
allowedCategories: string[];
includeDomains?: string[]; // restrict to these domains
dailySearchLimit: number;
}
const ROLE_PERMISSIONS: Record<string, ExaPermissions> = {
"rag-pipeline": {
maxResults: 10,
allowedTypes: ["neural", "auto"],
allowedCategories: [],
dailySearchLimit: 10000,
},
"research-analyst": {
maxResults: 25,
allowedTypes: ["neural", "keyword", "auto", "deep"],
allowedCategories: ["research paper", "news"],
dailySearchLimit: 500,
},
"marketing-team": {
maxResults: 5,
allowedTypes: ["keyword", "auto"],
allowedCategories: ["company", "news"],
dailySeaCreate a minimal working Exa search example with real results.
Exa Hello World
Overview
Minimal working examples demonstrating all core Exa search operations: basic search, search with contents, find similar, and get contents. Each example is runnable standalone.
Prerequisites
exa-jsSDK installed (npm install exa-js)EXA_API_KEYenvironment variable set- Node.js 18+ with ES module support
Instructions
Step 1: Basic Search (Metadata Only)
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Basic search returns URLs, titles, and scores — no page content
const results = await exa.search("best practices for building RAG pipelines", {
type: "auto", // auto | neural | keyword | fast | instant
numResults: 5,
});
for (const r of results.results) {
console.log(`[${r.score.toFixed(2)}] ${r.title}`);
console.log(` ${r.url}`);
}
Step 2: Search with Contents
// searchAndContents returns text, highlights, and/or summary with each result
const results = await exa.searchAndContents(
"how transformers work in large language models",
{
type: "neural",
numResults: 3,
text: { maxCharacters: 1000 },
highlights: { maxCharacters: 500, query: "attention mechanism" },
summary: { query: "explain transformers simply" },
}
);
for (const r of results.results) {
console.log(`## ${r.title}`);
console.log(`URL: ${r.url}`);
console.log(`Summary: ${r.summary}`);
console.log(`Text preview: ${r.text?.substring(0, 200)}...`);
console.log(`Highlights: ${r.highlights?.join(" | ")}`);
console.log();
}
Step 3: Find Similar Pages
// findSimilar takes a URL and returns semantically similar pages
const similar = await exa.findSimilarAndContents(
"https://arxiv.org/abs/2301.00234",
{
numResults: 5,
text: { maxCharacters: 500 },
excludeSourceDomain: true,
}
);
console.log("Pages similar to the seed URL:");
for (const r of similar.results) {
console.log(` ${r.title} — ${r.url}`);
}
Step 4: Get Contents for Known URLs
// getContents retrieves page content for specific URLs
const contents = await exa.getContents(
["https://example.com/article-1", "https://example.com/article-2"],
{
text: { maxCharacters: 2000 },
highlights: { maxCharacters: 500 },
livecrawl: "preferred",
livecrawlTimeout: 10000,
}
);
for (const r of contents.results) {
console.log(`${r.title}: ${r.text?.length} chars retrieved`);
}
Output
- Working TypeScript file with Exa client initialization
- Search results printed to console with titles, URLs, and scores
- C
Execute Exa incident response with triage, mitigation, and postmortem procedures.
Exa Incident Runbook
Prerequisites
- An incident ID, commander, affected environment/service, approved communication route, and redacted diagnostic access.
- A safe mitigation/rollback path plus data/policy owner for query/result exposure decisions.
Instructions
- Declare scope and severity, preserve minimal redacted evidence, and stabilize customer or automation impact.
- Use the documented pause, credential revocation, rate reduction, or fallback before deep diagnosis.
- Verify recovery against the SLO and policy boundary, then create root-cause/prevention follow-up work.
Output
- A time-stamped incident record with scope, mitigation, evidence, owner, and verified recovery or escalation.
Examples
For an unexpected result or availability incident, record opaque request IDs, environment, status/latency aggregates, and policy category, then reduce traffic or use the approved fallback. Do not share raw customer queries, result content, or credentials in incident channels.
Overview
Rapid incident response procedures for Exa search API issues. Exa errors include a requestId field for support escalation. Default rate limit is 10 QPS. Contact hello@exa.ai for urgent production issues.
Severity Levels
| Level | Definition | Response Time | Example |
|---|---|---|---|
| P1 | All Exa calls failing | < 15 min | 401/500 on every request |
| P2 | Degraded performance | < 1 hour | High latency, partial failures |
| P3 | Minor impact | < 4 hours | Empty results, content fetch failures |
| P4 | No user impact | Next business day | Monitoring gaps |
Quick Triage (Run First)
set -euo pipefail
echo "=== Exa Triage ==="
# 1. Test API connectivity
echo -n "API Status: "
HTTP_CODE=$(curl -s -o /tmp/exa-triage.json -w "%{http_code}" \
-X POST https://api.exa.ai/search \
-H "x-api-key: $EXA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"triage test","numResults":1}')
echo "$HTTP_CODE"
# 2. Show error details if not 200
if [ "$HTTP_CODE" != "200" ]; then
echo "Error response:"
cat /tmp/exa-triage.json | python3 -m json.tool 2>/dev/null || cat /tmp/exa-triage.json
fi
# 3. Check if it's a key issue
echo ""
echo "API Key: ${EXA_API_KEY:+SET (${#EXA_API_KEY} chars)}"
Decision Tree
Exa API returning errors?
├── YES: What HTTP code?
│ ├── 401 → API key invalid/expired → Regenerate at dashboard.exa.ai
│ ├── 402 → Credits exhausted → Top upInstall the exa-js SDK and configure API key authentication.
Exa Install & Auth
Overview
Install the official Exa SDK and configure API key authentication. Exa is a neural search API at api.exa.ai that retrieves web content using semantic similarity. Authentication uses the x-api-key header. The SDK is exa-js on npm or exa-py on PyPI.
Prerequisites
- Node.js 18+ or Python 3.10+
- Package manager (npm, pnpm, yarn, or pip)
- Exa account at dashboard.exa.ai
- API key from the Exa dashboard
Instructions
Step 1: Install the SDK
Node.js (exa-js)
set -euo pipefail
npm install exa-js
# or
pnpm add exa-js
Python (exa-py)
pip install exa-py
Step 2: Configure the API Key
# Set environment variable
export EXA_API_KEY="your-api-key-here"
# Or create .env file (add .env to .gitignore first)
echo 'EXA_API_KEY=your-api-key-here' >> .env
Add to .gitignore:
.env
.env.local
.env.*.local
Step 3: Initialize the Client
TypeScript
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
Python
from exa_py import Exa
import os
exa = Exa(api_key=os.environ["EXA_API_KEY"])
Step 4: Verify Connection
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
async function verifyConnection() {
try {
const result = await exa.search("test connectivity", { numResults: 1 });
console.log("Connected. Results:", result.results.length);
console.log("First result:", result.results[0]?.title);
} catch (err: any) {
if (err.status === 401) {
console.error("Invalid API key. Check EXA_API_KEY.");
} else if (err.status === 402) {
console.error("No credits remaining. Top up at dashboard.exa.ai.");
} else {
console.error("Connection failed:", err.message);
}
}
}
verifyConnection();
Output
exa-jsorexa-pyinstalled in project dependenciesEXA_API_KEYenvironment variable configured.envadded to.gitignore- Successful search result confirming connectivity
Error Handling
| Error | HTTP Code | Cause | Solution | |
|---|---|---|---|---|
INVALID_API_KEY |
401 | Missing or invalid API key | Verify key at dashboard.exa.ai |
| Condition | Safe response |
|---|---|
| Result is unsupported or stale | Verify primary sources and date; do not treat retrieval as authoritative proof. |
| Query contains sensitive data | Stop, sanitize or use an approved path, and follow exposure policy. |
| Automation scope expands | Require explicit review and reduce it to a bounded task. |
Examples
For a compliance research task, constrain Exa to approved primary domains and date range, inspect each result/citation, and retain only the summarized, non-sensitive evidence. Reject results that lack support rather than widening the query into private data.
Overview
Real gotchas when integrating Exa's neural search API. Exa uses embeddings-based search rather than keyword matching, which creates a different class of failure modes than traditional search APIs. This skill covers the top pitfalls with wrong/right examples.
Pitfall 1: Keyword-Style Queries
Exa's neural search interprets natural language semantically. Boolean operators and keyword syntax degrade results.
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// BAD: keyword/boolean style — Exa ignores AND/OR
const bad = await exa.search(
"python AND machine learning OR deep learning 2024"
);
// GOOD: natural language statement
const good = await exa.search(
"recent tutorials on building ML models with Python",
{ type: "neural", numResults: 10 }
);
Pitfall 2: Wrong Search Type
Using neural search for exact lookups (URLs, names) or keyword search for conceptual queries silently degrades quality.
// BAD: neural search for a specific URL/identifier
const bad = await exa.search("arxiv.org/abs/2301.00001", { type: "neural" });
// GOOD: keyword for exact terms, neural for concepts
const exactMatch = await exa.search("arxiv.org/abs/2301.00001", {
type: "keyword",
});
const conceptual = await exa.search(
"transformer aImplement Exa load testing, capacity planning, and scaling strategies.
Exa Load & Scale
Output
- A measured, rate-aware search/research workload with bounded concurrency, idempotent work tracking, owner, and rollback threshold.
- An aggregate capacity receipt that excludes raw queries, customer data, API keys, and full result content.
Examples
Use sanitized test queries to increase concurrency gradually below the approved limit, record aggregate latency, 429s, completion, and queue age, and apply backoff with jitter. Reduce load on throttling or quality regression; do not replay customer queries or bypass policy/rate controls to reach a benchmark.
Overview
Load testing and capacity planning for Exa integrations. Key constraint: Exa's default rate limit is 10 QPS. Scaling strategies focus on caching, request queuing, parallel processing within rate limits, and search type selection for latency budgets.
Prerequisites
- k6 load testing tool installed
- Test environment Exa API key (separate from production)
- Redis for result caching
Capacity Reference
| Search Type | Typical Latency | Max Throughput (10 QPS) |
|---|---|---|
instant |
< 150ms | 10 req/s (600/min) |
fast |
< 425ms | 10 req/s (600/min) |
auto |
300-1500ms | 10 req/s (600/min) |
neural |
500-2000ms | 10 req/s (600/min) |
deep |
2-5s | 10 req/s (600/min) |
With caching (50% hit rate): Effective throughput doubles to 20 req/s equivalent.
Instructions
Step 1: k6 Load Test Against Your Wrapper
// exa-load-test.js
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
stages: [
{ duration: "1m", target: 5 }, // Ramp up to 5 VUs
{ duration: "3m", target: 5 }, // Steady state
{ duration: "1m", target: 10 }, // Push toward rate limit
{ duration: "2m", target: 10 }, // Stress test
{ duration: "1m", target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ["p(95)<3000"], // 3s P95 for neural search
http_req_failed: ["rate<0.05"], // < 5% error rate
},
};
const queries = [
"best practices for building RAG systems",
"transformer architecture improvements 2025",
"TypeScript 5.5 new features",
"vector database comparison guide",
"AI safety alignment research",
];
export default function () {
const query = queries[Math.floor(Math.random() * queries.length)];
const response = http.post(
`${__ENV.APP_URL}/api/search`,
Configure Exa local development with hot reload, testing, and mock responses.
Exa Local Dev Loop
Output
- A small reviewed local Exa integration change with focused tests and normal source-control rollback.
- A redacted development verification receipt using sanitized queries and scoped credentials.
Overview
Set up a fast, reproducible local development workflow for Exa integrations. Covers project structure, mock responses for unit tests, integration test patterns, and hot-reload configuration.
Prerequisites
exa-jsinstalled andEXA_API_KEYconfigured- Node.js 18+ with npm/pnpm
vitestfor testing (orjest)
Instructions
Step 1: Project Structure
my-exa-project/
├── src/
│ ├── exa/
│ │ ├── client.ts # Singleton Exa client
│ │ ├── search.ts # Search wrappers
│ │ └── types.ts # Typed interfaces
│ └── index.ts
├── tests/
│ ├── exa.unit.test.ts # Mock-based unit tests
│ └── exa.integration.test.ts # Real API tests (needs key)
├── .env.local # Local secrets (git-ignored)
├── .env.example # Template for team
├── tsconfig.json
├── vitest.config.ts
└── package.json
Step 2: Package Setup
{
"scripts": {
"dev": "tsx watch src/index.ts",
"test": "vitest",
"test:unit": "vitest --testPathPattern=unit",
"test:integration": "vitest --testPathPattern=integration",
"build": "tsc"
},
"dependencies": {
"exa-js": "^1.0.0"
},
"devDependencies": {
"tsx": "^4.0.0",
"vitest": "^2.0.0",
"typescript": "^5.0.0"
}
}
Step 3: Mock Exa for Unit Tests
// tests/exa.unit.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";
// Mock the exa-js module
vi.mock("exa-js", () => {
return {
default: vi.fn().mockImplementation(() => ({
search: vi.fn().mockResolvedValue({
results: [
{ url: "https://example.com/1", title: "Test Result 1", score: 0.95 },
{ url: "https://example.com/2", title: "Test Result 2", score: 0.87 },
],
}),
searchAndContents: vi.fn().mockResolvedValue({
results: [
{
url: "https://example.com/1",
title: "Test Result 1",
score: 0.95,
text: "This is the full text content of the page.",
highlights: ["Key excerpt from the page"],
summary: "A summary of the page content.",
},
],
}),
findSimilar: vi.fn().mockResolvedValue({
reMigrate from other search APIs (Google, Bing, Tavily, Serper) to Exa neural search.
Exa Migration Deep Dive
Prerequisites
- An inventory of existing retrieval/data flows, policy classification, sanitized evaluation set, acceptance threshold, and rollback owner.
- Separate staging credentials and review for any automation or customer-query migration.
Output
- A staged migration record with compatibility/evaluation evidence, owner, observation window, and rollback configuration.
Examples
Run prior and target retrieval flows against sanitized evaluation queries in staging, compare aggregate citation/quality/latency/error data, then promote an approved canary. Roll back on policy or quality regression; do not bulk-replay customer queries or turn migration output into unreviewed decisions.
Current State
!npm list exa-js 2>/dev/null | grep exa-js || echo 'exa-js not installed' !npm list 2>/dev/null | grep -E '(google|bing|tavily|serper|serpapi)' || echo 'No competing search SDK found'
Overview
Migrate from traditional search APIs (Google Custom Search, Bing Web Search, Tavily, Serper) to Exa's neural search API. Key differences: Exa uses semantic/neural search instead of keyword matching, returns content (text/highlights/summary) in a single API call, and supports similarity search from a seed URL.
API Comparison
| Feature | Google/Bing | Tavily | Exa |
|---|---|---|---|
| Search model | Keyword | AI-enhanced | Neural embeddings |
| Content in results | Snippets only | Full text | Text + highlights + summary |
| Similarity search | No | No | findSimilar() by URL |
| AI answer | No | Yes | answer() + streamAnswer() |
| Categories | No | No | company, news, research paper, tweet, people |
| Date filtering | Limited | Yes | startPublishedDate / endPublishedDate |
| Domain filtering | Yes | Yes | includeDomains / excludeDomains (up to 1200) |
Instructions
Step 1: Install Exa SDK
set -euo pipefail
npm install exa-js
# Remove old SDK if replacing
# npm uninstall google-search-api tavily serpapi
Step 2: Create Adapter Layer
// src/search/adapter.ts
import Exa from "exa-js";
// Define a provider-agnostic search interface
interface SearchResult {
title: string;
url: string;
snippet: string;
score?: number;
publishedDate?: string;
}
interface SearchResponse {
results: SearchResult[];
query: string;
}
// Exa implementation
clConfigure Exa across development, staging, and production environments.
Exa Multi-Environment Setup
Output
- Isolated development, staging, and production configurations with separate scoped credentials, policy/routing controls, and owners.
- A synthetic-validation promotion receipt with a safe rollback path that avoids production-query experiments.
Examples
Validate a versioned configuration with sanitized queries in development, promote to staging using a separate key, and record quality/latency/policy results. Release through an approved production canary only; restore the prior configuration on regression and never copy production keys or private query data to lower environments.
Overview
Exa charges per search request at api.exa.ai. Multi-environment setup focuses on API key isolation per environment, request limits and caching to control costs in staging, and appropriate numResults/content settings per tier.
Prerequisites
- Exa API key(s) from dashboard.exa.ai
exa-jsinstalled (npm install exa-js)- Optional: Redis for search result caching in staging/production
Environment Strategy
| Environment | Key Isolation | numResults | Content | Cache TTL |
|---|---|---|---|---|
| Development | Shared dev key | 3 | highlights only | None |
| Staging | Staging key | 5 | text (1000 chars) | 5 min |
| Production | Prod key | 10 | text (2000 chars) | 1 hour |
Instructions
Step 1: Environment-Aware Configuration
// config/exa.ts
import Exa from "exa-js";
type Env = "development" | "staging" | "production";
interface ExaEnvConfig {
apiKey: string;
defaultNumResults: number;
maxCharacters: number;
searchType: "auto" | "neural" | "keyword";
cacheEnabled: boolean;
cacheTtlSeconds: number;
}
const configs: Record<Env, Omit<ExaEnvConfig, "apiKey"> & { keyVar: string }> = {
development: {
keyVar: "EXA_API_KEY",
defaultNumResults: 3,
maxCharacters: 500,
searchType: "auto",
cacheEnabled: false,
cacheTtlSeconds: 0,
},
staging: {
keyVar: "EXA_API_KEY_STAGING",
defaultNumResults: 5,
maxCharacters: 1000,
searchType: "auto",
cacheEnabled: true,
cacheTtlSeconds: 300, // 5 minutes
},
production: {
keyVar: "EXA_API_KEY_PROD",
defaultNumResults: 10,
maxCharacters: 2000,
searchType: "neural",
cacheEnabled: true,
cacheTtlSeconds: 3600, // 1 hour
},
};
export function getExaConfig(): ExaEnvConfig {
const env = (process.env.NODE_ENV || "development") as Env;Set up monitoring, metrics, and alerting for Exa search integrations.
Exa Observability
Output
- Bounded redacted metrics/traces for request outcome, latency, rate headroom, policy decision, source/citation coverage, and fallback behavior.
- An owned alert/runbook path that excludes raw queries, result content, identifiers, and credentials.
Examples
Emit aggregate metrics by environment, endpoint, status class, and policy outcome, then trigger a sanitized staging failure to verify alert routing. Record correlation ID and remediation time only; do not put customer queries, result text, or API keys into logs, dashboards, or tickets.
Overview
Monitor Exa search API performance, result quality, and cost efficiency. Key metrics: search latency by type (neural ~500-2000ms, keyword ~200-500ms), result count per query, cache hit rates, error rates by status code, and daily search volume for budget tracking.
Prerequisites
- Exa API integration in production
- Metrics backend (Prometheus, Datadog, or OpenTelemetry)
- Alerting system (PagerDuty, Slack, or equivalent)
Instructions
Step 1: Instrument the Exa Client
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Generic metrics emitter (replace with your metrics library)
function emitMetric(name: string, value: number, tags: Record<string, string>) {
// Prometheus: histogram/counter.observe(value, tags)
// Datadog: dogstatsd.histogram(name, value, tags)
// OpenTelemetry: meter.createHistogram(name).record(value, tags)
console.log(`[metric] ${name}=${value}`, tags);
}
async function trackedSearch(query: string, options: any = {}) {
const start = performance.now();
const type = options.type || "auto";
const hasContents = options.text || options.highlights || options.summary;
try {
const method = hasContents ? "searchAndContents" : "search";
const results = hasContents
? await exa.searchAndContents(query, options)
: await exa.search(query, options);
const duration = performance.now() - start;
emitMetric("exa.search.duration_ms", duration, { type, method });
emitMetric("exa.search.result_count", results.results.length, { type });
emitMetric("exa.search.success", 1, { type });
return results;
} catch (err: any) {
const duration = performance.now() - start;
const status = String(err.status || "unknown");
emitMetric("exa.search.duration_ms", duration, { type, status });
emitMetric("exa.search.error", 1, { type, status });
throw err;
}
}
Step 2: Track Result Quality
// Measure whether search results are actually used downstream
function trackResultUsage(
searchId: string,
resultIndex: number,
action: "clicked" | "used_in_conOptimize Exa API performance with search type selection, caching, and parallelization.
Exa Performance Tuning
Prerequisites
- A measured latency/throughput/quality/error baseline, sanitized evaluation set, SLO owner, and rollback threshold.
- Approved data/policy controls that remain in effect during tests.
Output
- A measured performance recommendation with policy/quality guardrails, owner, and reversible change record.
Examples
Measure sanitized staging queries, change one request option, cache behavior, or concurrency limit, and compare aggregate latency, quality, and errors against baseline. Revert on regression; do not disable citation, source, privacy, or human-review controls to improve a metric.
Overview
Optimize Exa search API response times for production workloads. Key levers: search type selection (instant < fast < auto < neural < deep), result count reduction, content scope control, result caching, and parallel query execution.
Latency by Search Type
| Type | Typical Latency | Use Case |
|---|---|---|
instant |
< 150ms | Real-time autocomplete, typeahead |
fast |
p50 < 425ms | Speed-critical user-facing search |
auto |
300-1500ms | General purpose (default) |
neural |
500-2000ms | Best semantic quality |
deep |
2-5s | Maximum coverage, light deep search |
deep-reasoning |
5-15s | Complex research questions |
Instructions
Step 1: Match Search Type to Latency Budget
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
function selectSearchType(latencyBudgetMs: number) {
if (latencyBudgetMs < 200) return "instant";
if (latencyBudgetMs < 500) return "fast";
if (latencyBudgetMs < 1500) return "auto";
if (latencyBudgetMs < 3000) return "neural";
return "deep";
}
async function optimizedSearch(query: string, latencyBudgetMs: number) {
const type = selectSearchType(latencyBudgetMs);
const numResults = latencyBudgetMs < 500 ? 3 : latencyBudgetMs < 2000 ? 5 : 10;
return exa.search(query, { type, numResults });
}
Step 2: Minimize Content Retrieval
// Each content option adds latency. Only request what you need.
// Fastest: metadata only (no content retrieval)
const metadataOnly = await exa.search("query", { numResults: 5 });
// Medium: highlights only (much smaller than full text)
const highlightsOnly = await exa.searchAndContents("query", {
numResults: 5,
highlights: { maxCharacters: 300 },
// No text or summary — saves conteImplement content policy enforcement, domain filtering, and usage guardrails for Exa.
Exa Policy Guardrails
Output
- A versioned policy-control configuration with owner, scope, enforcement/evaluation evidence, exception path, and rollback decision.
Examples
Test a guardrail using a sanitized query that should be allowed and one that should be blocked, verify the redacted decision/audit record, and review any exception through the designated owner. Do not encode private data or weaken guardrails solely to obtain a desired retrieval result.
Overview
Policy enforcement for Exa neural search integrations. Exa searches the open web, so results may include unreliable sources, competitor content, or inappropriate material. This skill covers domain allowlists/blocklists (via Exa's includeDomains/excludeDomains), content moderation, query sanitization, freshness policies, and per-user budget enforcement.
Prerequisites
exa-jsinstalled and configured- Content policy requirements defined
- Redis for per-user quota tracking (optional)
Instructions
Step 1: Domain Filtering (Built-in Exa Feature)
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Exa supports up to 1200 domains in includeDomains/excludeDomains
const TRUSTED_SOURCES = {
medical: [
"pubmed.ncbi.nlm.nih.gov", "who.int", "cdc.gov",
"nejm.org", "nature.com", "thelancet.com",
],
technical: [
"github.com", "stackoverflow.com", "developer.mozilla.org",
"docs.python.org", "nodejs.org", "arxiv.org",
],
news: [
"reuters.com", "apnews.com", "bbc.com",
"techcrunch.com", "arstechnica.com",
],
};
const BLOCKED_DOMAINS = [
"competitor1.com", "competitor2.io",
"spam-farm.com", "content-mill.net",
];
async function policySearch(
query: string,
category: keyof typeof TRUSTED_SOURCES | "general"
) {
const opts: any = {
type: "auto",
numResults: 10,
text: { maxCharacters: 1000 },
moderation: true, // Exa's built-in content moderation
};
if (category !== "general" && TRUSTED_SOURCES[category]) {
opts.includeDomains = TRUSTED_SOURCES[category];
} else {
opts.excludeDomains = BLOCKED_DOMAINS;
}
return exa.searchAndContents(query, opts);
}
Step 2: Query Content Policy
const BLOCKED_PATTERNS = [
/how to (hack|exploit|attack|ddos)/i,
/(buy|purchase|order)\s+(drugs|weapons|firearms)/i,
/personal.*(address|phone|ssn|social security)/i,
/generate.*(malware|ransomware|virus)/i,
];
function validateQuery(input: string): string {
for (const pattern of BLOCKED_PATTERNS) {
Execute Exa production deployment checklist with pre-flight, deploy, and rollback.
Exa Production Checklist
Prerequisites
- A named service/policy/data owner, approved model/provider route, production rollback plan, and passing staging evidence.
Instructions
- Complete evidence gates for identity/secrets, data handling, policy controls, source/citation requirements, observability, rate limits, and rollback.
- Validate an approved non-sensitive canary and verify its expected routing/guardrail behavior.
- Block release when any security, policy, data, ownership, or recovery gate is unverified.
Output
- A production-readiness receipt with evidence, owners, exceptions, canary result, and rollback path.
Examples
Release an approved staging configuration to a small canary using sanitized queries, verify policy/source/citation and alert behavior, then observe the defined window. Restore the previous configuration if any guardrail or SLO fails; do not widen automation to conceal a failure.
Overview
Complete checklist for deploying Exa search integrations to production. Covers API key management, error handling verification, performance baselines, monitoring, and rollback procedures.
Pre-Deployment Checklist
Security
- [ ] Production API key stored in secret manager (not env file)
- [ ] Different API keys for dev/staging/production
- [ ]
.envfiles in.gitignore - [ ] Git history scanned for accidentally committed keys
- [ ] API key has minimal scopes needed
Code Quality
- [ ] All tests passing (unit + integration)
- [ ] No hardcoded API keys or URLs
- [ ] Error handling covers all Exa HTTP codes (400, 401, 402, 403, 429, 5xx)
- [ ]
requestIdcaptured from error responses - [ ] Rate limiting/exponential backoff implemented
- [ ] Content moderation enabled (
moderation: true) for user-facing search
Performance
- [ ] Search type appropriate for latency SLO (
fast/auto/neural) - [ ]
numResultsminimized per use case (3-5 for most) - [ ]
maxCharactersset on text and highlights - [ ] Result caching enabled (LRU or Redis)
- [ ] Request queue with concurrency limit (respect 10 QPS default)
Monitoring
- [ ] Search latency histogram instrumented
- [ ] Error rate counter by status code
- [ ] Cache hit/miss rate tracked
- [ ] Daily search volume tracked (for budget)
- [ ] Alerts configured for latency > 3s, error rate > 5%
Deploy Procedure
Step 1: Pre-Flight Verification
set -euo pipefail
echo "=== Exa Pre-Flight ==="
# 1. Verify production API key works
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_codImplement Exa rate limiting, exponential backoff, and request queuing.
Exa Rate Limits
Output
- A rate-aware client/workflow with bounded concurrency, idempotency, backoff, monitoring, and safe recovery decisions.
- An aggregate throttle receipt that excludes raw queries, result content, and credentials.
Overview
Handle Exa API rate limits gracefully. Default limit is 10 QPS (queries per second) across all endpoints. Rate limit errors return HTTP 429 with a simple { "error": "rate limit exceeded" } response. For higher limits, contact hello@exa.ai for Enterprise plans.
Rate Limit Structure
| Endpoint | Default QPS | Notes |
|---|---|---|
/search |
10 | Most endpoints share this limit |
/find-similar |
10 | Same pool as search |
/contents |
10 | Same pool |
/answer |
10 | Same pool |
| Research API | Concurrent task limit | Long-running operations |
Prerequisites
exa-jsSDK installed- Understanding of async/await patterns
Instructions
Step 1: Exponential Backoff with Jitter
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
async function withBackoff<T>(
operation: () => Promise<T>,
config = { maxRetries: 5, baseDelayMs: 1000, maxDelayMs: 32000 }
): Promise<T> {
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (err: any) {
const status = err.status || err.response?.status;
// Only retry on 429 (rate limit) and 5xx (server errors)
if (status !== 429 && (status < 500 || status >= 600)) throw err;
if (attempt === config.maxRetries) throw err;
// Exponential delay with random jitter to prevent thundering herd
const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);
const jitter = Math.random() * 500;
const delay = Math.min(exponentialDelay + jitter, config.maxDelayMs);
console.log(`[Exa] ${status} — retry ${attempt + 1}/${config.maxRetries} in ${delay.toFixed(0)}ms`);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error("Unreachable");
}
// Usage
const results = await withBackoff(() =>
exa.searchAndContents("AI research", { numResults: 5, text: true })
);
Step 2: Request Queue with Concurrency Control
import PQueue from "p-queue";
// Limit to 8 concurrent requests (under the 10 QPS limit)
const exaQueue = new PQueue({
concurrency: 8,
interval: 1000, // per second
intervalCap: 10, // max 10 per interval (matchesImplement Exa reference architecture for search pipelines, RAG, and content discovery.
Exa Reference Architecture
Prerequisites
- An approved search/research data flow, policy/data classification, environment boundaries, and owner for each integration point.
- Reviewed interfaces for credentials, retrieval controls, result handling, observability, automation, and incident response.
Output
- A documented architecture with trust boundaries, ownership, source/citation controls, redacted telemetry, and reversible integration points.
Examples
Model a development client that receives sanitized queries, applies approved source/date constraints, records only aggregate/correlation metadata, and returns results for human review. Promote the versioned contract through staging before production automation; keep policy guardrails and fallback behavior explicit rather than treating retrieval output as authoritative.
Overview
Production architecture for Exa neural search integration. Covers search service design, content extraction pipeline, RAG integration, domain-scoped search profiles, and caching strategy.
Architecture Diagram
┌──────────────────────────────────────────────────────────┐
│ Application Layer │
│ RAG Pipeline | Research Agent | Content Discovery │
└──────────┬──────────────┬───────────────┬────────────────┘
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────┐
│ Exa Search Service Layer │
│ ┌────────────┐ ┌────────────┐ ┌──────────────────┐ │
│ │ search() │ │ findSimilar│ │ getContents() │ │
│ │ neural/ │ │ (URL seed) │ │ (known URLs) │ │
│ │ keyword/ │ └────────────┘ └──────────────────┘ │
│ │ auto/fast │ │
│ └────────────┘ ┌──────────────────┐ │
│ │ answer() / │ │
│ Content Options: │ streamAnswer() │ │
│ text | highlights | summary └──────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────────┐ │
│ │ Result Cache (LRU + Redis) │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────┐
│ api.exa.ai — Exa Neural Search API │
│ Auth: x-api-key header | Rate: 10 QPS default │
└──────────────────────────────────────────────────────────┘
Instructions
Step 1: Search Service Layer
// src/exa/service.ts
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
interface SearchRequest {
query:Implement Exa reliability patterns: query fallback chains, circuit breakers, and graceful degradation.
Exa Reliability Patterns
Prerequisites
- An SLO, owner, sanitized test inputs, rate/timeout policy, and a safe fallback/rollback path.
- Idempotent work tracking and redacted observability for request state and outcome.
Output
- A resilient retrieval integration with bounded retry, timeout, circuit-breaker/fallback, and incident evidence controls.
Examples
Use a sanitized query fixture to exercise timeout and transient error handling, verify exponential backoff and fallback behavior, then record aggregate completion/latency/error results. Do not retry unboundedly or turn a failed retrieval into an unreviewed automated decision.
Overview
Production reliability patterns for Exa neural search. Exa-specific failure modes include: empty result sets (query too narrow), content retrieval failures (sites block crawling), variable latency by search type, and 429 rate limits at 10 QPS default.
Instructions
Step 1: Query Fallback Chain
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// If neural search returns too few results, fall back through search types
async function resilientSearch(
query: string,
minResults = 3,
opts: any = {}
) {
// Try 1: Neural search (best quality)
let results = await exa.searchAndContents(query, {
type: "neural",
numResults: 10,
...opts,
});
if (results.results.length >= minResults) return results;
// Try 2: Auto search (Exa picks best approach)
results = await exa.searchAndContents(query, {
type: "auto",
numResults: 10,
...opts,
});
if (results.results.length >= minResults) return results;
// Try 3: Keyword search (different index)
results = await exa.searchAndContents(query, {
type: "keyword",
numResults: 10,
...opts,
});
if (results.results.length >= minResults) return results;
// Try 4: Remove filters and broaden
const broadOpts = { ...opts };
delete broadOpts.startPublishedDate;
delete broadOpts.endPublishedDate;
delete broadOpts.includeDomains;
delete broadOpts.includeText;
return exa.searchAndContents(query, {
type: "auto",
numResults: 10,
...broadOpts,
});
}
Step 2: Retry with Exponential Backoff
async function searchWithRetry(
query: string,
opts: any,
maxRetries = 3
) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await exa.searchAndContents(query, opts);
} catch (err: any) {
const status = err.status || 0;
// Only retry on rate limits (429) and server errors (5xx)
if (status !== 429 && (status < 500 || status >= 600)) throw err;
if (attempt === maxRetries) throw err;
const delay = 1000 * Math.pow(2, attempt) + Math.random() * 500;
Apply production-ready exa-js SDK patterns with type safety, singletons, and wrappers.
Exa SDK Patterns
Output
- A reusable Exa client boundary with scoped configuration, sanitized inputs, policy controls, redacted telemetry, and safe error classification.
- Unit/integration evidence that avoids real sensitive queries, result content, and credentials.
Overview
Production-ready patterns for the exa-js SDK. Covers client singletons, typed wrappers, error handling, retry logic, and response validation for real Exa API methods.
Prerequisites
exa-jsinstalled andEXA_API_KEYconfigured- TypeScript project with strict mode
- Familiarity with async/await and error handling
Instructions
Step 1: Client Singleton
// src/exa/client.ts
import Exa from "exa-js";
let instance: Exa | null = null;
export function getExa(): Exa {
if (!instance) {
const apiKey = process.env.EXA_API_KEY;
if (!apiKey) {
throw new Error("EXA_API_KEY not set. Get one at https://dashboard.exa.ai");
}
instance = new Exa(apiKey);
}
return instance;
}
Step 2: Typed Search Wrapper
// src/exa/search.ts
import Exa from "exa-js";
import { getExa } from "./client";
interface ExaSearchOptions {
type?: "auto" | "neural" | "keyword" | "fast" | "instant" | "deep" | "deep-reasoning";
numResults?: number;
includeDomains?: string[];
excludeDomains?: string[];
startPublishedDate?: string;
endPublishedDate?: string;
category?: "company" | "research paper" | "news" | "tweet" | "personal site" | "financial report" | "people";
includeText?: string[];
excludeText?: string[];
}
interface ExaContentsOptions {
text?: boolean | { maxCharacters?: number; includeHtmlTags?: boolean };
highlights?: boolean | { maxCharacters?: number; query?: string };
summary?: boolean | { query?: string };
livecrawl?: "always" | "preferred" | "fallback" | "never";
livecrawlTimeout?: number;
subpages?: number;
subpageTarget?: string | string[];
}
export async function exaSearch(query: string, opts: ExaSearchOptions = {}) {
const exa = getExa();
return exa.search(query, {
type: opts.type ?? "auto",
numResults: opts.numResults ?? 10,
...opts,
});
}
export async function exaSearchWithContents(
query: string,
searchOpts: ExaSearchOptions = {},
contentOpts: ExaContentsOptions = {}
) {
const exa = getExa();
return exa.searchAndContents(query, {
type: searchOpts.type ?? "auto",
numResults: searchOpts.numResults ?? 10,
...searchOpts,
...contentOpts,
});
}
Step 3: Error Handling Wrapper
exa-security-basics
View full skill →
Secure Exa API keys, implement content moderation, and manage domain restrictions.
ReadWriteGrep
Exa Security Basics
Output
- A least-privilege Exa integration with scoped credentials, approved data boundaries, policy enforcement, and incident/revocation ownership.
- A tested security boundary for secrets, private queries/results, automation scope, and redacted logging.
Overview
Security best practices for Exa API integrations. Exa authenticates via the x-api-key header. Key security concerns include API key protection, content moderation for search results, domain filtering to prevent exposure to malicious sources, and query sanitization.
Prerequisites
- Exa API key from dashboard.exa.ai
- Understanding of environment variable management
.gitignore configured for secrets
Instructions
Step 1: API Key Management
# .env (NEVER commit to git)
EXA_API_KEY=your-api-key-here
# .gitignore — add these entries
.env
.env.local
.env.*.local
// Validate API key exists before creating client
import Exa from "exa-js";
function createSecureClient(): Exa {
const apiKey = process.env.EXA_API_KEY;
if (!apiKey) {
throw new Error("EXA_API_KEY not configured");
}
if (apiKey.startsWith("sk_") && apiKey.length < 20) {
throw new Error("EXA_API_KEY appears malformed");
}
return new Exa(apiKey);
}
Step 2: Enable Content Moderation
const exa = new Exa(process.env.EXA_API_KEY);
// Exa supports content moderation to filter unsafe results
const results = await exa.searchAndContents(
"user-provided search query",
{
numResults: 10,
text: true,
moderation: true, // filter unsafe content from results
}
);
Step 3: Domain Filtering for Safety
// Restrict results to trusted domains for sensitive use cases
const TRUSTED_DOMAINS = [
"docs.python.org", "developer.mozilla.org", "nodejs.org",
"github.com", "stackoverflow.com", "arxiv.org",
];
const BLOCKED_DOMAINS = [
"known-malware-site.com", "phishing-domain.net",
];
async function safeDomainSearch(query: string) {
return exa.searchAndContents(query, {
numResults: 10,
includeDomains: TRUSTED_DOMAINS, // only return results from these
text: { maxCharacters: 1000 },
});
}
async function searchWithBlocklist(query: string) {
return exa.searchAndContents(query, {
numResults: 10,
excludeDomains: BLOCKED_DOMAINS, // never return results from these
text: { maxCharacters: 1000 },
});
}
Step 4: Query Sanitization
// Sanitize user-provided queries before sending to Exa
function sanitizeQuery(input: string): string {
// Remove p
Upgrade exa-js SDK versions and handle breaking changes safely.
Exa Upgrade & Migration
Prerequisites
- Current/target versions, compatibility notes, sanitized evaluation set, acceptance thresholds, and a rollback owner.
- Separate staging credentials plus a policy/data review for any query/result migration or automation change.
Output
- A staged upgrade record with compatibility/evaluation evidence, owner, observation window, and rollback revision.
- A safe pause decision when retrieval quality, latency, policy, or data handling regresses.
Examples
Upgrade in staging, run unit tests and sanitized evaluation queries through prior and target configurations, compare aggregate relevance/latency/error metrics, then release an approved canary. Roll back on regression and do not bulk-replay customer queries or export private result data to validate the migration.
Current State
!npm list exa-js 2>/dev/null | grep exa-js || echo 'exa-js not installed' !npm view exa-js version 2>/dev/null || echo 'cannot check latest'
Overview
Guide for upgrading the exa-js SDK. The SDK import is import Exa from "exa-js" and the client is instantiated with new Exa(apiKey). This skill covers checking for updates, handling breaking changes, and validating after upgrade.
Instructions
Step 1: Check Current vs Latest Version
set -euo pipefail
echo "Current version:"
npm list exa-js 2>/dev/null || echo "Not installed"
echo ""
echo "Latest available:"
npm view exa-js version
echo ""
echo "Changelog:"
npm view exa-js repository.url
Step 2: Create Upgrade Branch
set -euo pipefail
git checkout -b upgrade/exa-js-latest
npm install exa-js@latest
npm test
Step 3: Verify API Compatibility
import Exa from "exa-js";
async function verifyUpgrade() {
const exa = new Exa(process.env.EXA_API_KEY);
const checks = [];
// Check 1: Basic search
try {
const r = await exa.search("upgrade test", { numResults: 1 });
checks.push({ method: "search", status: "OK", results: r.results.length });
} catch (err: any) {
checks.push({ method: "search", status: "FAIL", error: err.message });
}
// Check 2: searchAndContents
try {
const r = await exa.searchAndContents("upgrade test", {
numResults: 1,
text: { maxCharacters: 100 },
highlights: { maxCharacters: 100 },
});
checks.push({
method: "searchAndContents",
status: "OK",
hasText: !!r.results[0]?.text,
hasHighlights: !!r.results[0]?.highlights,
});
} catch (err: any) {
checks.push({ method: "searBuild event-driven integrations with Exa using scheduled monitors and content alerts.
Exa Webhooks & Events
Output
- A verified signed/idempotent event path with redacted observability, bounded retry, and recovery ownership.
- A receipt with correlation ID, environment, type, state/result, and safe replay decision.
Overview
Build event-driven integrations around Exa neural search. Exa is a synchronous search API (no native webhooks), so this skill covers building async patterns: scheduled content monitoring with searchAndContents, similarity alerts with findSimilarAndContents, new content detection using date filters, and webhook-style notification delivery.
Prerequisites
exa-jsinstalled andEXA_API_KEYconfigured- Queue system (BullMQ/Redis) or cron scheduler
- Webhook endpoint for notifications
Event Patterns
| Pattern | Mechanism | Use Case |
|---|---|---|
| Content monitor | Scheduled searchAndContents with startPublishedDate |
New article alerts |
| Similarity alert | Periodic findSimilarAndContents + diff |
Competitive monitoring |
| Content change | Re-search + compare result sets | Update tracking |
| Research digest | Scheduled answer + email/Slack |
Daily briefings |
Instructions
Step 1: Content Monitor Service
import Exa from "exa-js";
import { Queue, Worker } from "bullmq";
const exa = new Exa(process.env.EXA_API_KEY!);
interface SearchMonitor {
id: string;
query: string;
webhookUrl: string;
lastResultUrls: Set<string>;
intervalMinutes: number;
searchType: "auto" | "neural" | "keyword";
}
const monitorQueue = new Queue("exa-monitors", {
connection: { host: "localhost", port: 6379 },
});
async function createMonitor(config: Omit<SearchMonitor, "lastResultUrls">) {
await monitorQueue.add("check-search", config, {
repeat: { every: config.intervalMinutes * 60 * 1000 },
jobId: config.id,
});
console.log(`Monitor created: ${config.id} (every ${config.intervalMinutes} min)`);
}
Step 2: Execute Monitored Searches
const worker = new Worker("exa-monitors", async (job) => {
const monitor = job.data;
// Search for new content published since last check
const results = await exa.searchAndContents(monitor.query, {
type: monitor.searchType || "auto",
numResults: 10,
text: { maxCharacters: 500 },
highlights: { maxCharacters: 300, query: monitor.query },
// Only find content published in the monitoring window
startPublishedDate: getLastCheckDate(mHow It Works
import Exa from "exa-js";
const exa = new Exa(process.env.EXA_API_KEY);
// Search with content extraction
const results = await exa.searchAndContents(
"best practices for building RAG pipelines",
{
type: "neural",
numResults: 5,
text: { maxCharacters: 2000 },
highlights: { maxCharacters: 500 },
summary: { query: "key takeaways" },
}
);
Ready to use exa-pack?
Related Plugins
supabase-pack
Complete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack.
/plugin install supabase-pack@claude-code-plugins-plus
vercel-pack
Complete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack.
/plugin install vercel-pack@claude-code-plugins-plus
clay-pack
Complete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack.
/plugin install clay-pack@claude-code-plugins-plus
cursor-pack
Complete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack.
/plugin install cursor-pack@claude-code-plugins-plus
firecrawl-pack
Complete Firecrawl integration skill pack with 30 skills covering web scraping, crawling, markdown conversion, and LLM-ready data extraction. Flagship+ tier vendor pack.
/plugin install firecrawl-pack@claude-code-plugins-plus
klingai-pack
Complete Kling AI integration skill pack with 30 skills covering AI video generation, text-to-video, image-to-video, and creative workflows. Flagship+ tier vendor pack.
/plugin install klingai-pack@claude-code-plugins-plus