Skip to main content

Perplexity Search

Overview

The Perplexity Search integration is the primary web search solution for the Mastra platform, particularly in the Reasoning Engine. Unlike traditional search APIs that return raw results, Perplexity searches the web, analyzes multiple sources, and returns a coherent synthesized answer with citations.

Key Features:

  • ✅ Single API call for search + synthesis
  • ✅ Automatic source citation and reference tracking (with URL extraction fallback)
  • ✅ Multiple search modes (general, academic, news, youtube, reddit)
  • ✅ Intelligent model selection (sonar for speed, sonar-pro for depth)
  • ✅ Structured output with detailed citations
  • ✅ Real-time web access
  • ✅ Default system prompt optimized for inline citations

Configuration

Set your Perplexity API key:

PERPLEXITY_API_KEY=your_api_key_here

Get your API key at: https://www.perplexity.ai/settings/api

Optional configuration:

PERPLEXITY_DEFAULT_MODEL=sonar          # or sonar-pro
PERPLEXITY_TIMEOUT_MS=60000 # Request timeout
PERPLEXITY_DEBUG_TIMINGS=true # Enable debug logging
PERPLEXITY_DEBUG_CITATIONS=true # Debug citation extraction
note

Citation Extraction: Perplexity API sometimes returns an empty citations array even when the answer contains inline URLs. The provider automatically falls back to regex-based URL extraction from the answer text to ensure citations are captured.

Models

  • Fast, general-purpose search
  • Good for most queries
  • Lower cost

sonar-pro

  • More thorough research
  • Higher quality synthesis
  • Better for complex topics

Search Modes

ModeDescriptionUse Case
internetGeneral web search (default)Most queries
academicScholarly sources, research papersAcademic research
newsRecent news and current eventsCurrent events
youtubeVideo contentTutorials, demos
redditCommunity discussionsUser opinions

Usage

import { perplexitySearchTool } from '../tools/base/perplexity-search.tool.ts';

const result = await perplexitySearchTool.execute({
query: "What are the latest findings on sleep and stress correlation?",
model: "sonar"
});

if (result.success) {
console.log(result.answer); // Synthesized answer
console.log(result.citations); // Source URLs
}

Academic Research

const result = await perplexitySearchTool.execute({
query: "research on personal well-being assessment methods",
model: "sonar-pro",
searchMode: "academic",
maxTokens: 2048
});

Custom System Prompt

const result = await perplexitySearchTool.execute({
query: "stress management techniques",
systemPrompt: "You are a clinical psychologist. Provide evidence-based recommendations with recent peer-reviewed sources.",
searchMode: "academic"
});

Provider-Level API

import { perplexitySearch, academicSearch } from '../providers/perplexity-search.ts';

// Convenience function for academic search
const result = await academicSearch(
"latest research on cognitive behavioral therapy"
);

console.log(result.answer);
console.log(result.citations);

Response Format

{
success: true,
answer: "Recent research indicates...",
citations: [
"https://pubmed.ncbi.nlm.nih.gov/12345678",
"https://www.nature.com/articles/..."
],
detailedCitations: [
{ number: 1, url: "https://...", title: "Study Title" }
],
model: "sonar-pro",
responseTime: 2450,
usage: {
promptTokens: 125,
completionTokens: 487,
totalTokens: 612
}
}

Comparison: Perplexity vs Tavily

Perplexity (Primary - Current)

// Single call with synthesis
const result = await perplexitySearchTool.execute({
query: "latest research on well-being assessment",
model: "sonar-pro",
searchMode: "academic"
});
// Done - answer + citations ready

Pros:

  • ✅ Simple one-call solution
  • ✅ Fast execution (~2-3s)
  • ✅ Built-in synthesis
  • ✅ Automatic citations with fallback extraction
  • ✅ Multiple search modes (academic, news, reddit, etc.)
  • ✅ Lower complexity for reasoning engine

Cons:

  • ❌ Less granular control over individual sources
  • ❌ Citations may require fallback extraction

Tavily (Legacy/Alternative)

// Traditional search API
const searchResults = await tavilySearch({
query: "well-being assessment methods",
searchDepth: 'basic',
maxResults: 5,
includeAnswer: true
});
// Returns raw search results + optional AI summary

Pros:

  • ✅ Structured search results with scores
  • ✅ Domain filtering capabilities
  • ✅ Topic-based search (general/news/finance)
  • ✅ Predictable result format

Cons:

  • ❌ No built-in synthesis (just optional summary)
  • ❌ Requires additional processing for knowledge extraction
  • ❌ More complex integration for reasoning workflows

When to Use Tavily:

  • When you need explicit control over result ranking
  • When domain filtering is critical
  • For diagnostic/testing tools (e.g., admin-test-tavily-search)

Use Cases

Reasoning Engine Domain Retrieval (Primary)

Perplexity is the primary search solution for domain knowledge retrieval:

// Parallel query execution with diversity checking
const results = await Promise.all(
topQueries.slice(0, 2).map(q =>
perplexitySearchTool.execute({
query: q.query,
model: q.model || 'sonar',
searchMode: q.searchMode || 'internet'
})
)
);

Quick Research

Use Perplexity for fast, synthesized answers:

const result = await perplexitySearchTool.execute({
query: user.question,
model: "sonar"
});

Academic Research

Leverage academic search mode for peer-reviewed sources:

const result = await perplexitySearchTool.execute({
query: "cognitive behavioral therapy efficacy",
model: "sonar-pro",
searchMode: "academic"
});

Testing

Test the Perplexity integration:

# Set API key
export PERPLEXITY_API_KEY=your_key_here

# Smoke test (runs directly via tsx, no script file required)
npx tsx -e "import { perplexitySearchTool } from './src/mastra/tools/base/perplexity-search.tool.ts'; const result = await perplexitySearchTool.execute({ query: 'What is the capital of France?', model: 'sonar', maxTokens: 128 }); console.log(result);"

Best Practices

  1. Choose the right model:

    • Use sonar for general queries
    • Use sonar-pro for complex research
  2. Set appropriate search modes:

    • academic for peer-reviewed sources
    • news for current events
    • internet (default) for general queries
  3. Optimize token usage:

    • Set maxTokens based on answer length needs
    • Use lower temperature (0.1-0.2) for factual responses
  4. Handle citations:

    • Always include returnCitations: true
    • Verify citation relevance before using
  5. Error handling:

    • Check result.success before accessing answer
    • Implement retry logic for transient failures

Pricing

Perplexity API pricing (as of 2026):

  • Sonar: ~$5 per 1M tokens
  • Sonar Pro: ~$50 per 1M tokens

Compare with multi-step costs:

  • Tavily: $4 per 1000 searches
  • Mozilla Readability: Free (local processing)
  • Content analysis: OpenAI API costs