The langchain-perplexity package provides LangChain integrations for Perplexity’s API, enabling you to build LLM applications with real-time web search capabilities.
LangChain is a popular Python framework for building applications powered by large language models. It provides composable components for chains, agents, and retrieval-augmented generation (RAG). Learn more at langchain.com.
The integration includes:
ChatPerplexity - Chat model with Pro Search, streaming, and search controls
PerplexitySearchRetriever - Retriever for RAG applications
PerplexitySearchResults - Tool for LangChain agents
Use ChatPerplexity for conversational AI with web search:
from langchain_perplexity import ChatPerplexitychat = ChatPerplexity(model="sonar")response = chat.invoke("What breakthroughs in fusion energy have been announced this year?")print(response.content)
from langchain_perplexity import ChatPerplexity, WebSearchOptionschat = ChatPerplexity( model="sonar-pro", web_search_options=WebSearchOptions(search_type="pro"))response = chat.invoke("How does the electoral college work?")# Access reasoning stepsif reasoning := response.additional_kwargs.get("reasoning_steps"): for step in reasoning: print(f"Thought: {step['thought']}")
from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_perplexity import ChatPerplexity, PerplexitySearchRetrieverllm = ChatPerplexity(model="sonar")retriever = PerplexitySearchRetriever(k=3)template = """Answer based on the following context:{context}Question: {question}"""prompt = ChatPromptTemplate.from_template(template)def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs)rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser())answer = rag_chain.invoke("What is the current status of ITER?")print(answer)