跳到主要内容
本指南将帮助您开始使用 Perplexity 聊天模型。有关所有 ChatPerplexity 功能和配置的详细文档,请参阅API 参考

概览

集成详情

类别本地可序列化PY 支持下载量版本
ChatPerplexity@langchain/community测试版NPM - DownloadsNPM - Version

模型功能

有关如何使用特定功能的指南,请参阅下表标题中的链接。
工具调用结构化输出JSON 模式图像输入音频输入视频输入令牌级流式传输Token 用量Logprobs
请注意,在撰写本文时,Perplexity 仅在特定使用层级支持结构化输出。

设置

要访问 Perplexity 模型,您需要创建一个 Perplexity 账户,获取一个 API 密钥,并安装 @langchain/community 集成包。

凭据

访问https://perplexity.ai 注册 Perplexity 并生成一个 API 密钥。完成后,设置 PERPLEXITY_API_KEY 环境变量。
export PERPLEXITY_API_KEY="your-api-key"
如果您想获取模型调用的自动化跟踪,您还可以通过取消注释下方来设置您的 LangSmith API 密钥
# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

安装

LangChain Perplexity 集成位于 @langchain/community 包中。
npm install @langchain/community @langchain/core

实例化

现在我们可以实例化我们的模型对象并生成聊天完成
import { ChatPerplexity } from "@langchain/community/chat_models/perplexity"

const llm = new ChatPerplexity({
  model: "sonar",
  temperature: 0,
  maxTokens: undefined,
  timeout: undefined,
  maxRetries: 2,
  // other params...
})

调用

const aiMsg = await llm.invoke([
  {
    role: "system",
    content: "You are a helpful assistant that translates English to French. Translate the user sentence.",
  },
  {
    role: "user",
    content: "I love programming.",
  },
])
aiMsg
AIMessage {
  "id": "run-71853938-aa30-4861-9019-f12323c09f9a",
  "content": "J'adore la programmation.",
  "additional_kwargs": {
    "citations": [
      "https://careersatagoda.com/blog/why-we-love-programming/",
      "https://henrikwarne.com/2012/06/02/why-i-love-coding/",
      "https://forum.freecodecamp.org/t/i-love-programming-but/497502",
      "https://ilovecoding.org",
      "https://thecodinglove.com"
    ]
  },
  "response_metadata": {
    "tokenUsage": {
      "promptTokens": 20,
      "completionTokens": 9,
      "totalTokens": 29
    }
  },
  "tool_calls": [],
  "invalid_tool_calls": []
}
console.log(aiMsg.content)
J'adore la programmation.

API 参考

有关所有 ChatPerplexity 功能和配置的详细文档,请参阅API 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.