perplex.js 0.1.0 → 0.1.3
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.
- package/LICENSE +19 -19
- package/README.md +36 -36
- package/package.json +33 -30
- package/src/client.js +354 -284
- package/src/index.js +7 -7
- package/src/sseParser.js +47 -47
package/LICENSE
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 DIDELOT Tim
|
|
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,
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 DIDELOT Tim
|
|
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
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
|
|
2
|
-
# Perplex.js — Minimal Node.js client for Perplexity AI
|
|
3
|
-
|
|
4
|
-
This small library provides a minimal client to query the Perplexity API.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
Features:
|
|
8
|
-
- Synchronous request to the SSE endpoint `/rest/sse/perplexity_ask`.
|
|
9
|
-
- Methods: `search` (returns the final response), `streamSearch` (async iterator for streaming messages).
|
|
10
|
-
|
|
11
|
-
Installation:
|
|
12
|
-
|
|
13
|
-
```bash
|
|
14
|
-
npm install
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
Usage (example):
|
|
20
|
-
|
|
21
|
-
```js
|
|
22
|
-
import { PerplexityClient } from 'perplex.js';
|
|
23
|
-
const c = new PerplexityClient();
|
|
24
|
-
// To use your account, manually export cookies from your browser
|
|
25
|
-
// (for example using a cookie export extension) and save them
|
|
26
|
-
// into `perplexity_cookies.json` as an array of {name, value, domain, ...} objects.
|
|
27
|
-
// Then:
|
|
28
|
-
// const cookies = JSON.parse(fs.readFileSync('./perplexity_cookies.json', 'utf8'));
|
|
29
|
-
// const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');
|
|
30
|
-
// const c = new PerplexityClient({ cookies: cookieHeader });
|
|
31
|
-
// await c.search('What is the capital of France?');
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
Notes:
|
|
35
|
-
- Authentication is performed via session cookies. This library does not require an API key.
|
|
36
|
-
- Endpoints and payload formats aim to match Perplexity's publicly observed API.
|
|
1
|
+
|
|
2
|
+
# Perplex.js — Minimal Node.js client for Perplexity AI
|
|
3
|
+
|
|
4
|
+
This small library provides a minimal client to query the Perplexity API.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
Features:
|
|
8
|
+
- Synchronous request to the SSE endpoint `/rest/sse/perplexity_ask`.
|
|
9
|
+
- Methods: `search` (returns the final response), `streamSearch` (async iterator for streaming messages).
|
|
10
|
+
|
|
11
|
+
Installation:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install perplex.js
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
Usage (example):
|
|
20
|
+
|
|
21
|
+
```js
|
|
22
|
+
import { PerplexityClient } from 'perplex.js';
|
|
23
|
+
const c = new PerplexityClient();
|
|
24
|
+
// To use your account, manually export cookies from your browser
|
|
25
|
+
// (for example using a cookie export extension) and save them
|
|
26
|
+
// into `perplexity_cookies.json` as an array of {name, value, domain, ...} objects.
|
|
27
|
+
// Then:
|
|
28
|
+
// const cookies = JSON.parse(fs.readFileSync('./perplexity_cookies.json', 'utf8'));
|
|
29
|
+
// const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ');
|
|
30
|
+
// const c = new PerplexityClient({ cookies: cookieHeader });
|
|
31
|
+
// await c.search('What is the capital of France?');
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Notes:
|
|
35
|
+
- Authentication is performed via session cookies. This library does not require an API key.
|
|
36
|
+
- Endpoints and payload formats aim to match Perplexity's publicly observed API.
|
package/package.json
CHANGED
|
@@ -1,30 +1,33 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "perplex.js",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Minimal Node.js client for the Perplexity API",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "src/index.js",
|
|
7
|
-
"repository": {
|
|
8
|
-
"type": "git",
|
|
9
|
-
"url": "https://github.com/xFufly/Perplex.js.git"
|
|
10
|
-
},
|
|
11
|
-
"files": [
|
|
12
|
-
"src",
|
|
13
|
-
"README.md"
|
|
14
|
-
],
|
|
15
|
-
"engines": {
|
|
16
|
-
"node": ">=18"
|
|
17
|
-
},
|
|
18
|
-
"scripts": {
|
|
19
|
-
"test": "node example.js",
|
|
20
|
-
"cli": "node examples/cli.js"
|
|
21
|
-
},
|
|
22
|
-
"keywords": [
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "perplex.js",
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"description": "Minimal Node.js client for the Perplexity API",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/xFufly/Perplex.js.git"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node example.js",
|
|
20
|
+
"cli": "node examples/cli.js"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"perplexity",
|
|
24
|
+
"perplexity.ai",
|
|
25
|
+
"ai",
|
|
26
|
+
"client"
|
|
27
|
+
],
|
|
28
|
+
"author": "DIDELOT Tim",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"undici": "^6.22.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/client.js
CHANGED
|
@@ -1,285 +1,355 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
} from '
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
'
|
|
12
|
-
'
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
1
|
+
import undici from 'undici';
|
|
2
|
+
const { request, fetch, FormData, Blob } = undici;
|
|
3
|
+
import { extname } from 'node:path';
|
|
4
|
+
import { parseSSE } from './sseParser.js';
|
|
5
|
+
|
|
6
|
+
const MODEL_PREFERENCES = {
|
|
7
|
+
auto: { null: 'turbo' },
|
|
8
|
+
pro: {
|
|
9
|
+
null: 'pplx_pro',
|
|
10
|
+
sonar: 'experimental',
|
|
11
|
+
'gpt-5.2': 'gpt52',
|
|
12
|
+
'claude-4.5-sonnet': 'claude45sonnet',
|
|
13
|
+
'grok-4.1': 'grok41nonreasoning'
|
|
14
|
+
},
|
|
15
|
+
reasoning: {
|
|
16
|
+
null: 'pplx_reasoning',
|
|
17
|
+
'gpt-5.2-thinking': 'gpt52_thinking',
|
|
18
|
+
'claude-4.5-sonnet-thinking': 'claude45sonnetthinking',
|
|
19
|
+
'gemini-3.0-pro': 'gemini30pro',
|
|
20
|
+
'kimi-k2-thinking': 'kimik2thinking',
|
|
21
|
+
'grok-4.1-reasoning': 'grok41reasoning'
|
|
22
|
+
},
|
|
23
|
+
'deep research': { null: 'pplx_alpha' }
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const MIME_MAP = {
|
|
27
|
+
'.txt': 'text/plain',
|
|
28
|
+
'.md': 'text/markdown',
|
|
29
|
+
'.json': 'application/json',
|
|
30
|
+
'.csv': 'text/csv',
|
|
31
|
+
'.pdf': 'application/pdf',
|
|
32
|
+
'.png': 'image/png',
|
|
33
|
+
'.jpg': 'image/jpeg',
|
|
34
|
+
'.jpeg': 'image/jpeg',
|
|
35
|
+
'.gif': 'image/gif',
|
|
36
|
+
'.webp': 'image/webp'
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
function defaultHeaders(cookie, contentType = 'application/json') {
|
|
40
|
+
const headers = {
|
|
41
|
+
accept: 'text/event-stream, text/plain, */*',
|
|
42
|
+
'content-type': contentType,
|
|
43
|
+
'user-agent': 'perplexity-js/0.1'
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
if (cookie) headers.cookie = serializeCookies(cookie);
|
|
47
|
+
return headers;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function serializeCookies(cookie) {
|
|
51
|
+
if (!cookie) return undefined;
|
|
52
|
+
return typeof cookie === 'string'
|
|
53
|
+
? cookie
|
|
54
|
+
: Object.entries(cookie)
|
|
55
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
56
|
+
.join('; ');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function guessMimeType(filename) {
|
|
60
|
+
const ext = extname(filename).toLowerCase();
|
|
61
|
+
return MIME_MAP[ext] || 'application/octet-stream';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parseFinalAnswer(data) {
|
|
65
|
+
if (!data || !data.text) return data;
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
const parsedText = typeof data.text === 'string' ? JSON.parse(data.text) : data.text;
|
|
69
|
+
data.text = parsedText;
|
|
70
|
+
|
|
71
|
+
if (Array.isArray(parsedText)) {
|
|
72
|
+
for (const step of parsedText) {
|
|
73
|
+
if (step && step.step_type === 'FINAL') {
|
|
74
|
+
const finalContent = step.content || {};
|
|
75
|
+
if (finalContent.answer) {
|
|
76
|
+
try {
|
|
77
|
+
const answerPayload = JSON.parse(finalContent.answer);
|
|
78
|
+
data.answer = answerPayload.answer ?? '';
|
|
79
|
+
data.chunks = answerPayload.chunks ?? [];
|
|
80
|
+
} catch (err) {
|
|
81
|
+
// swallow JSON parse errors and keep raw
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
} catch (err) {
|
|
89
|
+
// leave data as-is if parsing fails
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return data;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export default class PerplexityClient {
|
|
96
|
+
constructor(options = {}) {
|
|
97
|
+
// Perplexity access is done via session cookies (or anonymously). No API key is required.
|
|
98
|
+
this.base = options.base || 'https://www.perplexity.ai';
|
|
99
|
+
this.version = options.version || '2.18';
|
|
100
|
+
// optional cookies: either string or object map
|
|
101
|
+
this.cookies = options.cookies || null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Static mapping of modes -> available models
|
|
105
|
+
static getAvailableModels(mode = 'auto') {
|
|
106
|
+
const preferences = MODEL_PREFERENCES[mode] || MODEL_PREFERENCES.auto;
|
|
107
|
+
return Object.keys(preferences).map(k => (k === 'null' ? null : k));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Build the payload for the request
|
|
111
|
+
_buildPayload(query, opts = {}) {
|
|
112
|
+
const {
|
|
113
|
+
mode = 'auto',
|
|
114
|
+
model = null,
|
|
115
|
+
sources = ['web'],
|
|
116
|
+
attachments = [],
|
|
117
|
+
language = 'en-US',
|
|
118
|
+
follow_up = null,
|
|
119
|
+
incognito = false
|
|
120
|
+
} = opts;
|
|
121
|
+
|
|
122
|
+
const attachmentsFinal = attachments.concat(
|
|
123
|
+
follow_up && follow_up.attachments ? follow_up.attachments : []
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
const mpForMode = MODEL_PREFERENCES[mode] || MODEL_PREFERENCES.auto;
|
|
127
|
+
let modelPref = null;
|
|
128
|
+
if (mpForMode) {
|
|
129
|
+
if (model == null) {
|
|
130
|
+
modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
|
|
131
|
+
} else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) {
|
|
132
|
+
modelPref = mpForMode[model];
|
|
133
|
+
} else {
|
|
134
|
+
const allowed = Object.keys(mpForMode)
|
|
135
|
+
.filter(k => k !== 'null')
|
|
136
|
+
.join(', ');
|
|
137
|
+
throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed || '<none>'}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const params = {
|
|
142
|
+
attachments: attachmentsFinal,
|
|
143
|
+
frontend_context_uuid: cryptoRandomUUID(),
|
|
144
|
+
frontend_uuid: cryptoRandomUUID(),
|
|
145
|
+
is_incognito: incognito,
|
|
146
|
+
language,
|
|
147
|
+
last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
|
|
148
|
+
mode: mode === 'auto' ? 'concise' : 'copilot',
|
|
149
|
+
model_preference: modelPref,
|
|
150
|
+
source: 'default',
|
|
151
|
+
sources,
|
|
152
|
+
version: this.version
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
query_str: query,
|
|
157
|
+
params
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Simple helper to generate UUID without depending on node <16 helpers
|
|
162
|
+
async _fetch(url, opts) {
|
|
163
|
+
const res = await request(url, opts);
|
|
164
|
+
const { statusCode, headers, body } = res;
|
|
165
|
+
return { statusCode, headers, body };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async _postJson(url, body) {
|
|
169
|
+
const res = await fetch(url, {
|
|
170
|
+
method: 'POST',
|
|
171
|
+
headers: defaultHeaders(this.cookies),
|
|
172
|
+
body: JSON.stringify(body)
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const text = await res.text();
|
|
176
|
+
if (!res.ok) {
|
|
177
|
+
const err = new Error(`Request failed ${res.status} - ${text.slice(0, 200)}`);
|
|
178
|
+
err.status = res.status;
|
|
179
|
+
throw err;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return text ? JSON.parse(text) : {};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async _uploadFiles(files = {}) {
|
|
186
|
+
const entries = Object.entries(files);
|
|
187
|
+
if (!entries.length) return [];
|
|
188
|
+
|
|
189
|
+
const uploaded = [];
|
|
190
|
+
|
|
191
|
+
for (const [filename, raw] of entries) {
|
|
192
|
+
const mimeType = guessMimeType(filename);
|
|
193
|
+
const data = typeof raw === 'string' ? Buffer.from(raw) : Buffer.from(raw);
|
|
194
|
+
const fileSize = data.byteLength;
|
|
195
|
+
|
|
196
|
+
const uploadInfo = await this._postJson(
|
|
197
|
+
`${this.base}/rest/uploads/create_upload_url?version=${this.version}&source=default`,
|
|
198
|
+
{
|
|
199
|
+
content_type: mimeType,
|
|
200
|
+
file_size: fileSize,
|
|
201
|
+
filename,
|
|
202
|
+
force_image: false,
|
|
203
|
+
source: 'default'
|
|
204
|
+
}
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
const form = new FormData();
|
|
208
|
+
Object.entries(uploadInfo.fields || {}).forEach(([key, value]) => {
|
|
209
|
+
form.append(key, value);
|
|
210
|
+
});
|
|
211
|
+
form.append('file', new Blob([data], { type: mimeType }), filename);
|
|
212
|
+
|
|
213
|
+
const uploadResp = await fetch(uploadInfo.s3_bucket_url, {
|
|
214
|
+
method: 'POST',
|
|
215
|
+
body: form
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
if (!uploadResp.ok) {
|
|
219
|
+
const errText = await uploadResp.text();
|
|
220
|
+
const err = new Error(
|
|
221
|
+
`File upload failed for ${filename}: ${uploadResp.status} - ${errText.slice(0, 200)}`
|
|
222
|
+
);
|
|
223
|
+
err.status = uploadResp.status;
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let uploadedUrl = uploadInfo.s3_object_url;
|
|
228
|
+
if (uploadedUrl && uploadedUrl.includes('image/upload')) {
|
|
229
|
+
try {
|
|
230
|
+
const uploadBody = await uploadResp.json();
|
|
231
|
+
if (uploadBody.secure_url) {
|
|
232
|
+
uploadedUrl = uploadBody.secure_url.replace(
|
|
233
|
+
/\/private\/s--.*?--\/v\d+\/user_uploads\//,
|
|
234
|
+
'/private/user_uploads/'
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
} catch (err) {
|
|
238
|
+
// fall back to provided object url
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
uploaded.push(uploadedUrl);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return uploaded;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Supports both: (query, opts) and positional signature:
|
|
249
|
+
// search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
|
|
250
|
+
async search(...args) {
|
|
251
|
+
let query;
|
|
252
|
+
let opts = {};
|
|
253
|
+
|
|
254
|
+
if (args.length === 0) throw new Error('search requires at least a query string');
|
|
255
|
+
|
|
256
|
+
query = args[0];
|
|
257
|
+
|
|
258
|
+
// If second arg is an object, assume opts form
|
|
259
|
+
if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
|
|
260
|
+
opts = args[1];
|
|
261
|
+
} else if (args.length >= 2) {
|
|
262
|
+
// positional mapping for backwards compatibility
|
|
263
|
+
const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
|
|
264
|
+
opts = { mode, model, sources, files, stream, language, follow_up, incognito };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const uploaded = opts.files && Object.keys(opts.files).length ? await this._uploadFiles(opts.files) : [];
|
|
268
|
+
const payload = this._buildPayload(query, { ...opts, attachments: uploaded });
|
|
269
|
+
const url = `${this.base}/rest/sse/perplexity_ask`;
|
|
270
|
+
|
|
271
|
+
const { statusCode, headers, body } = await this._fetch(url, {
|
|
272
|
+
method: 'POST',
|
|
273
|
+
body: JSON.stringify(payload),
|
|
274
|
+
headers: defaultHeaders(this.cookies)
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
if (statusCode >= 400) {
|
|
278
|
+
const text = await body.text();
|
|
279
|
+
const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
|
|
280
|
+
err.status = statusCode;
|
|
281
|
+
throw err;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// collect SSE messages
|
|
285
|
+
const messages = [];
|
|
286
|
+
for await (const msg of parseSSE(body)) {
|
|
287
|
+
if (msg.event === 'message') {
|
|
288
|
+
let data = msg.data;
|
|
289
|
+
try {
|
|
290
|
+
data = JSON.parse(data);
|
|
291
|
+
} catch (e) {}
|
|
292
|
+
messages.push(parseFinalAnswer(data));
|
|
293
|
+
} else if (msg.event === 'end_of_stream') {
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return messages.length ? messages[messages.length - 1] : null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// streamSearch supports same signatures as search
|
|
302
|
+
async * streamSearch(...args) {
|
|
303
|
+
let query;
|
|
304
|
+
let opts = {};
|
|
305
|
+
|
|
306
|
+
if (args.length === 0) throw new Error('streamSearch requires at least a query string');
|
|
307
|
+
|
|
308
|
+
query = args[0];
|
|
309
|
+
if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
|
|
310
|
+
opts = args[1];
|
|
311
|
+
} else if (args.length >= 2) {
|
|
312
|
+
const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
|
|
313
|
+
opts = { mode, model, sources, files, stream, language, follow_up, incognito };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const uploaded = opts.files && Object.keys(opts.files).length ? await this._uploadFiles(opts.files) : [];
|
|
317
|
+
const payload = this._buildPayload(query, { ...opts, attachments: uploaded });
|
|
318
|
+
const url = `${this.base}/rest/sse/perplexity_ask`;
|
|
319
|
+
|
|
320
|
+
const { statusCode, headers, body } = await this._fetch(url, {
|
|
321
|
+
method: 'POST',
|
|
322
|
+
body: JSON.stringify(payload),
|
|
323
|
+
headers: defaultHeaders(this.cookies)
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
if (statusCode >= 400) {
|
|
327
|
+
const text = await body.text();
|
|
328
|
+
throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
for await (const msg of parseSSE(body)) {
|
|
332
|
+
if (msg.event === 'message') {
|
|
333
|
+
let data = msg.data;
|
|
334
|
+
try {
|
|
335
|
+
data = JSON.parse(data);
|
|
336
|
+
} catch (e) {}
|
|
337
|
+
yield parseFinalAnswer(data);
|
|
338
|
+
} else if (msg.event === 'end_of_stream') {
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function cryptoRandomUUID() {
|
|
346
|
+
// Use global crypto if available
|
|
347
|
+
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
|
|
348
|
+
|
|
349
|
+
// Fallback simple UUID v4 generator
|
|
350
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
|
351
|
+
const r = Math.random() * 16 | 0;
|
|
352
|
+
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
|
353
|
+
return v.toString(16);
|
|
354
|
+
});
|
|
285
355
|
}
|
package/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import PerplexityClient from './client.js';
|
|
2
|
-
|
|
3
|
-
// Provide a convenient alias `Client` to match common naming
|
|
4
|
-
const Client = PerplexityClient;
|
|
5
|
-
|
|
6
|
-
export { PerplexityClient, Client };
|
|
7
|
-
export default PerplexityClient;
|
|
1
|
+
import PerplexityClient from './client.js';
|
|
2
|
+
|
|
3
|
+
// Provide a convenient alias `Client` to match common naming
|
|
4
|
+
const Client = PerplexityClient;
|
|
5
|
+
|
|
6
|
+
export { PerplexityClient, Client };
|
|
7
|
+
export default PerplexityClient;
|
package/src/sseParser.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
// Minimal SSE parser that yields {event, data} objects from a ReadableStream body
|
|
2
|
-
export async function* parseSSE(body) {
|
|
3
|
-
const reader = body[Symbol.asyncIterator] ? body[Symbol.asyncIterator]() : body.getReader();
|
|
4
|
-
|
|
5
|
-
let decoder = new TextDecoder('utf-8');
|
|
6
|
-
let buffer = '';
|
|
7
|
-
|
|
8
|
-
for await (const chunk of body) {
|
|
9
|
-
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, {
|
|
10
|
-
stream: true
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
let idx;
|
|
14
|
-
while ((idx = buffer.indexOf('\r\n\r\n')) !== -1) {
|
|
15
|
-
const raw = buffer.slice(0, idx);
|
|
16
|
-
buffer = buffer.slice(idx + 4);
|
|
17
|
-
|
|
18
|
-
const lines = raw.split(/\r\n/).filter(Boolean);
|
|
19
|
-
let event = 'message';
|
|
20
|
-
let data = '';
|
|
21
|
-
|
|
22
|
-
for (const line of lines) {
|
|
23
|
-
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
24
|
-
else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
yield {
|
|
28
|
-
event,
|
|
29
|
-
data
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (buffer.trim()) {
|
|
35
|
-
// last partial
|
|
36
|
-
const lines = buffer.split(/\r\n/).filter(Boolean);
|
|
37
|
-
let event = 'message';
|
|
38
|
-
let data = '';
|
|
39
|
-
for (const line of lines) {
|
|
40
|
-
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
41
|
-
else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
|
|
42
|
-
}
|
|
43
|
-
yield {
|
|
44
|
-
event,
|
|
45
|
-
data
|
|
46
|
-
};
|
|
47
|
-
}
|
|
1
|
+
// Minimal SSE parser that yields {event, data} objects from a ReadableStream body
|
|
2
|
+
export async function* parseSSE(body) {
|
|
3
|
+
const reader = body[Symbol.asyncIterator] ? body[Symbol.asyncIterator]() : body.getReader();
|
|
4
|
+
|
|
5
|
+
let decoder = new TextDecoder('utf-8');
|
|
6
|
+
let buffer = '';
|
|
7
|
+
|
|
8
|
+
for await (const chunk of body) {
|
|
9
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, {
|
|
10
|
+
stream: true
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
let idx;
|
|
14
|
+
while ((idx = buffer.indexOf('\r\n\r\n')) !== -1) {
|
|
15
|
+
const raw = buffer.slice(0, idx);
|
|
16
|
+
buffer = buffer.slice(idx + 4);
|
|
17
|
+
|
|
18
|
+
const lines = raw.split(/\r\n/).filter(Boolean);
|
|
19
|
+
let event = 'message';
|
|
20
|
+
let data = '';
|
|
21
|
+
|
|
22
|
+
for (const line of lines) {
|
|
23
|
+
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
24
|
+
else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
yield {
|
|
28
|
+
event,
|
|
29
|
+
data
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (buffer.trim()) {
|
|
35
|
+
// last partial
|
|
36
|
+
const lines = buffer.split(/\r\n/).filter(Boolean);
|
|
37
|
+
let event = 'message';
|
|
38
|
+
let data = '';
|
|
39
|
+
for (const line of lines) {
|
|
40
|
+
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
41
|
+
else if (line.startsWith('data:')) data += (data ? '\n' : '') + line.slice(5).trim();
|
|
42
|
+
}
|
|
43
|
+
yield {
|
|
44
|
+
event,
|
|
45
|
+
data
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
48
|
}
|