langchain-perplexity 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_perplexity-0.1.0/LICENSE +21 -0
- langchain_perplexity-0.1.0/PKG-INFO +42 -0
- langchain_perplexity-0.1.0/README.md +29 -0
- langchain_perplexity-0.1.0/langchain_perplexity/__init__.py +5 -0
- langchain_perplexity-0.1.0/langchain_perplexity/chat_models.py +504 -0
- langchain_perplexity-0.1.0/langchain_perplexity/py.typed +0 -0
- langchain_perplexity-0.1.0/pyproject.toml +105 -0
- langchain_perplexity-0.1.0/tests/__init__.py +0 -0
- langchain_perplexity-0.1.0/tests/integration_tests/__init__.py +0 -0
- langchain_perplexity-0.1.0/tests/integration_tests/test_chat_models_standard.py +27 -0
- langchain_perplexity-0.1.0/tests/integration_tests/test_compile.py +7 -0
- langchain_perplexity-0.1.0/tests/unit_tests/__init__.py +3 -0
- langchain_perplexity-0.1.0/tests/unit_tests/test_chat_models.py +195 -0
- langchain_perplexity-0.1.0/tests/unit_tests/test_chat_models_standard.py +18 -0
- langchain_perplexity-0.1.0/tests/unit_tests/test_imports.py +7 -0
- langchain_perplexity-0.1.0/tests/unit_tests/test_secrets.py +8 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 LangChain, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: langchain-perplexity
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An integration package connecting Perplexity and LangChain
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Source Code, https://github.com/langchain-ai/langchain/tree/master/libs/partners/perplexity
|
|
7
|
+
Project-URL: Release Notes, https://github.com/langchain-ai/langchain/releases?q=tag%3A%22langchain-perplexity%3D%3D0%22&expanded=true
|
|
8
|
+
Project-URL: repository, https://github.com/langchain-ai/langchain
|
|
9
|
+
Requires-Python: <4.0,>=3.9
|
|
10
|
+
Requires-Dist: langchain-core<1.0.0,>=0.3.50
|
|
11
|
+
Requires-Dist: openai<2.0.0,>=1.68.2
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# langchain-perplexity
|
|
15
|
+
|
|
16
|
+
This package contains the LangChain integration with Perplexity.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install -U langchain-perplexity
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
And you should [configure your perplexity credentials](https://docs.perplexity.ai/guides/getting-started)
|
|
25
|
+
and then set the `PPLX_API_KEY` environment variable.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
This package contains the `ChatPerplexity` class, which is the recommended way to interface with Perplexity chat models.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import getpass
|
|
33
|
+
import os
|
|
34
|
+
|
|
35
|
+
if not os.environ.get("PPLX_API_KEY"):
|
|
36
|
+
os.environ["PPLX_API_KEY"] = getpass.getpass("Enter API key for Perplexity: ")
|
|
37
|
+
|
|
38
|
+
from langchain.chat_models import init_chat_model
|
|
39
|
+
|
|
40
|
+
llm = init_chat_model("llama-3.1-sonar-small-128k-online", model_provider="perplexity")
|
|
41
|
+
llm.invoke("Hello, world!")
|
|
42
|
+
```
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# langchain-perplexity
|
|
2
|
+
|
|
3
|
+
This package contains the LangChain integration with Perplexity.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install -U langchain-perplexity
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
And you should [configure your perplexity credentials](https://docs.perplexity.ai/guides/getting-started)
|
|
12
|
+
and then set the `PPLX_API_KEY` environment variable.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
This package contains the `ChatPerplexity` class, which is the recommended way to interface with Perplexity chat models.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import getpass
|
|
20
|
+
import os
|
|
21
|
+
|
|
22
|
+
if not os.environ.get("PPLX_API_KEY"):
|
|
23
|
+
os.environ["PPLX_API_KEY"] = getpass.getpass("Enter API key for Perplexity: ")
|
|
24
|
+
|
|
25
|
+
from langchain.chat_models import init_chat_model
|
|
26
|
+
|
|
27
|
+
llm = init_chat_model("llama-3.1-sonar-small-128k-online", model_provider="perplexity")
|
|
28
|
+
llm.invoke("Hello, world!")
|
|
29
|
+
```
|
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
"""Wrapper around Perplexity APIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from operator import itemgetter
|
|
7
|
+
from typing import (
|
|
8
|
+
Any,
|
|
9
|
+
Dict,
|
|
10
|
+
Iterator,
|
|
11
|
+
List,
|
|
12
|
+
Literal,
|
|
13
|
+
Mapping,
|
|
14
|
+
Optional,
|
|
15
|
+
Tuple,
|
|
16
|
+
Type,
|
|
17
|
+
TypeVar,
|
|
18
|
+
Union,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
import openai
|
|
22
|
+
from langchain_core.callbacks import CallbackManagerForLLMRun
|
|
23
|
+
from langchain_core.language_models import LanguageModelInput
|
|
24
|
+
from langchain_core.language_models.chat_models import (
|
|
25
|
+
BaseChatModel,
|
|
26
|
+
generate_from_stream,
|
|
27
|
+
)
|
|
28
|
+
from langchain_core.messages import (
|
|
29
|
+
AIMessage,
|
|
30
|
+
AIMessageChunk,
|
|
31
|
+
BaseMessage,
|
|
32
|
+
BaseMessageChunk,
|
|
33
|
+
ChatMessage,
|
|
34
|
+
ChatMessageChunk,
|
|
35
|
+
FunctionMessageChunk,
|
|
36
|
+
HumanMessage,
|
|
37
|
+
HumanMessageChunk,
|
|
38
|
+
SystemMessage,
|
|
39
|
+
SystemMessageChunk,
|
|
40
|
+
ToolMessageChunk,
|
|
41
|
+
)
|
|
42
|
+
from langchain_core.messages.ai import UsageMetadata, subtract_usage
|
|
43
|
+
from langchain_core.output_parsers import JsonOutputParser, PydanticOutputParser
|
|
44
|
+
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
|
|
45
|
+
from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
|
|
46
|
+
from langchain_core.utils import get_pydantic_field_names, secret_from_env
|
|
47
|
+
from langchain_core.utils.function_calling import convert_to_json_schema
|
|
48
|
+
from langchain_core.utils.pydantic import is_basemodel_subclass
|
|
49
|
+
from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
|
|
50
|
+
from typing_extensions import Self
|
|
51
|
+
|
|
52
|
+
_BM = TypeVar("_BM", bound=BaseModel)
|
|
53
|
+
_DictOrPydanticClass = Union[Dict[str, Any], Type[_BM], Type]
|
|
54
|
+
_DictOrPydantic = Union[Dict, _BM]
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _is_pydantic_class(obj: Any) -> bool:
|
|
60
|
+
return isinstance(obj, type) and is_basemodel_subclass(obj)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _create_usage_metadata(token_usage: dict) -> UsageMetadata:
|
|
64
|
+
input_tokens = token_usage.get("prompt_tokens", 0)
|
|
65
|
+
output_tokens = token_usage.get("completion_tokens", 0)
|
|
66
|
+
total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
|
|
67
|
+
return UsageMetadata(
|
|
68
|
+
input_tokens=input_tokens,
|
|
69
|
+
output_tokens=output_tokens,
|
|
70
|
+
total_tokens=total_tokens,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ChatPerplexity(BaseChatModel):
|
|
75
|
+
"""`Perplexity AI` Chat models API.
|
|
76
|
+
|
|
77
|
+
Setup:
|
|
78
|
+
To use, you should have the ``openai`` python package installed, and the
|
|
79
|
+
environment variable ``PPLX_API_KEY`` set to your API key.
|
|
80
|
+
Any parameters that are valid to be passed to the openai.create call
|
|
81
|
+
can be passed in, even if not explicitly saved on this class.
|
|
82
|
+
|
|
83
|
+
.. code-block:: bash
|
|
84
|
+
|
|
85
|
+
pip install openai
|
|
86
|
+
export PPLX_API_KEY=your_api_key
|
|
87
|
+
|
|
88
|
+
Key init args - completion params:
|
|
89
|
+
model: str
|
|
90
|
+
Name of the model to use. e.g. "llama-3.1-sonar-small-128k-online"
|
|
91
|
+
temperature: float
|
|
92
|
+
Sampling temperature to use. Default is 0.7
|
|
93
|
+
max_tokens: Optional[int]
|
|
94
|
+
Maximum number of tokens to generate.
|
|
95
|
+
streaming: bool
|
|
96
|
+
Whether to stream the results or not.
|
|
97
|
+
|
|
98
|
+
Key init args - client params:
|
|
99
|
+
pplx_api_key: Optional[str]
|
|
100
|
+
API key for PerplexityChat API. Default is None.
|
|
101
|
+
request_timeout: Optional[Union[float, Tuple[float, float]]]
|
|
102
|
+
Timeout for requests to PerplexityChat completion API. Default is None.
|
|
103
|
+
max_retries: int
|
|
104
|
+
Maximum number of retries to make when generating.
|
|
105
|
+
|
|
106
|
+
See full list of supported init args and their descriptions in the params section.
|
|
107
|
+
|
|
108
|
+
Instantiate:
|
|
109
|
+
.. code-block:: python
|
|
110
|
+
|
|
111
|
+
from langchain_community.chat_models import ChatPerplexity
|
|
112
|
+
|
|
113
|
+
llm = ChatPerplexity(
|
|
114
|
+
model="llama-3.1-sonar-small-128k-online", temperature=0.7
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
Invoke:
|
|
118
|
+
.. code-block:: python
|
|
119
|
+
|
|
120
|
+
messages = [("system", "You are a chatbot."), ("user", "Hello!")]
|
|
121
|
+
llm.invoke(messages)
|
|
122
|
+
|
|
123
|
+
Invoke with structured output:
|
|
124
|
+
.. code-block:: python
|
|
125
|
+
|
|
126
|
+
from pydantic import BaseModel
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class StructuredOutput(BaseModel):
|
|
130
|
+
role: str
|
|
131
|
+
content: str
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
llm.with_structured_output(StructuredOutput)
|
|
135
|
+
llm.invoke(messages)
|
|
136
|
+
|
|
137
|
+
Invoke with perplexity-specific params:
|
|
138
|
+
.. code-block:: python
|
|
139
|
+
|
|
140
|
+
llm.invoke(messages, extra_body={"search_recency_filter": "week"})
|
|
141
|
+
|
|
142
|
+
Stream:
|
|
143
|
+
.. code-block:: python
|
|
144
|
+
|
|
145
|
+
for chunk in llm.stream(messages):
|
|
146
|
+
print(chunk.content)
|
|
147
|
+
|
|
148
|
+
Token usage:
|
|
149
|
+
.. code-block:: python
|
|
150
|
+
|
|
151
|
+
response = llm.invoke(messages)
|
|
152
|
+
response.usage_metadata
|
|
153
|
+
|
|
154
|
+
Response metadata:
|
|
155
|
+
.. code-block:: python
|
|
156
|
+
|
|
157
|
+
response = llm.invoke(messages)
|
|
158
|
+
response.response_metadata
|
|
159
|
+
|
|
160
|
+
""" # noqa: E501
|
|
161
|
+
|
|
162
|
+
client: Any = None #: :meta private:
|
|
163
|
+
model: str = "llama-3.1-sonar-small-128k-online"
|
|
164
|
+
"""Model name."""
|
|
165
|
+
temperature: float = 0.7
|
|
166
|
+
"""What sampling temperature to use."""
|
|
167
|
+
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
|
|
168
|
+
"""Holds any model parameters valid for `create` call not explicitly specified."""
|
|
169
|
+
pplx_api_key: Optional[SecretStr] = Field(
|
|
170
|
+
default_factory=secret_from_env("PPLX_API_KEY", default=None), alias="api_key"
|
|
171
|
+
)
|
|
172
|
+
"""Base URL path for API requests,
|
|
173
|
+
leave blank if not using a proxy or service emulator."""
|
|
174
|
+
request_timeout: Optional[Union[float, Tuple[float, float]]] = Field(
|
|
175
|
+
None, alias="timeout"
|
|
176
|
+
)
|
|
177
|
+
"""Timeout for requests to PerplexityChat completion API. Default is None."""
|
|
178
|
+
max_retries: int = 6
|
|
179
|
+
"""Maximum number of retries to make when generating."""
|
|
180
|
+
streaming: bool = False
|
|
181
|
+
"""Whether to stream the results or not."""
|
|
182
|
+
max_tokens: Optional[int] = None
|
|
183
|
+
"""Maximum number of tokens to generate."""
|
|
184
|
+
|
|
185
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def lc_secrets(self) -> Dict[str, str]:
|
|
189
|
+
return {"pplx_api_key": "PPLX_API_KEY"}
|
|
190
|
+
|
|
191
|
+
@model_validator(mode="before")
|
|
192
|
+
@classmethod
|
|
193
|
+
def build_extra(cls, values: Dict[str, Any]) -> Any:
|
|
194
|
+
"""Build extra kwargs from additional params that were passed in."""
|
|
195
|
+
all_required_field_names = get_pydantic_field_names(cls)
|
|
196
|
+
extra = values.get("model_kwargs", {})
|
|
197
|
+
for field_name in list(values):
|
|
198
|
+
if field_name in extra:
|
|
199
|
+
raise ValueError(f"Found {field_name} supplied twice.")
|
|
200
|
+
if field_name not in all_required_field_names:
|
|
201
|
+
logger.warning(
|
|
202
|
+
f"""WARNING! {field_name} is not a default parameter.
|
|
203
|
+
{field_name} was transferred to model_kwargs.
|
|
204
|
+
Please confirm that {field_name} is what you intended."""
|
|
205
|
+
)
|
|
206
|
+
extra[field_name] = values.pop(field_name)
|
|
207
|
+
|
|
208
|
+
invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
|
|
209
|
+
if invalid_model_kwargs:
|
|
210
|
+
raise ValueError(
|
|
211
|
+
f"Parameters {invalid_model_kwargs} should be specified explicitly. "
|
|
212
|
+
f"Instead they were passed in as part of `model_kwargs` parameter."
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
values["model_kwargs"] = extra
|
|
216
|
+
return values
|
|
217
|
+
|
|
218
|
+
@model_validator(mode="after")
|
|
219
|
+
def validate_environment(self) -> Self:
|
|
220
|
+
"""Validate that api key and python package exists in environment."""
|
|
221
|
+
try:
|
|
222
|
+
self.client = openai.OpenAI(
|
|
223
|
+
api_key=self.pplx_api_key.get_secret_value()
|
|
224
|
+
if self.pplx_api_key
|
|
225
|
+
else None,
|
|
226
|
+
base_url="https://api.perplexity.ai",
|
|
227
|
+
)
|
|
228
|
+
except AttributeError:
|
|
229
|
+
raise ValueError(
|
|
230
|
+
"`openai` has no `ChatCompletion` attribute, this is likely "
|
|
231
|
+
"due to an old version of the openai package. Try upgrading it "
|
|
232
|
+
"with `pip install --upgrade openai`."
|
|
233
|
+
)
|
|
234
|
+
return self
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def _default_params(self) -> Dict[str, Any]:
|
|
238
|
+
"""Get the default parameters for calling PerplexityChat API."""
|
|
239
|
+
return {
|
|
240
|
+
"max_tokens": self.max_tokens,
|
|
241
|
+
"stream": self.streaming,
|
|
242
|
+
"temperature": self.temperature,
|
|
243
|
+
**self.model_kwargs,
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
def _convert_message_to_dict(self, message: BaseMessage) -> Dict[str, Any]:
|
|
247
|
+
if isinstance(message, ChatMessage):
|
|
248
|
+
message_dict = {"role": message.role, "content": message.content}
|
|
249
|
+
elif isinstance(message, SystemMessage):
|
|
250
|
+
message_dict = {"role": "system", "content": message.content}
|
|
251
|
+
elif isinstance(message, HumanMessage):
|
|
252
|
+
message_dict = {"role": "user", "content": message.content}
|
|
253
|
+
elif isinstance(message, AIMessage):
|
|
254
|
+
message_dict = {"role": "assistant", "content": message.content}
|
|
255
|
+
else:
|
|
256
|
+
raise TypeError(f"Got unknown type {message}")
|
|
257
|
+
return message_dict
|
|
258
|
+
|
|
259
|
+
def _create_message_dicts(
|
|
260
|
+
self, messages: List[BaseMessage], stop: Optional[List[str]]
|
|
261
|
+
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
|
|
262
|
+
params = dict(self._invocation_params)
|
|
263
|
+
if stop is not None:
|
|
264
|
+
if "stop" in params:
|
|
265
|
+
raise ValueError("`stop` found in both the input and default params.")
|
|
266
|
+
params["stop"] = stop
|
|
267
|
+
message_dicts = [self._convert_message_to_dict(m) for m in messages]
|
|
268
|
+
return message_dicts, params
|
|
269
|
+
|
|
270
|
+
def _convert_delta_to_message_chunk(
|
|
271
|
+
self, _dict: Mapping[str, Any], default_class: Type[BaseMessageChunk]
|
|
272
|
+
) -> BaseMessageChunk:
|
|
273
|
+
role = _dict.get("role")
|
|
274
|
+
content = _dict.get("content") or ""
|
|
275
|
+
additional_kwargs: Dict = {}
|
|
276
|
+
if _dict.get("function_call"):
|
|
277
|
+
function_call = dict(_dict["function_call"])
|
|
278
|
+
if "name" in function_call and function_call["name"] is None:
|
|
279
|
+
function_call["name"] = ""
|
|
280
|
+
additional_kwargs["function_call"] = function_call
|
|
281
|
+
if _dict.get("tool_calls"):
|
|
282
|
+
additional_kwargs["tool_calls"] = _dict["tool_calls"]
|
|
283
|
+
|
|
284
|
+
if role == "user" or default_class == HumanMessageChunk:
|
|
285
|
+
return HumanMessageChunk(content=content)
|
|
286
|
+
elif role == "assistant" or default_class == AIMessageChunk:
|
|
287
|
+
return AIMessageChunk(content=content, additional_kwargs=additional_kwargs)
|
|
288
|
+
elif role == "system" or default_class == SystemMessageChunk:
|
|
289
|
+
return SystemMessageChunk(content=content)
|
|
290
|
+
elif role == "function" or default_class == FunctionMessageChunk:
|
|
291
|
+
return FunctionMessageChunk(content=content, name=_dict["name"])
|
|
292
|
+
elif role == "tool" or default_class == ToolMessageChunk:
|
|
293
|
+
return ToolMessageChunk(content=content, tool_call_id=_dict["tool_call_id"])
|
|
294
|
+
elif role or default_class == ChatMessageChunk:
|
|
295
|
+
return ChatMessageChunk(content=content, role=role) # type: ignore[arg-type]
|
|
296
|
+
else:
|
|
297
|
+
return default_class(content=content) # type: ignore[call-arg]
|
|
298
|
+
|
|
299
|
+
def _stream(
|
|
300
|
+
self,
|
|
301
|
+
messages: List[BaseMessage],
|
|
302
|
+
stop: Optional[List[str]] = None,
|
|
303
|
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
|
304
|
+
**kwargs: Any,
|
|
305
|
+
) -> Iterator[ChatGenerationChunk]:
|
|
306
|
+
message_dicts, params = self._create_message_dicts(messages, stop)
|
|
307
|
+
params = {**params, **kwargs}
|
|
308
|
+
default_chunk_class = AIMessageChunk
|
|
309
|
+
params.pop("stream", None)
|
|
310
|
+
if stop:
|
|
311
|
+
params["stop_sequences"] = stop
|
|
312
|
+
stream_resp = self.client.chat.completions.create(
|
|
313
|
+
messages=message_dicts, stream=True, **params
|
|
314
|
+
)
|
|
315
|
+
first_chunk = True
|
|
316
|
+
prev_total_usage: Optional[UsageMetadata] = None
|
|
317
|
+
|
|
318
|
+
added_model_name: bool = False
|
|
319
|
+
for chunk in stream_resp:
|
|
320
|
+
if not isinstance(chunk, dict):
|
|
321
|
+
chunk = chunk.model_dump()
|
|
322
|
+
# Collect standard usage metadata (transform from aggregate to delta)
|
|
323
|
+
if total_usage := chunk.get("usage"):
|
|
324
|
+
lc_total_usage = _create_usage_metadata(total_usage)
|
|
325
|
+
if prev_total_usage:
|
|
326
|
+
usage_metadata: Optional[UsageMetadata] = subtract_usage(
|
|
327
|
+
lc_total_usage, prev_total_usage
|
|
328
|
+
)
|
|
329
|
+
else:
|
|
330
|
+
usage_metadata = lc_total_usage
|
|
331
|
+
prev_total_usage = lc_total_usage
|
|
332
|
+
else:
|
|
333
|
+
usage_metadata = None
|
|
334
|
+
if len(chunk["choices"]) == 0:
|
|
335
|
+
continue
|
|
336
|
+
choice = chunk["choices"][0]
|
|
337
|
+
|
|
338
|
+
additional_kwargs = {}
|
|
339
|
+
if first_chunk:
|
|
340
|
+
additional_kwargs["citations"] = chunk.get("citations", [])
|
|
341
|
+
for attr in ["images", "related_questions"]:
|
|
342
|
+
if attr in chunk:
|
|
343
|
+
additional_kwargs[attr] = chunk[attr]
|
|
344
|
+
|
|
345
|
+
generation_info = {}
|
|
346
|
+
if (model_name := chunk.get("model")) and not added_model_name:
|
|
347
|
+
generation_info["model_name"] = model_name
|
|
348
|
+
added_model_name = True
|
|
349
|
+
|
|
350
|
+
chunk = self._convert_delta_to_message_chunk(
|
|
351
|
+
choice["delta"], default_chunk_class
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
if isinstance(chunk, AIMessageChunk) and usage_metadata:
|
|
355
|
+
chunk.usage_metadata = usage_metadata
|
|
356
|
+
|
|
357
|
+
if first_chunk:
|
|
358
|
+
chunk.additional_kwargs |= additional_kwargs
|
|
359
|
+
first_chunk = False
|
|
360
|
+
|
|
361
|
+
if finish_reason := choice.get("finish_reason"):
|
|
362
|
+
generation_info["finish_reason"] = finish_reason
|
|
363
|
+
|
|
364
|
+
default_chunk_class = chunk.__class__
|
|
365
|
+
chunk = ChatGenerationChunk(message=chunk, generation_info=generation_info)
|
|
366
|
+
if run_manager:
|
|
367
|
+
run_manager.on_llm_new_token(chunk.text, chunk=chunk)
|
|
368
|
+
yield chunk
|
|
369
|
+
|
|
370
|
+
def _generate(
|
|
371
|
+
self,
|
|
372
|
+
messages: List[BaseMessage],
|
|
373
|
+
stop: Optional[List[str]] = None,
|
|
374
|
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
|
375
|
+
**kwargs: Any,
|
|
376
|
+
) -> ChatResult:
|
|
377
|
+
if self.streaming:
|
|
378
|
+
stream_iter = self._stream(
|
|
379
|
+
messages, stop=stop, run_manager=run_manager, **kwargs
|
|
380
|
+
)
|
|
381
|
+
if stream_iter:
|
|
382
|
+
return generate_from_stream(stream_iter)
|
|
383
|
+
message_dicts, params = self._create_message_dicts(messages, stop)
|
|
384
|
+
params = {**params, **kwargs}
|
|
385
|
+
response = self.client.chat.completions.create(messages=message_dicts, **params)
|
|
386
|
+
if usage := getattr(response, "usage", None):
|
|
387
|
+
usage_metadata = _create_usage_metadata(usage.model_dump())
|
|
388
|
+
else:
|
|
389
|
+
usage_metadata = None
|
|
390
|
+
|
|
391
|
+
additional_kwargs = {"citations": response.citations}
|
|
392
|
+
for attr in ["images", "related_questions"]:
|
|
393
|
+
if hasattr(response, attr):
|
|
394
|
+
additional_kwargs[attr] = getattr(response, attr)
|
|
395
|
+
|
|
396
|
+
message = AIMessage(
|
|
397
|
+
content=response.choices[0].message.content,
|
|
398
|
+
additional_kwargs=additional_kwargs,
|
|
399
|
+
usage_metadata=usage_metadata,
|
|
400
|
+
response_metadata={"model_name": getattr(response, "model", self.model)},
|
|
401
|
+
)
|
|
402
|
+
return ChatResult(generations=[ChatGeneration(message=message)])
|
|
403
|
+
|
|
404
|
+
@property
|
|
405
|
+
def _invocation_params(self) -> Mapping[str, Any]:
|
|
406
|
+
"""Get the parameters used to invoke the model."""
|
|
407
|
+
pplx_creds: Dict[str, Any] = {"model": self.model}
|
|
408
|
+
return {**pplx_creds, **self._default_params}
|
|
409
|
+
|
|
410
|
+
@property
|
|
411
|
+
def _llm_type(self) -> str:
|
|
412
|
+
"""Return type of chat model."""
|
|
413
|
+
return "perplexitychat"
|
|
414
|
+
|
|
415
|
+
def with_structured_output(
|
|
416
|
+
self,
|
|
417
|
+
schema: Optional[_DictOrPydanticClass] = None,
|
|
418
|
+
*,
|
|
419
|
+
method: Literal["json_schema"] = "json_schema",
|
|
420
|
+
include_raw: bool = False,
|
|
421
|
+
strict: Optional[bool] = None,
|
|
422
|
+
**kwargs: Any,
|
|
423
|
+
) -> Runnable[LanguageModelInput, _DictOrPydantic]:
|
|
424
|
+
"""Model wrapper that returns outputs formatted to match the given schema for Preplexity.
|
|
425
|
+
Currently, Preplexity only supports "json_schema" method for structured output
|
|
426
|
+
as per their official documentation: https://docs.perplexity.ai/guides/structured-outputs
|
|
427
|
+
|
|
428
|
+
Args:
|
|
429
|
+
schema:
|
|
430
|
+
The output schema. Can be passed in as:
|
|
431
|
+
|
|
432
|
+
- a JSON Schema,
|
|
433
|
+
- a TypedDict class,
|
|
434
|
+
- or a Pydantic class
|
|
435
|
+
|
|
436
|
+
method: The method for steering model generation, currently only support:
|
|
437
|
+
|
|
438
|
+
- "json_schema": Use the JSON Schema to parse the model output
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
include_raw:
|
|
442
|
+
If False then only the parsed structured output is returned. If
|
|
443
|
+
an error occurs during model output parsing it will be raised. If True
|
|
444
|
+
then both the raw model response (a BaseMessage) and the parsed model
|
|
445
|
+
response will be returned. If an error occurs during output parsing it
|
|
446
|
+
will be caught and returned as well. The final output is always a dict
|
|
447
|
+
with keys "raw", "parsed", and "parsing_error".
|
|
448
|
+
|
|
449
|
+
kwargs: Additional keyword args aren't supported.
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
A Runnable that takes same inputs as a :class:`langchain_core.language_models.chat.BaseChatModel`.
|
|
453
|
+
|
|
454
|
+
| If ``include_raw`` is False and ``schema`` is a Pydantic class, Runnable outputs an instance of ``schema`` (i.e., a Pydantic object). Otherwise, if ``include_raw`` is False then Runnable outputs a dict.
|
|
455
|
+
|
|
456
|
+
| If ``include_raw`` is True, then Runnable outputs a dict with keys:
|
|
457
|
+
|
|
458
|
+
- "raw": BaseMessage
|
|
459
|
+
- "parsed": None if there was a parsing error, otherwise the type depends on the ``schema`` as described above.
|
|
460
|
+
- "parsing_error": Optional[BaseException]
|
|
461
|
+
|
|
462
|
+
""" # noqa: E501
|
|
463
|
+
if method in ("function_calling", "json_mode"):
|
|
464
|
+
method = "json_schema"
|
|
465
|
+
if method == "json_schema":
|
|
466
|
+
if schema is None:
|
|
467
|
+
raise ValueError(
|
|
468
|
+
"schema must be specified when method is not 'json_schema'. "
|
|
469
|
+
"Received None."
|
|
470
|
+
)
|
|
471
|
+
is_pydantic_schema = _is_pydantic_class(schema)
|
|
472
|
+
response_format = convert_to_json_schema(schema)
|
|
473
|
+
llm = self.bind(
|
|
474
|
+
response_format={
|
|
475
|
+
"type": "json_schema",
|
|
476
|
+
"json_schema": {"schema": response_format},
|
|
477
|
+
},
|
|
478
|
+
ls_structured_output_format={
|
|
479
|
+
"kwargs": {"method": method},
|
|
480
|
+
"schema": response_format,
|
|
481
|
+
},
|
|
482
|
+
)
|
|
483
|
+
output_parser = (
|
|
484
|
+
PydanticOutputParser(pydantic_object=schema) # type: ignore[arg-type]
|
|
485
|
+
if is_pydantic_schema
|
|
486
|
+
else JsonOutputParser()
|
|
487
|
+
)
|
|
488
|
+
else:
|
|
489
|
+
raise ValueError(
|
|
490
|
+
f"Unrecognized method argument. Expected 'json_schema' Received:\
|
|
491
|
+
'{method}'"
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
if include_raw:
|
|
495
|
+
parser_assign = RunnablePassthrough.assign(
|
|
496
|
+
parsed=itemgetter("raw") | output_parser, parsing_error=lambda _: None
|
|
497
|
+
)
|
|
498
|
+
parser_none = RunnablePassthrough.assign(parsed=lambda _: None)
|
|
499
|
+
parser_with_fallback = parser_assign.with_fallbacks(
|
|
500
|
+
[parser_none], exception_key="parsing_error"
|
|
501
|
+
)
|
|
502
|
+
return RunnableMap(raw=llm) | parser_with_fallback
|
|
503
|
+
else:
|
|
504
|
+
return llm | output_parser
|
|
File without changes
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = [
|
|
3
|
+
"pdm-backend",
|
|
4
|
+
]
|
|
5
|
+
build-backend = "pdm.backend"
|
|
6
|
+
|
|
7
|
+
[project]
|
|
8
|
+
authors = []
|
|
9
|
+
requires-python = "<4.0,>=3.9"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"langchain-core<1.0.0,>=0.3.50",
|
|
12
|
+
"openai<2.0.0,>=1.68.2",
|
|
13
|
+
]
|
|
14
|
+
name = "langchain-perplexity"
|
|
15
|
+
version = "0.1.0"
|
|
16
|
+
description = "An integration package connecting Perplexity and LangChain"
|
|
17
|
+
readme = "README.md"
|
|
18
|
+
|
|
19
|
+
[project.license]
|
|
20
|
+
text = "MIT"
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
"Source Code" = "https://github.com/langchain-ai/langchain/tree/master/libs/partners/perplexity"
|
|
24
|
+
"Release Notes" = "https://github.com/langchain-ai/langchain/releases?q=tag%3A%22langchain-perplexity%3D%3D0%22&expanded=true"
|
|
25
|
+
repository = "https://github.com/langchain-ai/langchain"
|
|
26
|
+
|
|
27
|
+
[dependency-groups]
|
|
28
|
+
test = [
|
|
29
|
+
"pytest<8.0.0,>=7.3.0",
|
|
30
|
+
"freezegun<2.0.0,>=1.2.2",
|
|
31
|
+
"pytest-mock<4.0.0,>=3.10.0",
|
|
32
|
+
"syrupy<5.0.0,>=4.0.2",
|
|
33
|
+
"pytest-watcher<1.0.0,>=0.3.4",
|
|
34
|
+
"pytest-asyncio<1.0.0,>=0.21.1",
|
|
35
|
+
"pytest-cov<5.0.0,>=4.1.0",
|
|
36
|
+
"pytest-retry<1.8.0,>=1.7.0",
|
|
37
|
+
"pytest-socket<1.0.0,>=0.6.0",
|
|
38
|
+
"pytest-xdist<4.0.0,>=3.6.1",
|
|
39
|
+
"langchain-core",
|
|
40
|
+
"langchain-tests",
|
|
41
|
+
]
|
|
42
|
+
codespell = [
|
|
43
|
+
"codespell<3.0.0,>=2.2.0",
|
|
44
|
+
]
|
|
45
|
+
lint = [
|
|
46
|
+
"ruff<1.0,>=0.5",
|
|
47
|
+
]
|
|
48
|
+
dev = [
|
|
49
|
+
"langchain-core",
|
|
50
|
+
]
|
|
51
|
+
test_integration = [
|
|
52
|
+
"httpx<1.0.0,>=0.27.0",
|
|
53
|
+
"pillow<11.0.0,>=10.3.0",
|
|
54
|
+
]
|
|
55
|
+
typing = [
|
|
56
|
+
"mypy<2.0,>=1.10",
|
|
57
|
+
"types-tqdm<5.0.0.0,>=4.66.0.5",
|
|
58
|
+
"langchain-core",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.uv.sources.langchain-core]
|
|
62
|
+
path = "../../core"
|
|
63
|
+
editable = true
|
|
64
|
+
|
|
65
|
+
[tool.uv.sources.langchain-tests]
|
|
66
|
+
path = "../../standard-tests"
|
|
67
|
+
editable = true
|
|
68
|
+
|
|
69
|
+
[tool.mypy]
|
|
70
|
+
disallow_untyped_defs = "True"
|
|
71
|
+
plugins = [
|
|
72
|
+
"pydantic.mypy",
|
|
73
|
+
]
|
|
74
|
+
overrides = [
|
|
75
|
+
{ module = "transformers", ignore_missing_imports = true },
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
[tool.ruff.lint]
|
|
79
|
+
select = [
|
|
80
|
+
"E",
|
|
81
|
+
"F",
|
|
82
|
+
"I",
|
|
83
|
+
"T201",
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
[tool.ruff.format]
|
|
87
|
+
docstring-code-format = true
|
|
88
|
+
skip-magic-trailing-comma = true
|
|
89
|
+
|
|
90
|
+
[tool.coverage.run]
|
|
91
|
+
omit = [
|
|
92
|
+
"tests/*",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
[tool.pytest.ini_options]
|
|
96
|
+
addopts = "--snapshot-warn-unused --strict-markers --strict-config --durations=5 --cov=langchain_perplexity"
|
|
97
|
+
markers = [
|
|
98
|
+
"requires: mark tests as requiring a specific library",
|
|
99
|
+
"compile: mark placeholder test used to compile integration tests without running them",
|
|
100
|
+
"scheduled: mark tests to run in scheduled testing",
|
|
101
|
+
]
|
|
102
|
+
asyncio_mode = "auto"
|
|
103
|
+
filterwarnings = [
|
|
104
|
+
"ignore::langchain_core._api.beta_decorator.LangChainBetaWarning",
|
|
105
|
+
]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Standard LangChain interface tests."""
|
|
2
|
+
|
|
3
|
+
from typing import Type
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from langchain_core.language_models import BaseChatModel
|
|
7
|
+
from langchain_tests.integration_tests import ChatModelIntegrationTests
|
|
8
|
+
|
|
9
|
+
from langchain_perplexity import ChatPerplexity
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TestPerplexityStandard(ChatModelIntegrationTests):
|
|
13
|
+
@property
|
|
14
|
+
def chat_model_class(self) -> Type[BaseChatModel]:
|
|
15
|
+
return ChatPerplexity
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def chat_model_params(self) -> dict:
|
|
19
|
+
return {"model": "sonar"}
|
|
20
|
+
|
|
21
|
+
@pytest.mark.xfail(reason="TODO: handle in integration.")
|
|
22
|
+
def test_double_messages_conversation(self, model: BaseChatModel) -> None:
|
|
23
|
+
super().test_double_messages_conversation(model)
|
|
24
|
+
|
|
25
|
+
@pytest.mark.xfail(reason="Raises 400: Custom stop words not supported.")
|
|
26
|
+
def test_stop_sequence(self, model: BaseChatModel) -> None:
|
|
27
|
+
super().test_stop_sequence(model)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
from typing import Any, Dict, List, Optional
|
|
2
|
+
from unittest.mock import MagicMock
|
|
3
|
+
|
|
4
|
+
from langchain_core.messages import AIMessageChunk, BaseMessageChunk
|
|
5
|
+
from pytest_mock import MockerFixture
|
|
6
|
+
|
|
7
|
+
from langchain_perplexity import ChatPerplexity
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_perplexity_model_name_param() -> None:
|
|
11
|
+
llm = ChatPerplexity(model="foo")
|
|
12
|
+
assert llm.model == "foo"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_perplexity_model_kwargs() -> None:
|
|
16
|
+
llm = ChatPerplexity(model="test", model_kwargs={"foo": "bar"})
|
|
17
|
+
assert llm.model_kwargs == {"foo": "bar"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_perplexity_initialization() -> None:
|
|
21
|
+
"""Test perplexity initialization."""
|
|
22
|
+
# Verify that chat perplexity can be initialized using a secret key provided
|
|
23
|
+
# as a parameter rather than an environment variable.
|
|
24
|
+
for model in [
|
|
25
|
+
ChatPerplexity(
|
|
26
|
+
model="test", timeout=1, api_key="test", temperature=0.7, verbose=True
|
|
27
|
+
),
|
|
28
|
+
ChatPerplexity(
|
|
29
|
+
model="test",
|
|
30
|
+
request_timeout=1,
|
|
31
|
+
pplx_api_key="test",
|
|
32
|
+
temperature=0.7,
|
|
33
|
+
verbose=True,
|
|
34
|
+
),
|
|
35
|
+
]:
|
|
36
|
+
assert model.request_timeout == 1
|
|
37
|
+
assert (
|
|
38
|
+
model.pplx_api_key is not None
|
|
39
|
+
and model.pplx_api_key.get_secret_value() == "test"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_perplexity_stream_includes_citations(mocker: MockerFixture) -> None:
|
|
44
|
+
"""Test that the stream method includes citations in the additional_kwargs."""
|
|
45
|
+
llm = ChatPerplexity(model="test", timeout=30, verbose=True)
|
|
46
|
+
mock_chunk_0 = {
|
|
47
|
+
"choices": [{"delta": {"content": "Hello "}, "finish_reason": None}],
|
|
48
|
+
"citations": ["example.com", "example2.com"],
|
|
49
|
+
}
|
|
50
|
+
mock_chunk_1 = {
|
|
51
|
+
"choices": [{"delta": {"content": "Perplexity"}, "finish_reason": None}],
|
|
52
|
+
"citations": ["example.com", "example2.com"],
|
|
53
|
+
}
|
|
54
|
+
mock_chunks: List[Dict[str, Any]] = [mock_chunk_0, mock_chunk_1]
|
|
55
|
+
mock_stream = MagicMock()
|
|
56
|
+
mock_stream.__iter__.return_value = mock_chunks
|
|
57
|
+
patcher = mocker.patch.object(
|
|
58
|
+
llm.client.chat.completions, "create", return_value=mock_stream
|
|
59
|
+
)
|
|
60
|
+
stream = llm.stream("Hello langchain")
|
|
61
|
+
full: Optional[BaseMessageChunk] = None
|
|
62
|
+
for i, chunk in enumerate(stream):
|
|
63
|
+
full = chunk if full is None else full + chunk
|
|
64
|
+
assert chunk.content == mock_chunks[i]["choices"][0]["delta"]["content"]
|
|
65
|
+
if i == 0:
|
|
66
|
+
assert chunk.additional_kwargs["citations"] == [
|
|
67
|
+
"example.com",
|
|
68
|
+
"example2.com",
|
|
69
|
+
]
|
|
70
|
+
else:
|
|
71
|
+
assert "citations" not in chunk.additional_kwargs
|
|
72
|
+
assert isinstance(full, AIMessageChunk)
|
|
73
|
+
assert full.content == "Hello Perplexity"
|
|
74
|
+
assert full.additional_kwargs == {"citations": ["example.com", "example2.com"]}
|
|
75
|
+
|
|
76
|
+
patcher.assert_called_once()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_perplexity_stream_includes_citations_and_images(mocker: MockerFixture) -> None:
|
|
80
|
+
"""Test that the stream method includes citations in the additional_kwargs."""
|
|
81
|
+
llm = ChatPerplexity(model="test", timeout=30, verbose=True)
|
|
82
|
+
mock_chunk_0 = {
|
|
83
|
+
"choices": [{"delta": {"content": "Hello "}, "finish_reason": None}],
|
|
84
|
+
"citations": ["example.com", "example2.com"],
|
|
85
|
+
"images": [
|
|
86
|
+
{
|
|
87
|
+
"image_url": "mock_image_url",
|
|
88
|
+
"origin_url": "mock_origin_url",
|
|
89
|
+
"height": 100,
|
|
90
|
+
"width": 100,
|
|
91
|
+
}
|
|
92
|
+
],
|
|
93
|
+
}
|
|
94
|
+
mock_chunk_1 = {
|
|
95
|
+
"choices": [{"delta": {"content": "Perplexity"}, "finish_reason": None}],
|
|
96
|
+
"citations": ["example.com", "example2.com"],
|
|
97
|
+
"images": [
|
|
98
|
+
{
|
|
99
|
+
"image_url": "mock_image_url",
|
|
100
|
+
"origin_url": "mock_origin_url",
|
|
101
|
+
"height": 100,
|
|
102
|
+
"width": 100,
|
|
103
|
+
}
|
|
104
|
+
],
|
|
105
|
+
}
|
|
106
|
+
mock_chunks: List[Dict[str, Any]] = [mock_chunk_0, mock_chunk_1]
|
|
107
|
+
mock_stream = MagicMock()
|
|
108
|
+
mock_stream.__iter__.return_value = mock_chunks
|
|
109
|
+
patcher = mocker.patch.object(
|
|
110
|
+
llm.client.chat.completions, "create", return_value=mock_stream
|
|
111
|
+
)
|
|
112
|
+
stream = llm.stream("Hello langchain")
|
|
113
|
+
full: Optional[BaseMessageChunk] = None
|
|
114
|
+
for i, chunk in enumerate(stream):
|
|
115
|
+
full = chunk if full is None else full + chunk
|
|
116
|
+
assert chunk.content == mock_chunks[i]["choices"][0]["delta"]["content"]
|
|
117
|
+
if i == 0:
|
|
118
|
+
assert chunk.additional_kwargs["citations"] == [
|
|
119
|
+
"example.com",
|
|
120
|
+
"example2.com",
|
|
121
|
+
]
|
|
122
|
+
assert chunk.additional_kwargs["images"] == [
|
|
123
|
+
{
|
|
124
|
+
"image_url": "mock_image_url",
|
|
125
|
+
"origin_url": "mock_origin_url",
|
|
126
|
+
"height": 100,
|
|
127
|
+
"width": 100,
|
|
128
|
+
}
|
|
129
|
+
]
|
|
130
|
+
else:
|
|
131
|
+
assert "citations" not in chunk.additional_kwargs
|
|
132
|
+
assert "images" not in chunk.additional_kwargs
|
|
133
|
+
assert isinstance(full, AIMessageChunk)
|
|
134
|
+
assert full.content == "Hello Perplexity"
|
|
135
|
+
assert full.additional_kwargs == {
|
|
136
|
+
"citations": ["example.com", "example2.com"],
|
|
137
|
+
"images": [
|
|
138
|
+
{
|
|
139
|
+
"image_url": "mock_image_url",
|
|
140
|
+
"origin_url": "mock_origin_url",
|
|
141
|
+
"height": 100,
|
|
142
|
+
"width": 100,
|
|
143
|
+
}
|
|
144
|
+
],
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
patcher.assert_called_once()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_perplexity_stream_includes_citations_and_related_questions(
|
|
151
|
+
mocker: MockerFixture,
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Test that the stream method includes citations in the additional_kwargs."""
|
|
154
|
+
llm = ChatPerplexity(model="test", timeout=30, verbose=True)
|
|
155
|
+
mock_chunk_0 = {
|
|
156
|
+
"choices": [{"delta": {"content": "Hello "}, "finish_reason": None}],
|
|
157
|
+
"citations": ["example.com", "example2.com"],
|
|
158
|
+
"related_questions": ["example_question_1", "example_question_2"],
|
|
159
|
+
}
|
|
160
|
+
mock_chunk_1 = {
|
|
161
|
+
"choices": [{"delta": {"content": "Perplexity"}, "finish_reason": None}],
|
|
162
|
+
"citations": ["example.com", "example2.com"],
|
|
163
|
+
"related_questions": ["example_question_1", "example_question_2"],
|
|
164
|
+
}
|
|
165
|
+
mock_chunks: List[Dict[str, Any]] = [mock_chunk_0, mock_chunk_1]
|
|
166
|
+
mock_stream = MagicMock()
|
|
167
|
+
mock_stream.__iter__.return_value = mock_chunks
|
|
168
|
+
patcher = mocker.patch.object(
|
|
169
|
+
llm.client.chat.completions, "create", return_value=mock_stream
|
|
170
|
+
)
|
|
171
|
+
stream = llm.stream("Hello langchain")
|
|
172
|
+
full: Optional[BaseMessageChunk] = None
|
|
173
|
+
for i, chunk in enumerate(stream):
|
|
174
|
+
full = chunk if full is None else full + chunk
|
|
175
|
+
assert chunk.content == mock_chunks[i]["choices"][0]["delta"]["content"]
|
|
176
|
+
if i == 0:
|
|
177
|
+
assert chunk.additional_kwargs["citations"] == [
|
|
178
|
+
"example.com",
|
|
179
|
+
"example2.com",
|
|
180
|
+
]
|
|
181
|
+
assert chunk.additional_kwargs["related_questions"] == [
|
|
182
|
+
"example_question_1",
|
|
183
|
+
"example_question_2",
|
|
184
|
+
]
|
|
185
|
+
else:
|
|
186
|
+
assert "citations" not in chunk.additional_kwargs
|
|
187
|
+
assert "related_questions" not in chunk.additional_kwargs
|
|
188
|
+
assert isinstance(full, AIMessageChunk)
|
|
189
|
+
assert full.content == "Hello Perplexity"
|
|
190
|
+
assert full.additional_kwargs == {
|
|
191
|
+
"citations": ["example.com", "example2.com"],
|
|
192
|
+
"related_questions": ["example_question_1", "example_question_2"],
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
patcher.assert_called_once()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Test Perplexity Chat API wrapper."""
|
|
2
|
+
|
|
3
|
+
from typing import Tuple, Type
|
|
4
|
+
|
|
5
|
+
from langchain_core.language_models import BaseChatModel
|
|
6
|
+
from langchain_tests.unit_tests import ChatModelUnitTests
|
|
7
|
+
|
|
8
|
+
from langchain_perplexity import ChatPerplexity
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TestPerplexityStandard(ChatModelUnitTests):
|
|
12
|
+
@property
|
|
13
|
+
def chat_model_class(self) -> Type[BaseChatModel]:
|
|
14
|
+
return ChatPerplexity
|
|
15
|
+
|
|
16
|
+
@property
|
|
17
|
+
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
|
|
18
|
+
return ({"PPLX_API_KEY": "api_key"}, {}, {"pplx_api_key": "api_key"})
|