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

# ChatPerplexity 集成

> 使用 LangChain Python 集成 ChatPerplexity 对话模型。

本页面将帮助您入门Perplexity [智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md)。如需了解所有 `ChatPerplexity` 功能和配置的详细文档，请访问 [API参考](https://reference.langchain.com/python/langchain-perplexity/chat_models/ChatPerplexity)。

## 概述

### 集成细节

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

### 模型特性

| [工具调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | [结构化输出](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/structured-output.md) | [图像输入](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/messages.md#多模态) | 音频输入 | 视频输入 | [Token级流式](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/streaming.md#llm-tokens) | 原生异步 | [Token使用量](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#token-使用) | [对数概率](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/models.md#对数概率) |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ |

## 配置

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

### 凭据

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

```python theme={null}
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](https://docs.langchain.com/langsmith/observability) API密钥：

```python theme={null}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

```python theme={null}
from langchain_core.prompts import ChatPromptTemplate
from langchain_perplexity import ChatPerplexity
```

以下代码假设已通过环境变量设置 PPLX\_API\_KEY。若需手动指定API密钥并选择不同模型，可使用以下代码：

```python theme={null}
chat = ChatPerplexity(temperature=0, pplx_api_key="YOUR_API_KEY", model="sonar")
```

您可查看 [可用的Perplexity模型列表](https://docs.perplexity.ai/getting-started/models)。在笔记本中可通过输入API密钥动态设置以实现可复现性。

```python theme={null}
chat = ChatPerplexity(temperature=0, model="sonar")
```

```python theme={null}
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={null}
'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={null}
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={null}
'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'
```

## 智能体 API 支持（`use_responses_api`）

`ChatPerplexity` 可通过设置 `use_responses_api` 路由请求至Perplexity的 [智能体API](https://docs.perplexity.ai/docs/agent-api/quickstart)（Perplexity风格响应API）。其设计理念与 [`ChatOpenAI.use_responses_api`](https://reference.langchain.com/python/langchain-openai/chat_models/ChatOpenAI)一致：单类、双端点、通过单一标志位控制。

| 值 | 端点 | 备注 |
| :- | :- | :- |
| `None` (默认) | 自动检测 | 当请求使用内置Perplexity工具（`web_search`, `fetch_url`, `finance_search`, `people_search`）或包含响应专用字段（`previous_response_id`, `instructions`, `input`, `include`）时，路由至智能体API；否则路由至Chat Completions。 |
| `True` | 智能体API | 总是使用 `client.responses.create()`。 |
| `False` | Chat Completions | 总是使用 `client.chat.completions.create()`。 |

智能体API提供 `ChatPerplexity` 访问内置工具（实时网络搜索、URL获取、金融与人物搜索）及状态感知字段（`previous_response_id`, `instructions`, `include`），这些在Chat Completions中不可用。现有 `ChatPerplexity(model="sonar")` 调用方式不受影响——纯文本请求默认仍走Chat Completions路径。

```python theme={null}
from langchain_perplexity import ChatPerplexity

chat = ChatPerplexity(
    model="openai/gpt-5.5",
    use_responses_api=True,
)
response = chat.invoke("What did Apple announce at WWDC this week?")
response.content
```

您也可直接传递内置工具，无需设置标志——自动检测即可路由请求：

```python theme={null}
chat = ChatPerplexity(model="openai/gpt-5.5")

response = chat.invoke(
    "Summarize the latest LangChain release notes.",
    tools=[{"type": "web_search"}],
)
response.content
```

通过智能体API路由后，响应对象包含更丰富的元数据：

* `usage_metadata` 从响应形状的 `usage` 载荷填充（`input_tokens`, `output_tokens`, `total_tokens`）
* `response_metadata` 包含传输层字段：`id`, `model`, `status`, `object`
* `additional_kwargs` 提取Perplexity专用输出：`citations`, `images`, `related_questions`, `search_results`, `videos`, `reasoning_steps`
* 模型返回的工具调用在 `response.tool_calls` 中与 `ChatOpenAI` 保持一致

> [!WARNING]
>
> 智能体API不接受Chat-Completions专用采样与控制参数。当 `ChatPerplexity` 路由至智能体API（无论显式或自动检测），以下字段会被 `WARNING` 日志丢弃：`temperature`, `top_p`, `top_k`, `stop`, `metadata`。默认 `temperature` 被 `_default_params` 静默抑制，但用户自定义 `temperature` 仍会警告。
>
> `tool_choice` 不是被静默丢弃——当路由至智能体API时， `ValueError` 会因下游代理循环无法处理缺失的强制工具选择而抛出异常。

请参考 [Perplexity智能体API模型列表](https://docs.perplexity.ai/docs/agent-api/models) 查看完整支持模型列表（例如 `openai/gpt-5.5`, `anthropic/claude-sonnet-4-6`, `google/gemini-3-1-pro`）。

## 通过 `ChatPerplexity` 使用Perplexity专用参数

您也可通过 ChatPerplexity 类使用Perplexity专用参数。例如通过 extra\_body 参数设置以下参数：

```python theme={null}
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={null}
"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={null}
chat = ChatPerplexity(temperature=0, model="sonar")

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

# Main answer
print(response.content)

# First two supporting search results
response.additional_kwargs["search_results"][:2]
```

```text theme={null}
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={null}
[{'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={null}
chat = ChatPerplexity(temperature=0.7, model="sonar")

stream = chat.stream_events("Give me a list of famous tourist attractions in Pakistan", version="v3")
for token in stream.text:
    print(token, end="", flush=True)
```

```text theme={null}
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` 支持结构化输出（需三级及以上用户）

```python theme={null}
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={null}
AnswerFormat(first_name='Michael', last_name='Jordan', year_of_birth=1963, num_seasons_in_nba=15)
```

***

> 官方原文：[src/oss/python/integrations/chat/perplexity.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/chat/perplexity.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.