ChatPerplexity
This page will help you get started with Perplexity chat models. For detailed documentation of all ChatPerplexity
features and configurations head to the API reference.
The Perplexity API combines real-time, grounded web search with advanced reasoning and deep research capabilities. This allows your application to tap into up-to-date and verified information.
When to use:
- When your application requires timely, relevant data directly from the web, such as dynamic content updates or current event tracking.
- For products that need to support complex user queries with integrated reasoning and deep research, like digital assistants or advanced search engines.
For more information around Perplexity's API please visit the official API developer documentation.
Overview​
Integration details​
Class | Package | Local | Serializable | JS support | Package downloads | Package latest |
---|---|---|---|---|---|---|
ChatPerplexity | langchain-perplexity | ❌ | beta | ❌ |
Model features​
Tool calling | Structured output | JSON mode | Image input | Audio input | Video input | Token-level streaming | Native async | Token usage | Logprobs |
---|---|---|---|---|---|---|---|---|---|
❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ |
Setup​
To access Perplexity models you'll need to create a Perplexity account, get an API key, and install the langchain-perplexity
integration package.
Credentials​
Head to this page to sign up for Perplexity and generate an API key. Once you've done this set the PPLX_API_KEY
environment variable:
# !pip install langchain_perplexity
import getpass
import os
if "PPLX_API_KEY" not in os.environ:
os.environ["PPLX_API_KEY"] = getpass.getpass("Enter your Perplexity API key: ")
To enable automated tracing of your model calls, set your LangSmith API key:
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
from langchain_core.prompts import ChatPromptTemplate
from langchain_perplexity import ChatPerplexity
The code provided assumes that your PPLX_API_KEY is set in your environment variables. If you would like to manually specify your API key and also choose a different model, you can use the following code:
PPLX_API_KEY = __import__("os").environ.get("PPLX_API_KEY")
chat = ChatPerplexity(
temperature=0.2,
pplx_api_key=PPLX_API_KEY,
model="sonar-pro"
)
You can view a list of available models here. For reproducibility, we can set the API key dynamically by taking it as an input in this notebook.
system = "Be precise and concise."
human = "{input}"
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
chain = prompt | chat
response = chain.invoke({"input": "What is the weather like in NYC today?"})
response.content
'The weather in New York City today, Saturday, April 12, 2025, is cold and rainy. The high temperature is around 42°F, with rain and drizzle throughout the day, becoming windy in the afternoon. Tonight, the low temperature will be approximately 40°F, with breezy conditions and occasional rain and drizzle continuing[1][2][3].\n\nCurrently, the temperature is about 39°F, with a RealFeel® of 32°F due to wind and humidity. Winds are coming from the northeast at 11-16 mph, with gusts up to 33 mph. The humidity level is high at 85%, and cloud cover is nearly complete at 99-100%[2][3].'
You can format and structure the prompts like you would typically, while bearing in mind that this gives you access to real-time web search which requires a specific prompting strategy. You can read more about this in Perplexity's prompting guide here.
For example, we can ask the model to give us news on specific topics:
chat = ChatPerplexity(temperature=0, model="sonar-pro")
prompt = ChatPromptTemplate.from_messages([("human", "Tell me the latest news around {topic}")])
chain = prompt | chat
response = chain.invoke({"topic": "the US stock market"})
response.content
'The U.S. stock market experienced a significant rebound on Friday, April 11, 2025, with the Dow Jones Industrial Average closing over 600 points higher. This surge followed a tumultuous week marked by volatility. The positive market sentiment was driven by optimism surrounding potential tariff deals between the U.S. and China, as well as encouraging economic data. Investors were hopeful that ongoing trade tensions could be resolved, with the White House signaling progress in negotiations. Despite this optimism, experts cautioned that market volatility could persist in the coming weeks[1].\n\nAdditionally, the first-quarter earnings season began, with major banks like JPMorgan Chase, Morgan Stanley, and Wells Fargo reporting better-than-expected results. However, bank executives expressed concerns about ongoing uncertainty and the need for a resolution to trade tensions. Consumer spending remained strong, according to JPMorgan Chase, but the broader economic outlook remains uncertain due to geopolitical and trade-related challenges[1].'
Using Perplexity-specific parameters through ChatPerplexity
​
You can also use Perplexity-specific parameters through the ChatPerplexity
class to fine-tune how your web search works. For example, using the extra_body parameter, you can supply options such as:
- search_domain_filter: Restricts search results to specified domains or excludes certain domains, ensuring that only content from approved or relevant websites is included.
- return_images: If enabled, allows the API to return images along with text content, enriching the search results with visual context.
- return_related_questions: Provides additional context by returning a set of related questions based on the query, which can help in exploring further or clarifying information.
- search_recency_filter: Filters results based on recency, ensuring that the most current information is prioritized according to the time frame you specify (e.g., the past week or month).
These parameters empower you to tailor the search outputs to meet specific requirements for accuracy, relevance, and presentation in your applications.
chat = ChatPerplexity(temperature=0.2, model="sonar-pro")
response = chat.invoke(
"Give me the latest updates around US tariffs.",
extra_body={
"search_recency_filter": "week",
"search_domain_filter":["-cnn.com"], # You can also blacklist domains by adding a "-" sign in front
"return_related_questions":True,
"return_images":True
})
response.content
'The latest updates on U.S. tariffs indicate a significant escalation in the ongoing trade tensions between the United States and China. On April 11, 2025, China announced a sharp increase in tariffs on U.S. imports, raising rates from 84% to 125%, effectively more than doubling the costs of American goods entering the Chinese market. This move is a direct retaliation to a recent decision by the U.S. to impose higher tariffs on Chinese products. The trade war between the two largest economies shows no signs of de-escalation, with both sides continuing to implement aggressive economic measures against each other[1].'
ChatPerplexity
also supports streaming functionality:​
chat = ChatPerplexity(temperature=0.2, model="sonar-reasoning-pro")
for chunk in chat.stream("Analyze the feasibility of fusion energy becoming a mainstream power source by 2040."):
print(chunk.content, end="", flush=True)
<think>
Okay, let's tackle this question about whether fusion energy can become a mainstream power source by 2040. First, I need to go through all the search results provided and see what they say about current progress, challenges, and timelines.
Starting with the UK's STEP project mentioned in sources [1] and [7], they're aiming for a prototype plant by 2040. That's a key point. The UK government is investing over ÂŁ220 million, which shows commitment. But the article also mentions that ITER in France is facing delays and might not produce electricity until 2050. That's a red flag because ITER is a major international effort, and if it's delayed, it could affect broader timelines.
Source [5] talks about the US National Academy of Sciences suggesting a fusion pilot plant by 2035-2040. So the US is also targeting that timeframe. But they note significant technical and economic challenges. Private companies like General Atomics are involved, which is a good sign of both public and private sector interest.
Looking at the technical challenges, sources [1], [3], and [4] all mention the difficulty of sustaining the extreme temperatures and pressures needed for fusion. The Lawson criterion is a big hurdle. Even though JET (source [1]) made progress with a 5-second plasma, that's nowhere near the continuous operation needed for a power plant. Also, materials that can withstand neutron bombardment are still in development (source [6]).
Economic factors are another concern. Source [4] points out that the levelized cost of energy for fusion is estimated to be much higher than renewables like solar and wind. If fusion can't compete on cost, it might not become mainstream even if technically feasible. Plus, the initial capital costs are massive, which could deter investment unless there's strong government support.
International collaboration is happening with ITER and other projects, but source [7] mentions that each country is also pursuing its own initiatives, like the UK's STEP and China's CFETR. This could lead to fragmented progress, but also multiple avenues for breakthroughs.
Environmental benefits are clear from sources [9] and [3]—fusion produces no carbon emissions and minimal radioactive waste. However, tritium supply is an issue. Breeding tritium from lithium in the reactor is part of the plan, but that technology isn't fully proven yet (source [7]).
Private sector involvement is growing, with companies like General Fusion and Tokamak Energy making strides (sources [4] and [6]). This could accelerate development, but many of these are still in experimental stages.
Considering all this, the 2040 target is ambitious. The UK and US have pilot plants planned, but transitioning from prototypes to commercial-scale reactors in just 20 years is a huge leap. ITER's delays and the unresolved technical challenges (like materials and sustained plasma) suggest that while there might be some demonstration plants by 2040, mainstream adoption would require rapid scaling and cost reductions that may not be feasible by then. Also, competition from cheaper renewables could limit fusion's role unless it achieves significant cost breakthroughs.
In conclusion, fusion might start contributing to the energy mix by 2040 with pilot plants, but becoming a mainstream source would likely take longer, possibly into the 2050s or beyond. The progress is promising, but the technical and economic hurdles are substantial.
</think>
Nuclear fusion holds transformative potential as a nearly limitless, clean energy source, but its feasibility as a mainstream power source by 2040 faces significant technical, economic, and logistical challenges. Here’s a structured analysis:
### **Current Progress and Key Projects**
- **STEP (UK)**: The UK’s Spherical Tokamak for Energy Production aims to demonstrate net energy gain and grid connectivity by the 2040s, replacing a coal plant in Nottinghamshire[1][7]. The design emphasizes compact spherical tokamaks to reduce costs and improve maintenance[7].
- **ITER (France)**: This multinational project targets 500 MW of fusion power by the 2030s but has faced delays, with full operation now expected around 2050[1][6]. ITER’s success is critical for validating plasma confinement and energy scalability[9].
- **Private Initiatives**: Companies like General Fusion and Tokamak Energy are advancing compact reactor designs, with some aiming for pilot plants by the 2030s[4][6]. The U.S. National Academy of Sciences also envisions a fusion pilot plant by 2035–2040[5].
### **Technical Challenges**
1. **Plasma Stability and Energy Gain**: Sustaining plasma at 100–300 million°C without disruptions remains a hurdle. While JET achieved 59 megajoules over 5 seconds (11 MW), this is far from continuous operation[1][6].
2. **Materials Science**: Reactor components must withstand neutron bombardment and extreme heat. Tritium breeding blankets (to fuel the reaction) are still in experimental stages[7][9].
3. **Net Energy Breakthrough**: Most experiments, including the National Ignition Facility’s 2022 milestone, have not yet achieved a sustained energy gain ratio (Q) >10, a prerequisite for commercial viability[8].
### **Economic and Logistical Hurdles**
- **High Costs**: ITER’s budget has ballooned to ~$22 billion, and the UK’s STEP requires £220 million in initial funding[1][7]. Levelized cost estimates for fusion (~$121/MWh) exceed solar ($40–46/MWh) and onshore wind ($29–56/MWh)[4].
- **Supply Chains and Expertise**: Building specialized components (e.g., superconducting magnets) and training a skilled workforce will take decades[7].
### **Environmental and Competitive Landscape**
- **Advantages**: Fusion produces no COâ‚‚, minimal long-lived radioactive waste, and uses abundant fuel (deuterium from seawater, lithium for tritium)[9].
- **Renewables Competition**: Solar and wind are already cost-competitive and scalable, raising questions about fusion’s market niche[4][8].
### **Pathway to 2040**
- **Pilot Plants**: The UK’s STEP and U.S. public-private partnerships aim to demonstrate net electricity by 2040, but these will likely remain experimental rather than commercial[1][5][7].
- **Fuel Cycle Proof-of-Concept**: Achieving a closed tritium cycle (self-sustaining fuel) is critical and untested at scale[7][9].
- **Regulatory Frameworks**: Safety and licensing protocols for fusion reactors are still under development globally[6].
### **Conclusion**
While 2040 may see the first fusion pilot plants delivering electricity to grids, **mainstream adoption by this date is unlikely**. Technical breakthroughs in plasma control, materials, and tritium breeding are still needed, and costs must plummet to compete with renewables. Optimistic projections suggest fusion could contribute ~10% of global energy by 2050–2060 if current momentum persists[2][6][8]. For now, fusion remains a promising but nascent complement to existing low-carbon technologies.
Structured outputs with ChatPerplexity
​
Please follow the official documentation regarding structured outputs.
from pydantic import BaseModel
class NewsResult(BaseModel):
headline: str
summary: str
url: str
publication_date: str
# Initialize ChatPerplexity with desired parameters
chat = ChatPerplexity(temperature=0.7, model="sonar-pro")
# Create a structured output instance using the defined Pydantic schema
structured_chat = chat.with_structured_output(NewsResult)
# Invoke the API with a query that requires deep research on renewable energy breakthroughs.
response = structured_chat.invoke(
"Provide a comprehensive overview of renewable energy breakthroughs. "
"Your analysis should include detailed insights on industry trends, policy impacts, and expert opinions, "
"not just the headline. Return your answer as JSON with keys: headline (str), summary (str), url (str), "
"and publication_date (str).",
)
print(response.headline)
print(response.summary)
print(response.url)
Renewable Energy Industry Sees Major Developments in 2025
In 2025, the renewable energy sector is witnessing significant growth and technological advancements. Utility-scale solar and wind projects dominate new installations, with projections indicating solar capacity to surpass hydropower globally by 2029. The U.S. sees strong policy-driven growth, particularly through mechanisms like the Inflation Reduction Act and state-level Renewable Portfolio Standards. Globally, solar and wind energy technologies continue experiencing efficiency improvements, cost reductions, and expanded deployment. Policymakers and industry leaders focus on addressing infrastructure challenges, such as grid capacity and supply chain issues, to meet the rising demand for renewable energy sources.
https://www2.deloitte.com/us/en/insights/industry/renewable-energy/renewable-energy-industry-outlook.html
Using ChatPerplexity
as a tool within Langchain
You can mark the ask_perplexity
function as a LangChain tool by using LangChain's built-in @tool
decorator.
If you choose to use ChatPerplexity
as a tool, you may want to enable our search classifier to help you decide whether internet search is necessary in this context. You can do this by setting enable_search_classifier
to True.
from langchain_core.tools import tool
from langchain_perplexity import ChatPerplexity
@tool
def ask_perplexity(query: str) -> str:
"""
A tool for querying the Perplexity API's generative search capabilities.
By setting `enable_search_classifier` to True in extra body, the API can intelligently
decide whether to execute a full web search or bypass it, depending on the query.
This helps to reduce unnecessary searches while still delivering accurate responses.
"""
llm = ChatPerplexity(model="sonar")
return llm.invoke(query)
if __name__ == "__main__":
query = "Tell me a really good joke."
result = ask_perplexity(query)
print("Query result:")
print(result.content)
Query result:
Here's a good one:
**Why did the scarecrow win an award?**
Because he was outstanding in his field.
This joke plays on the double meaning of "outstanding in his field," which could refer both to the scarecrow's exceptional abilities and his physical presence in a field[2][3].
Related​
- Chat model conceptual guide
- Chat model how-to guides