Add Perplexity's Sonar API to your project for real-time web search-grounded AI responses using Vercel AI SDK. Supports multiple tiers (Sonar Pro, Sonar) with enhanced citation capabilities.
Integrate Perplexity's Sonar API into your application using the Vercel AI SDK. Perplexity provides a powerful answer engine with real-time web search capabilities, perfect for building applications that need current, factual information grounded in web sources.
This skill helps you add Perplexity's AI capabilities to your project, including:
Install the Perplexity provider and AI SDK core:
```bash
npm install @ai-sdk/perplexity ai
```
Create or update your `.env.local` file with your Perplexity API key:
```env
PERPLEXITY_API_KEY=your_api_key_here
```
**Important**: Add `.env.local` to your `.gitignore` to prevent committing secrets.
Create a new file (e.g., `src/lib/perplexity.ts`) to set up the provider:
```typescript
import { perplexity } from '@ai-sdk/perplexity';
import { generateText } from 'ai';
export async function queryPerplexity(prompt: string) {
const { text } = await generateText({
model: perplexity('sonar-pro'), // or 'sonar' for faster/cheaper option
prompt,
});
return text;
}
```
Example usage in a Next.js API route (`src/app/api/search/route.ts`):
```typescript
import { perplexity } from '@ai-sdk/perplexity';
import { streamText } from 'ai';
export const runtime = 'edge';
export async function POST(req: Request) {
const { prompt } = await req.json();
const result = streamText({
model: perplexity('sonar-pro'),
prompt,
});
return result.toDataStreamResponse();
}
```
Example client-side usage with streaming:
```typescript
'use client';
import { useChat } from 'ai/react';
export default function SearchPage() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: '/api/search',
});
return (
<div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Ask a question..."
/>
<button type="submit">Search</button>
</form>
{messages.map(m => (
<div key={m.id}>
<strong>{m.role}:</strong> {m.content}
</div>
))}
</div>
);
}
```
Select based on your use case:
```typescript
// For complex research queries
const research = await generateText({
model: perplexity('sonar-pro'),
prompt: 'Explain recent breakthroughs in fusion energy',
});
// For quick factual lookups
const quick = await generateText({
model: perplexity('sonar'),
prompt: 'What is the capital of France?',
});
```
For better UX, stream responses as they're generated:
```typescript
import { streamText } from 'ai';
const result = streamText({
model: perplexity('sonar-pro'),
prompt: 'Latest AI developments',
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
```
Provide additional context to guide responses:
```typescript
const { text } = await generateText({
model: perplexity('sonar-pro'),
system: 'You are a helpful assistant specializing in technology news.',
prompt: 'What happened in tech this week?',
});
```
Create a simple test script to verify integration:
```typescript
import { perplexity } from '@ai-sdk/perplexity';
import { generateText } from 'ai';
async function test() {
try {
const { text } = await generateText({
model: perplexity('sonar'),
prompt: 'What is 2+2?',
});
console.log('Success:', text);
} catch (error) {
console.error('Error:', error);
}
}
test();
```
1. **Research Assistant**: Build a chatbot that answers questions with real-time web data
2. **News Aggregator**: Create summaries of current events with automatic source citations
3. **Fact Checker**: Verify claims against current web information
4. **Market Intelligence**: Query real-time business and market data
5. **Technical Documentation Helper**: Get up-to-date answers about rapidly changing tech topics
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/perplexity-ai-sdk-integration/raw