perplexityai 1.0.3__tar.gz → 1.0.5__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.

Potentially problematic release.


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

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: perplexityai
3
- Version: 1.0.3
3
+ Version: 1.0.5
4
4
  Summary: A simple module to use Perplexity AI in Python.
5
5
  Home-page: https://github.com/Ruu3f/perplexityai
6
6
  Author: Ruu3f
@@ -0,0 +1,213 @@
1
+ __author__ = "Ruu3f"
2
+ __version__ = "1.0.5"
3
+
4
+ from uuid import uuid4
5
+ from requests import Session
6
+ from time import sleep, time
7
+ from threading import Thread
8
+ from json import loads, dumps
9
+ from random import getrandbits
10
+ from websocket import WebSocketApp
11
+
12
+
13
+ class Perplexity:
14
+ def __init__(self):
15
+ self.session = Session()
16
+ self.user_agent = {
17
+ "User-Agent": "Ask/2.4.1/224 (iOS; iPhone; Version 17.1) isiOSOnMac/false",
18
+ "X-Client-Name": "Perplexity-iOS",
19
+ }
20
+ self.session.headers.update(self.user_agent)
21
+ self.t = format(getrandbits(32), "08x")
22
+ response = self.session.get(
23
+ url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}"
24
+ ).text[1:]
25
+ self.sid = loads(response)["sid"]
26
+ self.n = 1
27
+ self.base = 420
28
+ self.finished = True
29
+ self.last_uuid = None
30
+ assert (
31
+ lambda: self.session.post(
32
+ url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}",
33
+ data='40{"jwt":"anonymous-ask-user"}',
34
+ ).text
35
+ == "OK"
36
+ )(), "Failed to ask the anonymous user."
37
+ self.ws = self._init_websocket()
38
+ self.ws_thread = Thread(target=self.ws.run_forever).start()
39
+ while not (self.ws.sock and self.ws.sock.connected):
40
+ sleep(0.1)
41
+
42
+ def _init_websocket(self):
43
+ def on_open(ws):
44
+ ws.send("2probe")
45
+ ws.send("5")
46
+
47
+ def on_message(ws, message):
48
+ if message == "2":
49
+ ws.send("3")
50
+ elif not self.finished:
51
+ if message.startswith("42"):
52
+ message = loads(message[2:])
53
+ content = message[1]
54
+ if "mode" in content:
55
+ content.update(loads(content["text"]))
56
+ content.pop("text")
57
+ if (not ("final" in content and content["final"])) or (
58
+ "status" in content and content["status"] == "completed"
59
+ ):
60
+ self.queue.append(content)
61
+ if message[0] == "query_answered":
62
+ self.last_uuid = content["uuid"]
63
+ self.finished = True
64
+ elif message.startswith("43"):
65
+ message = loads(message[3:])[0]
66
+ if (
67
+ "uuid" in message and message["uuid"] != self.last_uuid
68
+ ) or "uuid" not in message:
69
+ self.queue.append(message)
70
+ self.finished = True
71
+
72
+ cookies = "; ".join(
73
+ [f"{key}={value}" for key, value in self.session.cookies.get_dict().items()]
74
+ )
75
+ ws = WebSocketApp(
76
+ url=f"wss://www.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
77
+ header=self.user_agent,
78
+ cookie=cookies,
79
+ on_open=on_open,
80
+ on_message=on_message,
81
+ on_error=lambda ws, err: print(f"WebSocket error: {err}"),
82
+ )
83
+ return ws
84
+
85
+ def generate_answer(self, query):
86
+ self.finished = False
87
+ if self.n == 9:
88
+ self.n = 0
89
+ self.base *= 10
90
+ else:
91
+ self.n += 1
92
+ self.queue = []
93
+ self.ws.send(
94
+ str(self.base + self.n)
95
+ + dumps(
96
+ [
97
+ "perplexity_ask",
98
+ query,
99
+ {
100
+ "frontend_session_id": str(uuid4()),
101
+ "language": "en-GB",
102
+ "timezone": "UTC",
103
+ "search_focus": "internet",
104
+ "frontend_uuid": str(uuid4()),
105
+ "mode": "concise",
106
+ },
107
+ ]
108
+ )
109
+ )
110
+ start_time = time()
111
+ while (not self.finished) or len(self.queue) != 0:
112
+ if time() - start_time > 30:
113
+ self.finished = True
114
+ return {"error": "Timed out."}
115
+ if len(self.queue) != 0:
116
+ yield self.queue.pop(0)
117
+ self.ws.close()
118
+
119
+
120
+ class Labs:
121
+ def __init__(self):
122
+ self.history = []
123
+ self.session = Session()
124
+ self.session.headers.update(
125
+ {
126
+ "User-Agent": "Ask/2.2.1/334 (iOS; iPhone) isiOSOnMac/false",
127
+ "X-Client-Name": "Perplexity-iOS",
128
+ }
129
+ )
130
+ self.session.get(url=f"https://www.perplexity.ai/search/{str(uuid4())}")
131
+ self.t = format(getrandbits(32), "08x")
132
+ response = self.session.get(
133
+ url="https://labs-api.perplexity.ai/socket.io/?transport=polling&EIO=4"
134
+ ).text[1:]
135
+ self.sid = loads(response)["sid"]
136
+
137
+ self.queue = []
138
+ self.finished = True
139
+
140
+ response = self.session.post(
141
+ url=f"https://labs-api.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}",
142
+ data='40{"jwt":"anonymous-ask-user"}',
143
+ ).text
144
+ assert response == "OK", "failed to ask anonymous user"
145
+
146
+ self._init_websocket()
147
+
148
+ while not (self.ws.sock and self.ws.sock.connected):
149
+ sleep(0.01)
150
+
151
+ def _init_websocket(self):
152
+ def on_open(ws):
153
+ ws.send("2probe")
154
+ ws.send("5")
155
+
156
+ def on_message(ws, message):
157
+ if message == "2":
158
+ ws.send("3")
159
+ elif message.startswith("42"):
160
+ message = loads(message[2:])[1]
161
+ if "status" not in message:
162
+ self.queue.append(message)
163
+ elif message["status"] == "completed":
164
+ self.finished = True
165
+ self.history.append(
166
+ {
167
+ "role": "assistant",
168
+ "content": message["output"],
169
+ "priority": 0,
170
+ }
171
+ )
172
+ elif message["status"] == "failed":
173
+ self.finished = True
174
+
175
+ cookies = "; ".join(
176
+ [f"{key}={value}" for key, value in self.session.cookies.get_dict().items()]
177
+ )
178
+ self.ws = WebSocketApp(
179
+ url=f"wss://labs-api.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
180
+ header={
181
+ "User-Agent": "Ask/2.2.1/334 (iOS; iPhone) isiOSOnMac/false",
182
+ "Cookie": cookies,
183
+ },
184
+ on_open=on_open,
185
+ on_message=on_message,
186
+ on_error=lambda ws, err: print(f"websocket error: {err}"),
187
+ )
188
+ Thread(target=self.ws.run_forever).start()
189
+ self.session.get(url="https://www.perplexity.ai/api/auth/session")
190
+
191
+ def generate_answer(self, prompt, model="mistral-7b-instruct"):
192
+ assert self.finished, "already searching"
193
+ assert model in [
194
+ "mixtral-8x7b-instruct",
195
+ "llava-7b-chat",
196
+ "llama-2-70b-chat",
197
+ "codellama-34b-instruct",
198
+ "mistral-7b-instruct",
199
+ "pplx-7b-chat",
200
+ "pplx-70b-chat",
201
+ "pplx-7b-online",
202
+ "pplx-70b-online",
203
+ ]
204
+ self.finished = False
205
+ self.history.append({"role": "user", "content": prompt, "priority": 0})
206
+ self.ws.send(
207
+ f'42["perplexity_labs",{{"version":"2.2","source":"default","model":"{model}","messages":{dumps(self.history)}}}]'
208
+ )
209
+
210
+ while (not self.finished) or (len(self.queue) != 0):
211
+ if len(self.queue) > 0:
212
+ yield self.queue.pop(0)
213
+ self.ws.close()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: perplexityai
3
- Version: 1.0.3
3
+ Version: 1.0.5
4
4
  Summary: A simple module to use Perplexity AI in Python.
5
5
  Home-page: https://github.com/Ruu3f/perplexityai
6
6
  Author: Ruu3f
@@ -2,7 +2,6 @@ LICENSE
2
2
  README.md
3
3
  setup.py
4
4
  perplexityai/__init__.py
5
- perplexityai/labs.py
6
5
  perplexityai.egg-info/PKG-INFO
7
6
  perplexityai.egg-info/SOURCES.txt
8
7
  perplexityai.egg-info/dependency_links.txt
@@ -5,7 +5,7 @@ with open("README.md", encoding="utf-8") as f:
5
5
 
6
6
  setup(
7
7
  name="perplexityai",
8
- version="1.0.3",
8
+ version="1.0.5",
9
9
  description="A simple module to use Perplexity AI in Python.",
10
10
  long_description=README,
11
11
  long_description_content_type="text/markdown",
@@ -1,118 +0,0 @@
1
- __author__ = "Ruu3f"
2
- __version__ = "1.0.2"
3
-
4
- from labs import Labs
5
- from uuid import uuid4
6
- from time import sleep, time
7
- from threading import Thread
8
- from json import loads, dumps
9
- from random import getrandbits
10
- from websocket import WebSocketApp
11
- from requests import Session
12
-
13
-
14
- class Perplexity:
15
- def __init__(self):
16
- self.session = Session()
17
- self.user_agent = {
18
- "User-Agent": "Ask/2.4.1/224 (iOS; iPhone; Version 17.1) isiOSOnMac/false",
19
- "X-Client-Name": "Perplexity-iOS",
20
- }
21
- self.session.headers.update(self.user_agent)
22
- self.t = format(getrandbits(32), "08x")
23
- self.sid = loads(
24
- self.session.get(
25
- url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}"
26
- ).text[1:]
27
- )["sid"]
28
- self.n = 1
29
- self.base = 420
30
- self.finished = True
31
- self.last_uuid = None
32
- assert (
33
- lambda: self.session.post(
34
- url=f"https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}",
35
- data='40{"jwt":"anonymous-ask-user"}',
36
- ).text
37
- == "OK"
38
- )(), "Failed to ask the anonymous user."
39
- self.ws = self._init_websocket()
40
- self.ws_thread = Thread(target=self.ws.run_forever).start()
41
- while not (self.ws.sock and self.ws.sock.connected):
42
- sleep(0.1)
43
-
44
- def _init_websocket(self):
45
- def on_open(ws):
46
- ws.send("2probe")
47
- ws.send("5")
48
-
49
- def on_message(ws, message):
50
- if message == "2":
51
- ws.send("3")
52
- elif not self.finished:
53
- if message.startswith("42"):
54
- message = loads(message[2:])
55
- content = message[1]
56
- if "mode" in content:
57
- content.update(loads(content["text"]))
58
- content.pop("text")
59
- if (not ("final" in content and content["final"])) or (
60
- "status" in content and content["status"] == "completed"
61
- ):
62
- self.queue.append(content)
63
- if message[0] == "query_answered":
64
- self.last_uuid = content["uuid"]
65
- self.finished = True
66
- elif message.startswith("43"):
67
- message = loads(message[3:])[0]
68
- if (
69
- "uuid" in message and message["uuid"] != self.last_uuid
70
- ) or "uuid" not in message:
71
- self.queue.append(message)
72
- self.finished = True
73
-
74
- cookies = ""
75
- for key, value in self.session.cookies.get_dict().items():
76
- cookies += f"{key}={value}; "
77
- return WebSocketApp(
78
- url=f"wss://www.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
79
- header=self.user_agent,
80
- cookie=cookies[:-2],
81
- on_open=on_open,
82
- on_message=on_message,
83
- on_error=lambda ws, err: print(f"WebSocket error: {err}"),
84
- )
85
-
86
- def generate_answer(self, query):
87
- self.finished = False
88
- if self.n == 9:
89
- self.n = 0
90
- self.base *= 10
91
- else:
92
- self.n += 1
93
- self.queue = []
94
- self.ws.send(
95
- str(self.base + self.n)
96
- + dumps(
97
- [
98
- "perplexity_ask",
99
- query,
100
- {
101
- "frontend_session_id": str(uuid4()),
102
- "language": "en-GB",
103
- "timezone": "UTC",
104
- "search_focus": "internet",
105
- "frontend_uuid": str(uuid4()),
106
- "mode": "concise",
107
- },
108
- ]
109
- )
110
- )
111
- start_time = time()
112
- while (not self.finished) or len(self.queue) != 0:
113
- if time() - start_time > 30:
114
- self.finished = True
115
- return {"error": "Timed out."}
116
- if len(self.queue) != 0:
117
- yield self.queue.pop(0)
118
- self.ws.close()
@@ -1,114 +0,0 @@
1
- from uuid import uuid4
2
- from requests import Session
3
- from threading import Thread
4
- from json import loads, dumps
5
- from random import getrandbits
6
- from websocket import WebSocketApp
7
-
8
-
9
- class Labs:
10
- def __init__(self):
11
- self.history = []
12
- self.session = Session()
13
- self.session.headers.update(
14
- {
15
- "User-Agent": "Ask/2.2.1/334 (iOS; iPhone) isiOSOnMac/false",
16
- "X-Client-Name": "Perplexity-iOS",
17
- }
18
- )
19
- self._init_session_without_login()
20
-
21
- self.t = format(getrandbits(32), "08x")
22
- self.sid = loads(
23
- self.session.get(
24
- url="https://labs-api.perplexity.ai/socket.io/?transport=polling&EIO=4"
25
- ).text[1:]
26
- )["sid"]
27
-
28
- self.queue = []
29
- self.finished = True
30
-
31
- assert self._ask_anonymous_user(), "failed to ask anonymous user"
32
- self.ws = WebSocketApp(
33
- url=f"wss://labs-api.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
34
- header=self._get_headers(),
35
- on_open=self._on_open,
36
- on_message=self._on_message,
37
- on_error=lambda ws, err: print(f"websocket error: {err}"),
38
- )
39
- Thread(target=self.ws.run_forever).start()
40
- self._auth_session()
41
-
42
- while not (self.ws.sock and self.ws.sock.connected):
43
- import time
44
-
45
- time.sleep(0.01)
46
-
47
- def _init_session_without_login(self):
48
- self.session.get(url=f"https://www.perplexity.ai/search/{str(uuid4())}")
49
- self.session.headers.update(
50
- {"User-Agent": "Ask/2.2.1/334 (iOS; iPhone) isiOSOnMac/false"}
51
- )
52
-
53
- def _auth_session(self):
54
- self.session.get(url="https://www.perplexity.ai/api/auth/session")
55
-
56
- def _ask_anonymous_user(self):
57
- response = self.session.post(
58
- url=f"https://labs-api.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.t}&sid={self.sid}",
59
- data='40{"jwt":"anonymous-ask-user"}',
60
- ).text
61
- return response == "OK"
62
-
63
- def _get_cookies_str(self):
64
- return "; ".join(
65
- [f"{key}={value}" for key, value in self.session.cookies.get_dict().items()]
66
- )
67
-
68
- def _get_headers(self):
69
- headers = {"User-Agent": "Ask/2.2.1/334 (iOS; iPhone) isiOSOnMac/false"}
70
- headers["Cookie"] = self._get_cookies_str()
71
- return headers
72
-
73
- def _on_open(self, ws):
74
- ws.send("2probe")
75
- ws.send("5")
76
-
77
- def _on_message(self, ws, message):
78
- if message == "2":
79
- ws.send("3")
80
- elif message.startswith("42"):
81
- message = loads(message[2:])[1]
82
- if "status" not in message:
83
- self.queue.append(message)
84
- elif message["status"] == "completed":
85
- self.finished = True
86
- self.history.append(
87
- {"role": "assistant", "content": message["output"], "priority": 0}
88
- )
89
- elif message["status"] == "failed":
90
- self.finished = True
91
-
92
- def generate_answer(self, prompt, model="mistral-7b-instruct"):
93
- assert self.finished, "already searching"
94
- assert model in [
95
- "mixtral-8x7b-instruct",
96
- "llava-7b-chat",
97
- "llama-2-70b-chat",
98
- "codellama-34b-instruct",
99
- "mistral-7b-instruct",
100
- "pplx-7b-chat",
101
- "pplx-70b-chat",
102
- "pplx-7b-online",
103
- "pplx-70b-online",
104
- ]
105
- self.finished = False
106
- self.history.append({"role": "user", "content": prompt, "priority": 0})
107
- self.ws.send(
108
- f'42["perplexity_labs",{{"version":"2.2","source":"default","model":"{model}","messages":{dumps(self.history)}}}]'
109
- )
110
-
111
- while (not self.finished) or (len(self.queue) != 0):
112
- if len(self.queue) > 0:
113
- yield self.queue.pop(0)
114
- self.ws.close()
File without changes
File without changes
File without changes