PE

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.zip

Installs 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.
72 charsno explicit “when” trigger
Beginner

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

You give it
Search query string
You get back
Web-grounded answer with citation URLs

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-auth setup
  • openai package installed
  • PERPLEXITY_API_KEY environment 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

ErrorCauseSolution
401 UnauthorizedInvalid API keyVerify key at perplexity.ai/settings/api
Empty citations arrayQuery too abstractAsk a specific, factual question
429 Too Many RequestsRate limit exceededWait and retry with backoff
TimeoutComplex search queryUse 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

PERPLEXITY_API_KEYopenai package

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.

SkillInstallsUpdatedSafetyDifficulty
perplexity-hello-world (this skill)127dReviewBeginner
claude-opus-4-5-migration98moNo flagsBeginner
copilot-sdk74moReviewIntermediate
api-test-generator19moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

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.

9101

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.

763

api-test-generator

mikopbx

Генерация полных Python pytest тестов для REST API эндпоинтов с валидацией схемы. Использовать при создании тестов для новых эндпоинтов, добавлении покрытия для CRUD операций или валидации соответствия API с OpenAPI схемами.

16

create-bubble

bubblelabai

Create a new Bubble integration for Bubble Lab following all established patterns and best practices from CREATE_BUBBLE_README.md

23

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".

14

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".

13

Search skills

Search the agent skills registry