> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# ChatPerplexity 集成

> 使用 LangChain Python 与 ChatPerplexity 聊天模型集成。

本页面将帮助您开始使用 Perplexity [聊天模型](/oss/python/langchain/models)。有关所有 `ChatPerplexity` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/langchain-perplexity/chat_models/ChatPerplexity)。

## 概述

### 集成详情

| 类                                                                                                          | 包                                                                                     | 可序列化 | [JS 支持](https://js.langchain.com/docs/integrations/chat/xai) |                                                  下载量                                                  |                                                 版本                                                 |
| :--------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ | :--: | :----------------------------------------------------------: | :---------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------: |
| [`ChatPerplexity`](https://reference.langchain.com/python/langchain-perplexity/chat_models/ChatPerplexity) | [`langchain-perplexity`](https://reference.langchain.com/python/langchain-perplexity) | beta |                               ❌                              | ![PyPI - Downloads](https://img.shields.io/pypi/dm/langchain-perplexity?style=flat-square\&label=%20) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-perplexity?style=flat-square\&label=%20) |

### 模型特性

| [工具调用](/oss/python/langchain/tools) | [结构化输出](/oss/python/langchain/structured-output) | [图像输入](/oss/python/langchain/messages#multimodal) | 音频输入 | 视频输入 | [令牌级流式传输](/oss/python/langchain/streaming#llm-tokens) | 原生异步 | [令牌使用量](/oss/python/langchain/models#token-usage) | [对数概率](/oss/python/langchain/models#log-probabilities) |
| :---------------------------------: | :----------------------------------------------: | :-----------------------------------------------: | :--: | :--: | :---------------------------------------------------: | :--: | :-----------------------------------------------: | :----------------------------------------------------: |
|                  ❌                  |                         ✅                        |                         ❌                         |   ❌  |   ❌  |                           ✅                           |   ❌  |                         ✅                         |                            ❌                           |

## 设置

要访问 Perplexity 模型，您需要创建一个 Perplexity 账户，获取 API 密钥，并安装 `langchain-perplexity` 集成包。

### 凭证

前往[此页面](https://www.perplexity.ai/)注册 Perplexity 并生成 API 密钥。完成此操作后，设置 `PPLX_API_KEY` 环境变量：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass
import os

if "PPLX_API_KEY" not in os.environ:
    os.environ["PPLX_API_KEY"] = getpass.getpass("Enter your Perplexity API key: ")
```

要启用模型调用的自动跟踪，请设置您的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.prompts import ChatPromptTemplate
from langchain_perplexity import ChatPerplexity
```

提供的代码假设您的 PPLX\_API\_KEY 已在环境变量中设置。如果您想手动指定 API 密钥并选择不同的模型，可以使用以下代码：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0, pplx_api_key="YOUR_API_KEY", model="sonar")
```

您可以查看[可用的 Perplexity 模型列表](https://docs.perplexity.ai/docs/model-cards)。为了可重现性，我们可以通过在此笔记本中将其作为输入来动态设置 API 密钥。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0, model="sonar")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
system = "You are a helpful assistant."
human = "{input}"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])

chain = prompt | chat
response = chain.invoke({"input": "Why is the Higgs Boson important?"})
response.content
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'The Higgs Boson is an elementary subatomic particle that plays a crucial role in the Standard Model of particle physics, which accounts for three of the four fundamental forces governing the behavior of our universe: the strong and weak nuclear forces, electromagnetism, and gravity. The Higgs Boson is important for several reasons:\n\n1. **Final Elementary Particle**: The Higgs Boson is the last elementary particle waiting to be discovered under the Standard Model. Its detection helps complete the Standard Model and further our understanding of the fundamental forces in the universe.\n\n2. **Mass Generation**: The Higgs Boson is responsible for giving mass to other particles, a process that occurs through its interaction with the Higgs field. This mass generation is essential for the formation of atoms, molecules, and the visible matter we observe in the universe.\n\n3. **Implications for New Physics**: While the detection of the Higgs Boson has confirmed many aspects of the Standard Model, it also opens up new possibilities for discoveries beyond the Standard Model. Further research on the Higgs Boson could reveal insights into the nature of dark matter, supersymmetry, and other exotic phenomena.\n\n4. **Advancements in Technology**: The search for the Higgs Boson has led to significant advancements in technology, such as the development of artificial intelligence and machine learning algorithms used in particle accelerators like the Large Hadron Collider (LHC). These advancements have not only contributed to the discovery of the Higgs Boson but also have potential applications in various other fields.\n\nIn summary, the Higgs Boson is important because it completes the Standard Model, plays a crucial role in mass generation, hints at new physics phenomena beyond the Standard Model, and drives advancements in technology.\n'
```

您可以像通常一样格式化和构建提示。在下面的示例中，我们要求模型给我们讲一个关于猫的笑话。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0, model="sonar")
prompt = ChatPromptTemplate.from_messages([("human", "Tell me a joke about {topic}")])
chain = prompt | chat
response = chain.invoke({"topic": "cats"})
response.content
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'Here\'s a joke about cats:\n\nWhy did the cat want math lessons from a mermaid?\n\nBecause it couldn\'t find its "core purpose" in life!\n\nRemember, cats are unique and fascinating creatures, and each one has its own special traits and abilities. While some may see them as mysterious or even a bit aloof, they are still beloved pets that bring joy and companionship to their owners. So, if your cat ever seeks guidance from a mermaid, just remember that they are on their own journey to self-discovery!\n'
```

## 通过 `ChatPerplexity` 使用 Perplexity 特定参数

您还可以通过 ChatPerplexity 类使用 Perplexity 特定的参数。例如，使用 extra\_body 参数传递 search\_domain\_filter、return\_images、return\_related\_questions 或 search\_recency\_filter 等参数，如下所示：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0.7, model="sonar")
response = chat.invoke(
    "Tell me a joke about cats", extra_body={"search_recency_filter": "week"}
)
response.content
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
"Sure, here's a cat joke for you:\n\nWhy are cats bad storytellers?\n\nBecause they only have one tale. (Pun alert!)\n\nSource: OneLineFun.com [4]"
```

### 访问搜索结果元数据

Perplexity 通常会提供其查阅的网页列表（“search\_results”）。
您无需传递任何特殊参数——该列表位于
`response.additional_kwargs["search_results"]` 中。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0, model="sonar")

response = chat.invoke(
    "What is the tallest mountain in South America?",
)

# 主要答案
print(response.content)

# 前两个支持性搜索结果
response.additional_kwargs["search_results"][:2]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
The tallest mountain in South America is Aconcagua. It has a summit elevation of approximately 6,961 meters (22,838 feet), making it not only the highest peak in South America but also the highest mountain in the Americas, the Western Hemisphere, and the Southern Hemisphere[1]\[2]\[4].

Aconcagua is located in the Principal Cordillera of the Andes mountain range, in Mendoza Province, Argentina, near the border with Chile[1]\[2]\[4]. It is of volcanic origin but is not an active volcano[4]. The mountain is part of Aconcagua Provincial Park and features several glaciers, including the large Ventisquero Horcones Inferior glacier[1].

In summary, Aconcagua stands as the tallest mountain in South America at about 6,961 meters (22,838 feet) in height.
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[{'title': 'Aconcagua - Wikipedia',
  'url': 'https://en.wikipedia.org/wiki/Aconcagua',
  'date': None},
 {'title': 'The 10 Highest Mountains in South America - Much Better Adventures',
  'url': 'https://www.muchbetteradventures.com/magazine/highest-mountains-south-america/',
  'date': '2023-07-05'}]
```

## `ChatPerplexity` 也支持流式功能

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
chat = ChatPerplexity(temperature=0.7, model="sonar")

for chunk in chat.stream("Give me a list of famous tourist attractions in Pakistan"):
    print(chunk.content, end="", flush=True)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Here is a list of some famous tourist attractions in Pakistan:

1. **Minar-e-Pakistan**: A 62-meter high minaret in Lahore that represents the history of Pakistan.
2. **Badshahi Mosque**: A historic mosque in Lahore with a capacity of 10,000 worshippers.
3. **Shalimar Gardens**: A beautiful garden in Lahore with landscaped grounds and a series of cascading pools.
4. **Pakistan Monument**: A national monument in Islamabad representing the four provinces and three districts of Pakistan.
5. **National Museum of Pakistan**: A museum in Karachi showcasing the country's cultural history.
6. **Faisal Mosque**: A large mosque in Islamabad that can accommodate up to 300,000 worshippers.
7. **Clifton Beach**: A popular beach in Karachi offering water activities and recreational facilities.
8. **Kartarpur Corridor**: A visa-free border crossing and religious corridor connecting Gurdwara Darbar Sahib in Pakistan to Gurudwara Sri Kartarpur Sahib in India.
9. **Mohenjo-daro**: An ancient Indus Valley civilization site in Sindh, Pakistan, dating back to around 2500 BCE.
10. **Hunza Valley**: A picturesque valley in Gilgit-Baltistan known for its stunning mountain scenery and unique culture.

These attractions showcase the rich history, diverse culture, and natural beauty of Pakistan, making them popular destinations for both local and international tourists.
```

## `ChatPerplexity` 为 3 级及以上用户提供结构化输出

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pydantic import BaseModel


class AnswerFormat(BaseModel):
    first_name: str
    last_name: str
    year_of_birth: int
    num_seasons_in_nba: int


chat = ChatPerplexity(temperature=0.7, model="sonar-pro")
structured_chat = chat.with_structured_output(AnswerFormat)
response = structured_chat.invoke(
    "Tell me about Michael Jordan. Return your answer "
    "as JSON with keys first_name (str), last_name (str), "
    "year_of_birth (int), and num_seasons_in_nba (int)."
)
response
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
AnswerFormat(first_name='Michael', last_name='Jordan', year_of_birth=1963, num_seasons_in_nba=15)
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/chat/perplexity.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
