perplexityai 1.0.3__py3-none-any.whl → 1.0.5__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.
perplexityai/__init__.py CHANGED
@@ -1,14 +1,13 @@
1
1
  __author__ = "Ruu3f"
2
- __version__ = "1.0.2"
2
+ __version__ = "1.0.5"
3
3
 
4
- from labs import Labs
5
4
  from uuid import uuid4
5
+ from requests import Session
6
6
  from time import sleep, time
7
7
  from threading import Thread
8
8
  from json import loads, dumps
9
9
  from random import getrandbits
10
10
  from websocket import WebSocketApp
11
- from requests import Session
12
11
 
13
12
 
14
13
  class Perplexity:
@@ -20,11 +19,10 @@ class Perplexity:
20
19
  }
21
20
  self.session.headers.update(self.user_agent)
22
21
  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"]
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"]
28
26
  self.n = 1
29
27
  self.base = 420
30
28
  self.finished = True
@@ -71,17 +69,18 @@ class Perplexity:
71
69
  self.queue.append(message)
72
70
  self.finished = True
73
71
 
74
- cookies = ""
75
- for key, value in self.session.cookies.get_dict().items():
76
- cookies += f"{key}={value}; "
77
- return WebSocketApp(
72
+ cookies = "; ".join(
73
+ [f"{key}={value}" for key, value in self.session.cookies.get_dict().items()]
74
+ )
75
+ ws = WebSocketApp(
78
76
  url=f"wss://www.perplexity.ai/socket.io/?EIO=4&transport=websocket&sid={self.sid}",
79
77
  header=self.user_agent,
80
- cookie=cookies[:-2],
78
+ cookie=cookies,
81
79
  on_open=on_open,
82
80
  on_message=on_message,
83
81
  on_error=lambda ws, err: print(f"WebSocket error: {err}"),
84
82
  )
83
+ return ws
85
84
 
86
85
  def generate_answer(self, query):
87
86
  self.finished = False
@@ -116,3 +115,99 @@ class Perplexity:
116
115
  if len(self.queue) != 0:
117
116
  yield self.queue.pop(0)
118
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
@@ -0,0 +1,6 @@
1
+ perplexityai/__init__.py,sha256=5QhLPh6qnDIgZJB-iiUs5z4EKD4TsFSfwqcZMIVPwjc,7671
2
+ perplexityai-1.0.5.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
3
+ perplexityai-1.0.5.dist-info/METADATA,sha256=SPSxIS0hVxOsaHCSMGnxB9XxXqKX8ZThHnf6PxRHzD8,2783
4
+ perplexityai-1.0.5.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
5
+ perplexityai-1.0.5.dist-info/top_level.txt,sha256=FjfrNBQgBFDzSUW0lbumU3KJrpdyFC7rx_cn96Jt7Ik,13
6
+ perplexityai-1.0.5.dist-info/RECORD,,
perplexityai/labs.py DELETED
@@ -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()
@@ -1,7 +0,0 @@
1
- perplexityai/__init__.py,sha256=LtVe3dvryPOwxGgEWaj0pAV-WEoXhu3xab2s61DHK2I,4218
2
- perplexityai/labs.py,sha256=jQTBrQVg9SCqjef96IplUikcN7FZt1z8r_PTF9j0N8k,4027
3
- perplexityai-1.0.3.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
4
- perplexityai-1.0.3.dist-info/METADATA,sha256=pXKPDcgjIu-bJiQa04Jr0mx933YcYNkDyQOuuc8nD5c,2783
5
- perplexityai-1.0.3.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
6
- perplexityai-1.0.3.dist-info/top_level.txt,sha256=FjfrNBQgBFDzSUW0lbumU3KJrpdyFC7rx_cn96Jt7Ik,13
7
- perplexityai-1.0.3.dist-info/RECORD,,