이 페이지는 Perplexity chat models 시작하기를 도와드립니다. 모든 ChatPerplexity 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요.

Overview

Integration details

ClassPackageLocalSerializableJS supportDownloadsVersion
ChatPerplexitylangchain-perplexitybetaPyPI - DownloadsPyPI - Version

Model features

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

Setup

Perplexity 모델에 액세스하려면 Perplexity 계정을 생성하고 API 키를 받은 다음 langchain-perplexity integration package를 설치해야 합니다.

Credentials

이 페이지로 이동하여 Perplexity에 가입하고 API 키를 생성하세요. 완료한 후 PPLX_API_KEY environment variable을 설정하세요:
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 API 키를 설정하세요:
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
제공된 코드는 PPLX_API_KEY가 environment variables에 설정되어 있다고 가정합니다. API 키를 수동으로 지정하고 다른 모델을 선택하려면 다음 코드를 사용할 수 있습니다:
chat = ChatPerplexity(temperature=0, pplx_api_key="YOUR_API_KEY", model="sonar")
사용 가능한 모델 목록은 여기에서 확인할 수 있습니다. 재현성을 위해 이 notebook에서 입력으로 받아 API 키를 동적으로 설정할 수 있습니다.
chat = ChatPerplexity(temperature=0, model="sonar")
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
'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'
일반적으로 하는 것처럼 prompt를 포맷하고 구조화할 수 있습니다. 다음 예제에서는 모델에게 고양이에 관한 농담을 해달라고 요청합니다.
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
'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 전용 parameter 사용하기

ChatPerplexity class를 통해 Perplexity 전용 parameter를 사용할 수도 있습니다. 예를 들어, 아래와 같이 extra_body parameter를 사용하여 search_domain_filter, return_images, return_related_questions 또는 search_recency_filter와 같은 parameter를 사용할 수 있습니다:
chat = ChatPerplexity(temperature=0.7, model="sonar")
response = chat.invoke(
    "Tell me a joke about cats", extra_body={"search_recency_filter": "week"}
)
response.content
"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]"

검색 결과 metadata 액세스하기

Perplexity는 종종 참조한 웹 페이지 목록(“search_results”)을 제공합니다. 특별한 parameter를 전달할 필요가 없으며, 목록은 response.additional_kwargs["search_results"]에 배치됩니다.
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]
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.
[{'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는 streaming 기능도 지원합니다

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)
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는 Tier 3+ 사용자를 위한 Structured Outputs를 지원합니다

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
AnswerFormat(first_name='Michael', last_name='Jordan', year_of_birth=1963, num_seasons_in_nba=15)
CRITICAL: Provide ONLY the translated MDX content without any additional explanation, comments, or questions. If the content is empty or contains only frontmatter, return it exactly as provided.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I