Perplexity AI搜索API教程
想让自己的应用返回带引用的实时网络答案。
💡 你将学到
想让自己的应用返回带引用的实时网络答案。
📜 目录
Perplexity AI 搜索 API 指南 2026:20 分钟构建一个研究助手
Perplexity API 是为应用添加实时网页搜索的最简单方式。与普通的 LLM API 不同,它在回答之前会执行真实的网页搜索,并返回引用来源。截至 2026 年 8 月,该 API 支持 sonar 和 sonar-pro 模型,sonar-deep-research 处于测试阶段,用于多步骤研究。
你将获得
- 带引用来源的实时网页答案
- 与普通 LLM 调用相当的 Token 用量
- Python SDK 和 REST 端点
- 按用量计费,新账户有免费额度
第 1 步:获取 API 密钥
在 perplexity.ai 注册,进入 设置 > API,创建一个密钥。截至 2026 年年中,新账户可获得 $5 的免费额度——大约可进行 2,000 次 sonar 查询。
第 2 步:最小调用示例
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": "简洁回答并附上引用来源。"},
{"role": "user", "content": "Raspberry Pi 5 的最新规格是什么?"}
],
)
print(response.choices[0].message.content)
响应中包含一个带 URL 的 citations 字段。这就是全部要点——你的应用现在可以带着实时来源来回答问题了。
第 3 步:强制最新搜索
在请求体中设置 "search_recency_filter": "week",强制使用最近一周的搜索窗口。默认是最近一个月。
第 4 步:处理引用来源
for c in response.citations:
print(c.url)
存储这些 URL 并将它们渲染为链接——用户更信任可以验证的答案。
成本实况(2026 年 8 月)
| 模型 | 输入 | 输出 | 备注 |
|---|---|---|---|
| sonar | $1/百万 Token | $1/百万 Token | 快速,基础搜索 |
| sonar-pro | $3/百万 Token | $15/百万 Token | 更强的推理能力 |
| sonar-deep-research | $5/次调用 | - | 多步骤研究(测试版) |
常见问题
Perplexity API 免费吗? 有 $5 的试用额度;之后按用量计费。
可以不使用 OpenAI SDK 吗? 可以,REST 端点是 https://api.perplexity.ai/chat/completions,请求体格式相同。
它与 ChatGPT API 有什么区别? Perplexity 在回答前会执行实时网页搜索;而普通的 LLM API 只能使用其训练数据。
相关文章
❓ 常见问题
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.
本站文章由编辑人工撰写,收录的工具均经过实测或公开资料核验。文中链接指向工具官网或 GitHub 仓库,仅作信息参考,不构成付费推广。
