using-perplexity-platform
Perplexity Sonar API development with search-augmented generation, real-time web search, citations, and OpenAI-compatible Chat Completions. Use for AI-powered applications requiring up-to-date information, research assistants, and grounded responses with sources.
What this skill does
# Perplexity Sonar API Development Skill
## Quick Reference
Perplexity Sonar API development with Python and TypeScript/JavaScript clients. Covers Sonar model family for search-augmented generation, Chat Completions API (OpenAI-compatible), real-time web search, citations, and streaming.
---
## Table of Contents
1. [When to Use](#when-to-use)
2. [Sonar Model Family](#sonar-model-family)
3. [Quick Start](#quick-start)
4. [Chat Completions API](#chat-completions-api)
5. [Citations and Sources](#citations-and-sources)
6. [Search Configuration](#search-configuration)
7. [Streaming](#streaming)
8. [Error Handling](#error-handling)
9. [Best Practices](#best-practices)
10. [Anti-Patterns](#anti-patterns)
11. [Integration Checklist](#integration-checklist)
12. [When to Use Perplexity vs Others](#when-to-use-perplexity-vs-others)
13. [CLI Quick Test](#cli-quick-test)
14. [See Also](#see-also)
---
## When to Use
This skill is loaded by `backend-developer` when:
- `openai` package in `requirements.txt` or `pyproject.toml` with Perplexity base URL
- Environment variables `PERPLEXITY_API_KEY` or `PPLX_API_KEY` present
- User mentions "Perplexity", "Sonar", or "search-augmented" in task
- Code uses `api.perplexity.ai` base URL
**Minimum Detection Confidence**: 0.8 (80%)
---
## Sonar Model Family
### Available Models
| Model | Context | Search | Use Case | Speed |
|-------|---------|--------|----------|-------|
| `sonar` | 128K | Yes | General search-augmented | Fast |
| `sonar-pro` | 200K | Yes | Complex research, deeper search | Medium |
| `sonar-reasoning` | 128K | Yes | Multi-step reasoning with search | Slower |
| `sonar-reasoning-pro` | 200K | Yes | Advanced reasoning, citations | Slowest |
### Model Selection Guide
```
Task Complexity -> Model Selection
+-- Simple factual queries -> sonar (fast, affordable)
+-- Research with citations -> sonar-pro (deeper search)
+-- Multi-step reasoning -> sonar-reasoning
+-- Complex analysis -> sonar-reasoning-pro
```
### Pricing (per 1M tokens)
| Model | Input | Output |
|-------|-------|--------|
| sonar | $1.00 | $1.00 |
| sonar-pro | $3.00 | $15.00 |
| sonar-reasoning | $1.00 | $5.00 |
| sonar-reasoning-pro | $2.00 | $8.00 |
---
## Quick Start
### Python Setup (Using OpenAI SDK)
```python
from openai import OpenAI
client = OpenAI(
api_key="pplx-...", # or use PERPLEXITY_API_KEY env var
base_url="https://api.perplexity.ai"
)
response = client.chat.completions.create(
model="sonar",
messages=[
{"role": "system", "content": "Be precise and concise. Cite sources."},
{"role": "user", "content": "What are the latest developments in AI?"}
]
)
print(response.choices[0].message.content)
# Access citations if available
if hasattr(response, 'citations'):
for citation in response.citations:
print(f" - {citation}")
```
### TypeScript Setup
```typescript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.PERPLEXITY_API_KEY,
baseURL: 'https://api.perplexity.ai'
});
const response = await client.chat.completions.create({
model: 'sonar',
messages: [
{ role: 'system', content: 'Be precise and concise. Cite sources.' },
{ role: 'user', content: 'What are the latest developments in AI?' }
]
});
console.log(response.choices[0].message.content);
```
### Environment Configuration
```bash
export PERPLEXITY_API_KEY="pplx-..."
# Alternative: export PPLX_API_KEY="pplx-..."
```
---
## Chat Completions API
### Common Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `model` | string | Model ID (required) |
| `messages` | array | Conversation messages (required) |
| `temperature` | float (0-2) | Randomness (0=deterministic) |
| `max_tokens` | int | Max response tokens |
| `stream` | boolean | Enable streaming |
### Perplexity-Specific Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `search_domain_filter` | array | Limit search to specific domains |
| `return_images` | boolean | Include relevant images |
| `return_related_questions` | boolean | Suggest follow-up questions |
| `search_recency_filter` | string | Filter by recency (day, week, month, year) |
```python
# Advanced search configuration
response = client.chat.completions.create(
model="sonar-pro",
messages=[{"role": "user", "content": "Recent tech layoffs?"}],
extra_body={
"search_domain_filter": ["techcrunch.com", "theverge.com"],
"search_recency_filter": "week",
"return_related_questions": True
}
)
```
---
## Citations and Sources
Perplexity automatically includes citations. Extract and display them:
```python
def get_response_with_citations(client, query, model="sonar"):
"""Get response with structured citations."""
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": query}]
)
content = response.choices[0].message.content
citations = []
if hasattr(response, 'citations'):
citations = response.citations
return content, citations
# Usage
answer, sources = get_response_with_citations(client, "Who won the latest Super Bowl?")
print("Answer:", answer)
for source in sources:
print(f" - {source}")
```
---
## Search Configuration
### Domain Filtering
```python
response = client.chat.completions.create(
model="sonar-pro",
messages=[{"role": "user", "content": "Latest research on LLMs"}],
extra_body={
"search_domain_filter": ["arxiv.org", "openai.com", "anthropic.com"]
}
)
```
### Recency Filtering
```python
response = client.chat.completions.create(
model="sonar",
messages=[{"role": "user", "content": "Stock market news"}],
extra_body={
"search_recency_filter": "day" # day, week, month, year
}
)
```
### Academic Focus
```python
response = client.chat.completions.create(
model="sonar-pro",
messages=[{
"role": "system",
"content": "Focus on peer-reviewed academic sources."
}, {
"role": "user",
"content": "Research on sleep and memory consolidation?"
}],
extra_body={
"search_domain_filter": [
"pubmed.ncbi.nlm.nih.gov", "nature.com", "science.org"
]
}
)
```
---
## Streaming
### Synchronous Streaming
```python
stream = client.chat.completions.create(
model="sonar",
messages=[{"role": "user", "content": "Explain machine learning."}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
```
### Async Streaming
```python
import asyncio
from openai import AsyncOpenAI
async def stream_response(prompt: str):
client = AsyncOpenAI(
api_key="pplx-...",
base_url="https://api.perplexity.ai"
)
stream = await client.chat.completions.create(
model="sonar",
messages=[{"role": "user", "content": prompt}],
stream=True
)
async for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
asyncio.run(stream_response("What's happening in AI today?"))
```
---
## Error Handling
```python
from openai import (
OpenAI, RateLimitError, AuthenticationError, APIConnectionError
)
import time
def safe_search(query: str, max_retries: int = 3) -> str | None:
client = OpenAI(api_key="pplx-...", base_url="https://api.perplexity.ai")
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="sonar",
messages=[{"role": "user", "content": query}]
)
return response.choices[0].message.content
except AuthenticationError:
raise # Don't retry auth errors
except RateLimitError:
if attempt == max_retries - 1:
raise
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.