Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 55 additions & 16 deletions .claude/agents/PerplexityResearcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,63 @@ You are a meticulous, thorough researcher who believes in evidence-based answers

## Research Methodology

### Primary Tool Usage
**Use the research skill for comprehensive research tasks.**
### Primary Tool: Perplexity Command-Line Interface

To load the research skill:
**USE THE PERPLEXITY CLI FOR ALL RESEARCH**

The Perplexity CLI is your primary research tool:

```bash
perplexity "Your research query here"
```
Skill("research")

**Models Available:**
- `sonar` - Fast web search (default)
- `sonar-pro` - Deeper analysis, more comprehensive

**Example Usage:**
```bash
# Basic query
perplexity "What are the latest developments in AI agents 2025?"

# Deep research with sonar-pro
perplexity --model sonar-pro "Compare different approaches to building AI agent systems"
```

The research skill provides:
- Multi-source parallel research with multiple researcher agents
- Content extraction and analysis workflows
- YouTube extraction via Fabric CLI
- Web scraping with multi-layer fallback (WebFetch → BrightData → Apify)
- Perplexity API integration for deep search (requires PERPLEXITY_API_KEY)

For simple queries, you can use tools directly:
1. Use WebSearch for current information and news
2. Use WebFetch to retrieve and analyze specific URLs
3. Use multiple queries to triangulate information
4. Verify facts across multiple sources
### Research Orchestration Process

When given a research query, you MUST:

1. **Query Decomposition (3-7 variations)**
- Analyze the main research question
- Break it into complementary sub-queries
- Each variation should explore a different angle

2. **Execute Research**
- Run `perplexity "query"` for each sub-query
- Use `--model sonar-pro` for complex/deep research
- Collect findings from each query

3. **Result Synthesis**
- Identify patterns, contradictions, and consensus
- Synthesize into comprehensive final answer
- Note conflicting findings with source attribution

### Query Decomposition Example

**Original Query:** "Best practices for building AI agents in 2025"

**Decomposed Queries:**
1. `perplexity "AI agent architecture patterns 2025 best practices"`
2. `perplexity "AI agent memory and context management approaches"`
3. `perplexity "AI agent tool use and function calling patterns"`
4. `perplexity "AI agent safety and guardrails implementation"`
5. `perplexity "Production AI agent deployment challenges solutions"`

### Fallback Tools

If Perplexity CLI is unavailable, use these alternatives:
1. WebSearch for current information and news
2. WebFetch to retrieve and analyze specific URLs
3. Multiple queries to triangulate information

192 changes: 192 additions & 0 deletions .claude/tools/perplexity
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
#!/usr/bin/env bun

/**
* Perplexity AI CLI - Simple wrapper for Perplexity API
*
* Usage:
* perplexity "your research query"
* perplexity --model sonar-pro "deep research query"
* perplexity --help
*
* Models:
* sonar - Fast web search (default)
* sonar-pro - Deeper analysis, more comprehensive
*/

import { homedir } from 'os';
import { join } from 'path';
import { existsSync, readFileSync } from 'fs';

// Load .env from ~/.claude directory
function loadEnv(): void {
const envPath = join(homedir(), '.claude', '.env');
if (existsSync(envPath)) {
const envContent = readFileSync(envPath, 'utf-8');
envContent.split('\n').forEach(line => {
const trimmedLine = line.trim();
if (trimmedLine && !trimmedLine.startsWith('#')) {
const eqIndex = trimmedLine.indexOf('=');
if (eqIndex > 0) {
const key = trimmedLine.substring(0, eqIndex).trim();
const value = trimmedLine.substring(eqIndex + 1).trim().replace(/^["']|["']$/g, '');
if (key && value) {
process.env[key] = value;
}
}
}
});
}
}

// Parse command line arguments
function parseArgs(): { query: string; model: string; help: boolean } {
const args = process.argv.slice(2);
let model = 'sonar';
let help = false;
const queryParts: string[] = [];

for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--help' || arg === '-h') {
help = true;
} else if (arg === '--model' || arg === '-m') {
model = args[++i] || 'sonar';
} else if (arg.startsWith('--model=')) {
model = arg.split('=')[1];
} else {
queryParts.push(arg);
}
}

return { query: queryParts.join(' '), model, help };
}

// Show help
function showHelp(): void {
console.log(`
Perplexity AI CLI - Web research powered by Perplexity

USAGE:
perplexity "your research query"
perplexity --model sonar-pro "deep research query"

OPTIONS:
-m, --model <model> AI model to use (default: sonar)
-h, --help Show this help message

MODELS:
sonar Fast web search, good for quick queries
sonar-pro Deeper analysis, more comprehensive results

EXAMPLES:
perplexity "What is the latest on AI agents?"
perplexity --model sonar-pro "Compare React vs Vue for enterprise apps in 2025"
perplexity "Best practices for TypeScript in 2025"

CONFIGURATION:
API key is loaded from ~/.claude/.env
Set PERPLEXITY_API_KEY=your_key_here
`);
}

// Call Perplexity API
async function search(query: string, model: string): Promise<void> {
const apiKey = process.env.PERPLEXITY_API_KEY;

if (!apiKey) {
console.error('Error: PERPLEXITY_API_KEY not found');
console.error('Add to ~/.claude/.env: PERPLEXITY_API_KEY=your_key_here');
console.error('Get your key from: https://www.perplexity.ai/settings/api');
process.exit(1);
}

try {
const response = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
messages: [{
role: 'system',
content: 'You are a helpful research assistant. Provide comprehensive, well-sourced answers. Include relevant details and cite your sources when possible.'
}, {
role: 'user',
content: query
}],
return_citations: true
})
});

if (!response.ok) {
const errorText = await response.text();
console.error(`API Error: ${response.status} - ${errorText}`);
process.exit(1);
}

const data = await response.json() as {
model: string;
choices: Array<{ message: { content: string } }>;
citations?: string[];
usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };
};

// Output the response
console.log('\n' + '='.repeat(60));
console.log(`PERPLEXITY RESEARCH (${model})`);
console.log('='.repeat(60) + '\n');

console.log('QUERY:', query);
console.log('\n' + '-'.repeat(60) + '\n');

// Main content
const content = data.choices[0]?.message?.content || 'No response';
console.log('FINDINGS:\n');
console.log(content);

// Citations
if (data.citations && data.citations.length > 0) {
console.log('\n' + '-'.repeat(60));
console.log('\nSOURCES:');
data.citations.forEach((citation, i) => {
console.log(` [${i + 1}] ${citation}`);
});
}

// Usage stats
if (data.usage) {
console.log('\n' + '-'.repeat(60));
console.log(`Tokens: ${data.usage.prompt_tokens} in / ${data.usage.completion_tokens} out / ${data.usage.total_tokens} total`);
}

console.log('\n' + '='.repeat(60) + '\n');

} catch (error) {
console.error('Error calling Perplexity API:', error);
process.exit(1);
}
}

// Main
async function main(): Promise<void> {
loadEnv();
const { query, model, help } = parseArgs();

if (help) {
showHelp();
process.exit(0);
}

if (!query) {
console.error('Error: No query provided');
console.error('Usage: perplexity "your research query"');
console.error('Run perplexity --help for more options');
process.exit(1);
}

await search(query, model);
}

main();