perplexityai 0.3.0__py3-none-any.whl

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.

Potentially problematic release.


This version of perplexityai might be problematic. Click here for more details.

@@ -0,0 +1,36 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Union, Optional
6
+ from typing_extensions import Literal, Required, TypedDict
7
+
8
+ from .._types import SequenceNotStr
9
+
10
+ __all__ = ["SearchPerformParams"]
11
+
12
+
13
+ class SearchPerformParams(TypedDict, total=False):
14
+ query: Required[Union[str, SequenceNotStr[str]]]
15
+
16
+ country: Optional[str]
17
+
18
+ last_updated_after_filter: Optional[str]
19
+
20
+ last_updated_before_filter: Optional[str]
21
+
22
+ max_results: int
23
+
24
+ max_tokens: int
25
+
26
+ safe_search: Optional[bool]
27
+
28
+ search_after_date_filter: Optional[str]
29
+
30
+ search_before_date_filter: Optional[str]
31
+
32
+ search_domain_filter: Optional[SequenceNotStr[str]]
33
+
34
+ search_mode: Optional[Literal["web", "academic", "sec"]]
35
+
36
+ search_recency_filter: Optional[Literal["hour", "day", "week", "month", "year"]]
@@ -0,0 +1,25 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing import List, Optional
4
+
5
+ from .._models import BaseModel
6
+
7
+ __all__ = ["SearchPerformResponse", "Result"]
8
+
9
+
10
+ class Result(BaseModel):
11
+ snippet: str
12
+
13
+ title: str
14
+
15
+ url: str
16
+
17
+ date: Optional[str] = None
18
+
19
+ last_updated: Optional[str] = None
20
+
21
+
22
+ class SearchPerformResponse(BaseModel):
23
+ id: str
24
+
25
+ results: List[Result]
@@ -0,0 +1,414 @@
1
+ Metadata-Version: 2.3
2
+ Name: perplexityai
3
+ Version: 0.3.0
4
+ Summary: The official Python library for the perplexity API
5
+ Project-URL: Homepage, https://github.com/ppl-ai/perplexity-py
6
+ Project-URL: Repository, https://github.com/ppl-ai/perplexity-py
7
+ Author: Perplexity
8
+ License: Apache-2.0
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.8
25
+ Requires-Dist: anyio<5,>=3.5.0
26
+ Requires-Dist: distro<2,>=1.7.0
27
+ Requires-Dist: httpx<1,>=0.23.0
28
+ Requires-Dist: pydantic<3,>=1.9.0
29
+ Requires-Dist: sniffio
30
+ Requires-Dist: typing-extensions<5,>=4.10
31
+ Provides-Extra: aiohttp
32
+ Requires-Dist: aiohttp; extra == 'aiohttp'
33
+ Requires-Dist: httpx-aiohttp>=0.1.8; extra == 'aiohttp'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # Perplexity Python API library
37
+
38
+ <!-- prettier-ignore -->
39
+ [![PyPI version](https://img.shields.io/pypi/v/perplexityai.svg?label=pypi%20(stable))](https://pypi.org/project/perplexityai/)
40
+
41
+ The Perplexity Python library provides convenient access to the Perplexity REST API from any Python 3.8+
42
+ application. The library includes type definitions for all request params and response fields,
43
+ and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
44
+
45
+ It is generated with [Stainless](https://www.stainless.com/).
46
+
47
+ ## Documentation
48
+
49
+ The full API of this library can be found in [api.md](https://github.com/ppl-ai/perplexity-py/tree/main/api.md).
50
+
51
+ ## Installation
52
+
53
+ ```sh
54
+ # install from PyPI
55
+ pip install perplexityai
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ The full API of this library can be found in [api.md](https://github.com/ppl-ai/perplexity-py/tree/main/api.md).
61
+
62
+ ```python
63
+ import os
64
+ from perplexity import Perplexity
65
+
66
+ client = Perplexity(
67
+ bearer_token=os.environ.get("PERPLEXITY_API_KEY"), # This is the default and can be omitted
68
+ )
69
+
70
+ response = client.search.perform(
71
+ query="string",
72
+ )
73
+ print(response.id)
74
+ ```
75
+
76
+ While you can provide a `bearer_token` keyword argument,
77
+ we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
78
+ to add `PERPLEXITY_API_KEY="My Bearer Token"` to your `.env` file
79
+ so that your Bearer Token is not stored in source control.
80
+
81
+ ## Async usage
82
+
83
+ Simply import `AsyncPerplexity` instead of `Perplexity` and use `await` with each API call:
84
+
85
+ ```python
86
+ import os
87
+ import asyncio
88
+ from perplexity import AsyncPerplexity
89
+
90
+ client = AsyncPerplexity(
91
+ bearer_token=os.environ.get("PERPLEXITY_API_KEY"), # This is the default and can be omitted
92
+ )
93
+
94
+
95
+ async def main() -> None:
96
+ response = await client.search.perform(
97
+ query="string",
98
+ )
99
+ print(response.id)
100
+
101
+
102
+ asyncio.run(main())
103
+ ```
104
+
105
+ Functionality between the synchronous and asynchronous clients is otherwise identical.
106
+
107
+ ### With aiohttp
108
+
109
+ By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.
110
+
111
+ You can enable this by installing `aiohttp`:
112
+
113
+ ```sh
114
+ # install from PyPI
115
+ pip install perplexityai[aiohttp]
116
+ ```
117
+
118
+ Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:
119
+
120
+ ```python
121
+ import asyncio
122
+ from perplexity import DefaultAioHttpClient
123
+ from perplexity import AsyncPerplexity
124
+
125
+
126
+ async def main() -> None:
127
+ async with AsyncPerplexity(
128
+ bearer_token="My Bearer Token",
129
+ http_client=DefaultAioHttpClient(),
130
+ ) as client:
131
+ response = await client.search.perform(
132
+ query="string",
133
+ )
134
+ print(response.id)
135
+
136
+
137
+ asyncio.run(main())
138
+ ```
139
+
140
+ ## Using types
141
+
142
+ Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like:
143
+
144
+ - Serializing back into JSON, `model.to_json()`
145
+ - Converting to a dictionary, `model.to_dict()`
146
+
147
+ Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.
148
+
149
+ ## Handling errors
150
+
151
+ When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `perplexity.APIConnectionError` is raised.
152
+
153
+ When the API returns a non-success status code (that is, 4xx or 5xx
154
+ response), a subclass of `perplexity.APIStatusError` is raised, containing `status_code` and `response` properties.
155
+
156
+ All errors inherit from `perplexity.APIError`.
157
+
158
+ ```python
159
+ import perplexity
160
+ from perplexity import Perplexity
161
+
162
+ client = Perplexity()
163
+
164
+ try:
165
+ client.search.perform(
166
+ query="string",
167
+ )
168
+ except perplexity.APIConnectionError as e:
169
+ print("The server could not be reached")
170
+ print(e.__cause__) # an underlying Exception, likely raised within httpx.
171
+ except perplexity.RateLimitError as e:
172
+ print("A 429 status code was received; we should back off a bit.")
173
+ except perplexity.APIStatusError as e:
174
+ print("Another non-200-range status code was received")
175
+ print(e.status_code)
176
+ print(e.response)
177
+ ```
178
+
179
+ Error codes are as follows:
180
+
181
+ | Status Code | Error Type |
182
+ | ----------- | -------------------------- |
183
+ | 400 | `BadRequestError` |
184
+ | 401 | `AuthenticationError` |
185
+ | 403 | `PermissionDeniedError` |
186
+ | 404 | `NotFoundError` |
187
+ | 422 | `UnprocessableEntityError` |
188
+ | 429 | `RateLimitError` |
189
+ | >=500 | `InternalServerError` |
190
+ | N/A | `APIConnectionError` |
191
+
192
+ ### Retries
193
+
194
+ Certain errors are automatically retried 2 times by default, with a short exponential backoff.
195
+ Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
196
+ 429 Rate Limit, and >=500 Internal errors are all retried by default.
197
+
198
+ You can use the `max_retries` option to configure or disable retry settings:
199
+
200
+ ```python
201
+ from perplexity import Perplexity
202
+
203
+ # Configure the default for all requests:
204
+ client = Perplexity(
205
+ # default is 2
206
+ max_retries=0,
207
+ )
208
+
209
+ # Or, configure per-request:
210
+ client.with_options(max_retries=5).search.perform(
211
+ query="string",
212
+ )
213
+ ```
214
+
215
+ ### Timeouts
216
+
217
+ By default requests time out after 1 minute. You can configure this with a `timeout` option,
218
+ which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:
219
+
220
+ ```python
221
+ from perplexity import Perplexity
222
+
223
+ # Configure the default for all requests:
224
+ client = Perplexity(
225
+ # 20 seconds (default is 1 minute)
226
+ timeout=20.0,
227
+ )
228
+
229
+ # More granular control:
230
+ client = Perplexity(
231
+ timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
232
+ )
233
+
234
+ # Override per-request:
235
+ client.with_options(timeout=5.0).search.perform(
236
+ query="string",
237
+ )
238
+ ```
239
+
240
+ On timeout, an `APITimeoutError` is thrown.
241
+
242
+ Note that requests that time out are [retried twice by default](https://github.com/ppl-ai/perplexity-py/tree/main/#retries).
243
+
244
+ ## Advanced
245
+
246
+ ### Logging
247
+
248
+ We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
249
+
250
+ You can enable logging by setting the environment variable `PERPLEXITY_LOG` to `info`.
251
+
252
+ ```shell
253
+ $ export PERPLEXITY_LOG=info
254
+ ```
255
+
256
+ Or to `debug` for more verbose logging.
257
+
258
+ ### How to tell whether `None` means `null` or missing
259
+
260
+ In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:
261
+
262
+ ```py
263
+ if response.my_field is None:
264
+ if 'my_field' not in response.model_fields_set:
265
+ print('Got json like {}, without a "my_field" key present at all.')
266
+ else:
267
+ print('Got json like {"my_field": null}.')
268
+ ```
269
+
270
+ ### Accessing raw response data (e.g. headers)
271
+
272
+ The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
273
+
274
+ ```py
275
+ from perplexity import Perplexity
276
+
277
+ client = Perplexity()
278
+ response = client.search.with_raw_response.perform(
279
+ query="string",
280
+ )
281
+ print(response.headers.get('X-My-Header'))
282
+
283
+ search = response.parse() # get the object that `search.perform()` would have returned
284
+ print(search.id)
285
+ ```
286
+
287
+ These methods return an [`APIResponse`](https://github.com/ppl-ai/perplexity-py/tree/main/src/perplexity/_response.py) object.
288
+
289
+ The async client returns an [`AsyncAPIResponse`](https://github.com/ppl-ai/perplexity-py/tree/main/src/perplexity/_response.py) with the same structure, the only difference being `await`able methods for reading the response content.
290
+
291
+ #### `.with_streaming_response`
292
+
293
+ The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
294
+
295
+ To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
296
+
297
+ ```python
298
+ with client.search.with_streaming_response.perform(
299
+ query="string",
300
+ ) as response:
301
+ print(response.headers.get("X-My-Header"))
302
+
303
+ for line in response.iter_lines():
304
+ print(line)
305
+ ```
306
+
307
+ The context manager is required so that the response will reliably be closed.
308
+
309
+ ### Making custom/undocumented requests
310
+
311
+ This library is typed for convenient access to the documented API.
312
+
313
+ If you need to access undocumented endpoints, params, or response properties, the library can still be used.
314
+
315
+ #### Undocumented endpoints
316
+
317
+ To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other
318
+ http verbs. Options on the client will be respected (such as retries) when making this request.
319
+
320
+ ```py
321
+ import httpx
322
+
323
+ response = client.post(
324
+ "/foo",
325
+ cast_to=httpx.Response,
326
+ body={"my_param": True},
327
+ )
328
+
329
+ print(response.headers.get("x-foo"))
330
+ ```
331
+
332
+ #### Undocumented request params
333
+
334
+ If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request
335
+ options.
336
+
337
+ #### Undocumented response properties
338
+
339
+ To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You
340
+ can also get all the extra fields on the Pydantic model as a dict with
341
+ [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
342
+
343
+ ### Configuring the HTTP client
344
+
345
+ You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
346
+
347
+ - Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
348
+ - Custom [transports](https://www.python-httpx.org/advanced/transports/)
349
+ - Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
350
+
351
+ ```python
352
+ import httpx
353
+ from perplexity import Perplexity, DefaultHttpxClient
354
+
355
+ client = Perplexity(
356
+ # Or use the `PERPLEXITY_BASE_URL` env var
357
+ base_url="http://my.test.server.example.com:8083",
358
+ http_client=DefaultHttpxClient(
359
+ proxy="http://my.test.proxy.example.com",
360
+ transport=httpx.HTTPTransport(local_address="0.0.0.0"),
361
+ ),
362
+ )
363
+ ```
364
+
365
+ You can also customize the client on a per-request basis by using `with_options()`:
366
+
367
+ ```python
368
+ client.with_options(http_client=DefaultHttpxClient(...))
369
+ ```
370
+
371
+ ### Managing HTTP resources
372
+
373
+ By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
374
+
375
+ ```py
376
+ from perplexity import Perplexity
377
+
378
+ with Perplexity() as client:
379
+ # make requests here
380
+ ...
381
+
382
+ # HTTP client is now closed
383
+ ```
384
+
385
+ ## Versioning
386
+
387
+ This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
388
+
389
+ 1. Changes that only affect static types, without breaking runtime behavior.
390
+ 2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
391
+ 3. Changes that we do not expect to impact the vast majority of users in practice.
392
+
393
+ We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
394
+
395
+ We are keen for your feedback; please open an [issue](https://www.github.com/ppl-ai/perplexity-py/issues) with questions, bugs, or suggestions.
396
+
397
+ ### Determining the installed version
398
+
399
+ If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
400
+
401
+ You can determine the version that is being used at runtime with:
402
+
403
+ ```py
404
+ import perplexity
405
+ print(perplexity.__version__)
406
+ ```
407
+
408
+ ## Requirements
409
+
410
+ Python 3.8 or higher.
411
+
412
+ ## Contributing
413
+
414
+ See [the contributing documentation](https://github.com/ppl-ai/perplexity-py/tree/main/./CONTRIBUTING.md).
@@ -0,0 +1,37 @@
1
+ perplexity/__init__.py,sha256=5epbvK3UiJEgvsBW9Ds6RFB6zObkUxYkA9fIQlgUaXA,2655
2
+ perplexity/_base_client.py,sha256=DSeMteXutziRGJA9HqJaoLpG7ktzpU2GPcaIgQT1oZQ,67051
3
+ perplexity/_client.py,sha256=6Jw9Vj9yIfis_IzBnveUSNcpuOc4Zja4RWjqw8belD4,15250
4
+ perplexity/_compat.py,sha256=DQBVORjFb33zch24jzkhM14msvnzY7mmSmgDLaVFUM8,6562
5
+ perplexity/_constants.py,sha256=S14PFzyN9-I31wiV7SmIlL5Ga0MLHxdvegInGdXH7tM,462
6
+ perplexity/_exceptions.py,sha256=v-hOXWSDTEtXcn_By7pPml3HjEmG5HXpbE-RK_A6_0Q,3228
7
+ perplexity/_files.py,sha256=KnEzGi_O756MvKyJ4fOCW_u3JhOeWPQ4RsmDvqihDQU,3545
8
+ perplexity/_models.py,sha256=c29x_mRccdxlGwdUPfSR5eJxGXe74Ea5Dje5igZTrKQ,30024
9
+ perplexity/_qs.py,sha256=AOkSz4rHtK4YI3ZU_kzea-zpwBUgEY8WniGmTPyEimc,4846
10
+ perplexity/_resource.py,sha256=Pgc8KNBsIc1ltJn94uhDcDl0-3n5RLbe3iC2AiiNRnE,1124
11
+ perplexity/_response.py,sha256=bpqzmVGq6jnivoMkUgt3OI0Rh6xHd6BMcp5PHgSFPb0,28842
12
+ perplexity/_streaming.py,sha256=SQ61v42gFmNiO57uMFUZMAuDlGE0n_EulkZcPgJXt4U,10116
13
+ perplexity/_types.py,sha256=XZYv2_G7oQGhQkjI28-TFIMP_yZZV590TRuKAoLJ3wM,7300
14
+ perplexity/_version.py,sha256=U9sUKjBKb3A9ToG_1ejhE_i3pd9hUeG4kll8UjAvTxQ,162
15
+ perplexity/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ perplexity/_utils/__init__.py,sha256=7fch0GT9zpNnErbciSpUNa-SjTxxjY6kxHxKMOM4AGs,2305
17
+ perplexity/_utils/_compat.py,sha256=D8gtAvjJQrDWt9upS0XaG9Rr5l1QhiAx_I_1utT_tt0,1195
18
+ perplexity/_utils/_datetime_parse.py,sha256=bABTs0Bc6rabdFvnIwXjEhWL15TcRgWZ_6XGTqN8xUk,4204
19
+ perplexity/_utils/_logs.py,sha256=CsE-zYnAQTOCueNGVjEn6bozMyE86gdjMhJDNWDLpaQ,786
20
+ perplexity/_utils/_proxy.py,sha256=aglnj2yBTDyGX9Akk2crZHrl10oqRmceUy2Zp008XEs,1975
21
+ perplexity/_utils/_reflection.py,sha256=ZmGkIgT_PuwedyNBrrKGbxoWtkpytJNU1uU4QHnmEMU,1364
22
+ perplexity/_utils/_resources_proxy.py,sha256=iMCHPeYmXwSunawEq3fcKGszOF3kL9w1ob-48Xnl04I,609
23
+ perplexity/_utils/_streams.py,sha256=SMC90diFFecpEg_zgDRVbdR3hSEIgVVij4taD-noMLM,289
24
+ perplexity/_utils/_sync.py,sha256=TpGLrrhRNWTJtODNE6Fup3_k7zrWm1j2RlirzBwre-0,2862
25
+ perplexity/_utils/_transform.py,sha256=i_U4R82RtQJtKKCriwFqmfcWjtwmmsiiF1AEXKQ_OPo,15957
26
+ perplexity/_utils/_typing.py,sha256=N_5PPuFNsaygbtA_npZd98SVN1LQQvFTKL6bkWPBZGU,4786
27
+ perplexity/_utils/_utils.py,sha256=D2QE7mVPNEJzaB50u8rvDQAUDS5jx7JoeFD7zdj-TeI,12231
28
+ perplexity/lib/.keep,sha256=wuNrz-5SXo3jJaJOJgz4vFHM41YH_g20F5cRQo0vLes,224
29
+ perplexity/resources/__init__.py,sha256=e0o4Fhm2rFANVaRFoUJUmfCjJunhyhiJHWWRRnwv_yg,552
30
+ perplexity/resources/search.py,sha256=mtMyJldXSFqxV2_aAXCBwtgfQGhc8rFwxeB7w4iIqtI,9049
31
+ perplexity/types/__init__.py,sha256=aDrqSVZlm4J2cYRjWW4rgjj9L9RmjB1vLgKLtYVWx6U,285
32
+ perplexity/types/search_perform_params.py,sha256=fVLLBEZRfv14PEoOoRMF17LY6hbJ7cjDZ6RerU3fq40,888
33
+ perplexity/types/search_perform_response.py,sha256=Ye9MCiV-sObUt78wqOeNPm2BbHTsSixekMiX7UOsUU0,428
34
+ perplexityai-0.3.0.dist-info/METADATA,sha256=EYTvlFSNje_L85SH3INEavRqLMXaf6mnonR8zu1b2Ms,13676
35
+ perplexityai-0.3.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
36
+ perplexityai-0.3.0.dist-info/licenses/LICENSE,sha256=hkCriG3MT4vBhhc0roAOsrCE7IEDr1ywVEMonVHGmAQ,11340
37
+ perplexityai-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.26.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any