perplexity-hello-world
A quick-start guide to implementing a basic Perplexity Sonar search feature with citation handling in your code.
Install
mkdir -p .claude/skills/perplexity-hello-world && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5379" && unzip -o skill.zip -d .claude/skills/perplexity-hello-world && rm skill.zipInstalls to .claude/skills/perplexity-hello-world
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Create a minimal working Perplexity Sonar search example with citations.Key capabilities
- →Perform web-grounded search queries
- →Access and parse citation data from responses
- →Filter search results by domain and recency
- →Implement streaming responses for search
- →Monitor token usage for billing
How it works
The skill demonstrates how to use the OpenAI SDK to interface with the Perplexity API, specifically showing how to extract citation arrays and apply search filters.
Inputs & outputs
When to use perplexity-hello-world
- →Prototyping Perplexity integrations
- →Testing API connectivity
- →Learning to process citation outputs
- →Building search-grounded AI features
About this skill
Perplexity Hello World
Overview
Minimal working example demonstrating Perplexity's core value: web-grounded answers with citations. Unlike standard LLMs, Perplexity searches the web for every query and returns cited sources.
Prerequisites
- Completed
perplexity-install-authsetup openaipackage installedPERPLEXITY_API_KEYenvironment variable set
Instructions
Step 1: Basic Search with Citations (TypeScript)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.PERPLEXITY_API_KEY,
baseURL: "https://api.perplexity.ai",
});
async function main() {
const response = await client.chat.completions.create({
model: "sonar",
messages: [
{
role: "system",
content: "Be precise and cite your sources.",
},
{
role: "user",
content: "What are the latest features in Node.js 22?",
},
],
});
const answer = response.choices[0].message.content;
console.log("Answer:", answer);
// Citations are returned as a top-level array on the response
const citations = (response as any).citations || [];
console.log("\nSources:");
citations.forEach((url: string, i: number) => {
console.log(` [${i + 1}] ${url}`);
});
// Usage breakdown
console.log("\nUsage:", {
prompt_tokens: response.usage?.prompt_tokens,
completion_tokens: response.usage?.completion_tokens,
total_tokens: response.usage?.total_tokens,
});
}
main().catch(console.error);
Step 2: Basic Search with Citations (Python)
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["PERPLEXITY_API_KEY"],
base_url="https://api.perplexity.ai",
)
response = client.chat.completions.create(
model="sonar",
messages=[
{"role": "system", "content": "Be precise and cite your sources."},
{"role": "user", "content": "What are the latest features in Node.js 22?"},
],
)
answer = response.choices[0].message.content
print("Answer:", answer)
# Citations from the raw response
raw = response.model_dump()
citations = raw.get("citations", [])
print("\nSources:")
for i, url in enumerate(citations, 1):
print(f" [{i}] {url}")
print(f"\nTokens: {response.usage.total_tokens}")
Step 3: Search with Domain Filter
// Restrict search to specific domains
const response = await client.chat.completions.create({
model: "sonar",
messages: [
{ role: "user", content: "What is the latest Python release?" },
],
// Perplexity-specific parameters (pass as extra body)
search_domain_filter: ["python.org", "docs.python.org"],
search_recency_filter: "month",
} as any);
Step 4: Streaming Search
const stream = await client.chat.completions.create({
model: "sonar",
messages: [
{ role: "user", content: "Explain quantum computing breakthroughs in 2025" },
],
stream: true,
});
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content || "";
process.stdout.write(text);
// Citations arrive in the final chunk
if ((chunk as any).citations) {
console.log("\n\nSources:", (chunk as any).citations);
}
}
Output
- Working search query returning a web-grounded answer
- Parsed citation URLs from the response
- Token usage stats confirming billing
Error Handling
| Error | Cause | Solution |
|---|---|---|
401 Unauthorized | Invalid API key | Verify key at perplexity.ai/settings/api |
| Empty citations array | Query too abstract | Ask a specific, factual question |
429 Too Many Requests | Rate limit exceeded | Wait and retry with backoff |
| Timeout | Complex search query | Use sonar instead of sonar-pro |
Resources
Next Steps
Proceed to perplexity-local-dev-loop for development workflow setup.
When not to use it
- →When the task does not require web-grounded information
- →When the application requires non-OpenAI compatible SDK patterns
Prerequisites
Limitations
- →Citations are only available for web-grounded queries
- →Requires specific model selection for optimal search performance
How it compares
It highlights the specific handling of citation data and search-specific parameters that are unique to the Perplexity API.
Compared to similar skills
perplexity-hello-world side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| perplexity-hello-world (this skill) | 1 | 27d | Review | Beginner |
| claude-opus-4-5-migration | 9 | 8mo | No flags | Beginner |
| copilot-sdk | 7 | 4mo | Review | Intermediate |
| api-test-generator | 1 | 9mo | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by jeremylongshore
View all by jeremylongshore →You might also like
claude-opus-4-5-migration
anthropics
Migrate prompts and code from Claude Sonnet 4.0, Sonnet 4.5, or Opus 4.1 to Opus 4.5. Use when the user wants to update their codebase, prompts, or API calls to use Opus 4.5. Handles model string updates and prompt adjustments for known Opus 4.5 behavioral differences. Does NOT migrate Haiku 4.5.
copilot-sdk
github
Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.
api-test-generator
mikopbx
Генерация полных Python pytest тестов для REST API эндпоинтов с валидацией схемы. Использовать при создании тестов для новых эндпоинтов, добавлении покрытия для CRUD операций или валидации соответствия API с OpenAPI схемами.
create-bubble
bubblelabai
Create a new Bubble integration for Bubble Lab following all established patterns and best practices from CREATE_BUBBLE_README.md
exa-sdk-patterns
jeremylongshore
Apply production-ready Exa SDK patterns for TypeScript and Python. Use when implementing Exa integrations, refactoring SDK usage, or establishing team coding standards for Exa. Trigger with phrases like "exa SDK patterns", "exa best practices", "exa code patterns", "idiomatic exa".
generating-api-sdks
jeremylongshore
Generate client SDKs in multiple languages from OpenAPI specifications. Use when generating client libraries for API consumption. Trigger with phrases like "generate SDK", "create client library", or "build API SDK".