Perplexity AI搜索API教程
想让自己的应用返回带引用的实时网络答案。
Perplexity AI Search API Guide 2026: Build a Research Assistant in 20 Minutes
The Perplexity API is the easiest way to add live web search to an app. Unlike a plain LLM API, it runs a real web search before answering and returns citations. By August 2026 the API supports the sonar and sonar-pro models, with sonar-deep-research in beta for multi-step research.
What You Get
- Real-time web answers with cited sources
- Token usage comparable to a normal LLM call
- A Python SDK and REST endpoint
- Usage-based pricing with a free tier for new accounts
Step 1: Get a Key
Sign up at perplexity.ai, go to Settings > API, and create a key. As of mid-2026, new accounts get $5 in free credits - roughly 2,000 sonar queries.
Step 2: The Minimal Call
from openai import OpenAI
client = OpenAI(api_key="pplx-...", base_url="https://api.perplexity.ai")
response = client.chat.completions.create(
model="sonar",
messages=[
{"role": "system", "content": "Answer concisely with citations."},
{"role": "user", "content": "What are the latest specs of the Raspberry Pi 5?"}
],
)
print(response.choices[0].message.content)
The response includes a citations field with URLs. That is the whole trick - your app now answers with live sources.
Step 3: Force Fresh Search
Set "search_recency_filter": "week" in the extra body to force a recent search window. Default is month.
Step 4: Handle Citations
for c in response.citations:
print(c.url)
Store the URLs and render them as links - users trust answers they can verify.
Cost Reality Check (August 2026)
| Model | Input | Output | Notes |
|---|---|---|---|
| sonar | $1/M tokens | $1/M tokens | Fast, basic search |
| sonar-pro | $3/M tokens | $15/M tokens | Stronger reasoning |
| sonar-deep-research | $5/call | - | Multi-step research (beta) |
FAQ
Is the Perplexity API free? There is a $5 trial credit; after that it is usage-based.
Can I use it without the OpenAI SDK? Yes, the REST endpoint is https://api.perplexity.ai/chat/completions with the same body format.
How is it different from the ChatGPT API? Perplexity performs live web search before answering; a plain LLM API only uses its training data.
