Skip to content
perplexity-hello-world logo

Perplexity Hello World

perplexity-hello-world

Create a minimal working Perplexity Sonar search example with citations.

SKILL.md

Full skill instructions

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.

More skills from jeremylongshore

openrouter-compliance-review logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-compliance-review

Review OpenRouter integration for regulatory compliance (SOC2, GDPR,

2.8K 0
View
maintainx-data-handling logo
jeremylongshore/claude-code-plugins-plus-skills

maintainx-data-handling

Data synchronization, ETL patterns, and data management for MaintainX.

2.8K 0
View
groq-core-workflow-a logo
jeremylongshore/claude-code-plugins-plus-skills

groq-core-workflow-a

Execute Groq primary workflow: chat completions with tool use and JSON

2.8K 0
View
validating-csrf-protection logo
jeremylongshore/claude-code-plugins-plus-skills

validating-csrf-protection

Validate CSRF protection implementations for security gaps. Use when

2.8K 0
View
api-contract logo
jeremylongshore/claude-code-plugins-plus-skills

api-contract

Configure this skill should be used when the user asks about "API contract",

2.8K 0
View
ideogram-incident-runbook logo
jeremylongshore/claude-code-plugins-plus-skills

ideogram-incident-runbook

Execute Ideogram incident response with triage, mitigation, and postmortem.

2.8K 0
View
gamma-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

gamma-sdk-patterns

Reusable patterns for the Gamma REST API (no SDK exists).

2.8K 0
View
deepgram-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

deepgram-sdk-patterns

Apply production-ready Deepgram SDK patterns for TypeScript and Python.

2.8K 0
View
openrouter-upgrade-migration logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-upgrade-migration

Migrate to OpenRouter from direct provider APIs or upgrade between SDK/model

2.8K 0
View
openrouter-common-errors logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-common-errors

Diagnose and fix common OpenRouter API errors. Use when encountering

2.8K 0
View
linear-cost-tuning logo
jeremylongshore/claude-code-plugins-plus-skills

linear-cost-tuning

Optimize Linear API usage, reduce unnecessary calls, and maximize

2.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View