Implementation:Langchain ai Langchain ChatPerplexity
| Knowledge Sources | |
|---|---|
| Domains | LLM Integration, Chat Models, Search-Augmented Generation |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
LangChain chat model wrapper around the Perplexity AI Chat Completions API, providing search-augmented language model capabilities.
Description
ChatPerplexity is a class in the langchain-perplexity partner package that extends BaseChatModel from langchain-core. It wraps the Perplexity AI API to provide chat completions with built-in web search capabilities, citation tracking, and support for specialized search modes (academic, SEC filings, web). The class supports synchronous and asynchronous generation, streaming, structured output via JSON schema, and Perplexity-specific features such as reasoning steps, related questions, image/video responses, and search result metadata.
Usage
Import ChatPerplexity when building LangChain applications that need Perplexity AI's search-augmented chat models with real-time web knowledge.
Code Reference
Source Location
- Repository: Langchain_ai_Langchain
- File: libs/partners/perplexity/langchain_perplexity/chat_models.py
- Lines: 1-816
Signature
class ChatPerplexity(BaseChatModel):
client: Any = Field(default=None, exclude=True)
async_client: Any = Field(default=None, exclude=True)
model: str = "sonar"
temperature: float = 0.7
model_kwargs: dict[str, Any] = Field(default_factory=dict)
pplx_api_key: SecretStr | None = Field(
default_factory=secret_from_env("PPLX_API_KEY", default=None), alias="api_key"
)
request_timeout: float | tuple[float, float] | None = Field(None, alias="timeout")
max_retries: int = 6
streaming: bool = False
max_tokens: int | None = None
search_mode: Literal["academic", "sec", "web"] | None = None
reasoning_effort: Literal["low", "medium", "high"] | None = None
...
Import
from langchain_perplexity import ChatPerplexity
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| model | str | No | Model name to use. Defaults to "sonar". |
| temperature | float | No | Sampling temperature. Defaults to 0.7. |
| pplx_api_key | SecretStr or None | No | Perplexity API key. Reads from PPLX_API_KEY environment variable if not set. |
| max_tokens | int or None | No | Maximum number of tokens to generate. |
| streaming | bool | No | Whether to stream results. Defaults to False. |
| max_retries | int | No | Maximum retries on failure. Defaults to 6. |
| request_timeout | float or tuple or None | No | Timeout for API requests. |
| search_mode | Literal["academic", "sec", "web"] or None | No | Specialized search mode for content. |
| reasoning_effort | Literal["low", "medium", "high"] or None | No | Reasoning effort level. |
| language_preference | str or None | No | Language preference for responses. |
| search_domain_filter | list[str] or None | No | List of domains to filter search results (max 20). |
| return_images | bool | No | Whether to return images. Defaults to False. |
| return_related_questions | bool | No | Whether to return related questions. Defaults to False. |
| search_recency_filter | Literal["day", "week", "month", "year"] or None | No | Filter search results by recency. |
| disable_search | bool | No | Whether to disable web search entirely. Defaults to False. |
| web_search_options | WebSearchOptions or None | No | Configuration for web search behavior. |
| media_response | MediaResponse or None | No | Media response configuration. |
Outputs
| Name | Type | Description |
|---|---|---|
| ChatResult | ChatResult | Contains AIMessage with content, usage_metadata, response_metadata, and additional_kwargs (citations, images, videos, reasoning_steps, related_questions, search_results). |
| ChatGenerationChunk | ChatGenerationChunk | When streaming, yields chunks with incremental content and metadata. |
Key Methods
| Method | Description |
|---|---|
| _generate(messages, stop, run_manager, **kwargs) | Synchronous generation. Delegates to streaming if streaming=True. |
| _agenerate(messages, stop, run_manager, **kwargs) | Async generation. Delegates to async streaming if streaming=True. |
| _stream(messages, stop, run_manager, **kwargs) | Synchronous streaming via Perplexity client. |
| _astream(messages, stop, run_manager, **kwargs) | Async streaming via Perplexity async client. |
| with_structured_output(schema, method, include_raw, strict, **kwargs) | Returns a Runnable that produces structured output matching the given schema. Only supports "json_schema" method. |
Usage Examples
Basic Usage
from langchain_perplexity import ChatPerplexity
model = ChatPerplexity(model="sonar", temperature=0.7)
messages = [("system", "You are a chatbot."), ("user", "Hello!")]
response = model.invoke(messages)
print(response.content)
Streaming
from langchain_perplexity import ChatPerplexity
model = ChatPerplexity(model="sonar", streaming=True)
for chunk in model.stream([("user", "What is quantum computing?")]):
print(chunk.content, end="")
Structured Output
from pydantic import BaseModel
from langchain_perplexity import ChatPerplexity
class StructuredOutput(BaseModel):
role: str
content: str
model = ChatPerplexity(model="sonar")
structured = model.with_structured_output(StructuredOutput)
result = structured.invoke([("user", "Describe your role.")])
Response Metadata
Perplexity responses include rich metadata in additional_kwargs on the AIMessage:
- citations: List of cited sources from web search.
- images: Image results when return_images is enabled.
- videos: Video results when media_response includes videos.
- related_questions: Related questions when return_related_questions is enabled.
- search_results: Raw search results.
- reasoning_steps: Reasoning step details for reasoning-capable models.
The response_metadata includes:
- model_name: The model used for the response.
- num_search_queries: Number of search queries executed.
- search_context_size: Size of the search context used.