perplex.js 0.1.0
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 +20 -0
- package/README.md +36 -0
- package/package.json +30 -0
- package/src/client.js +285 -0
- package/src/index.js +7 -0
- package/src/sseParser.js +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +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,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +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 https://github.com/xFufly/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
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "perplex.js",
|
|
3
|
+
"version": "0.1.0",
|
|
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": ["perplexity", "perplexity.ai", "ai", "client"],
|
|
23
|
+
"author": "DIDELOT Tim",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"undici": "^6.0.0"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
package/src/client.js
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import {
|
|
2
|
+
request
|
|
3
|
+
} from 'undici';
|
|
4
|
+
import {
|
|
5
|
+
parseSSE
|
|
6
|
+
} from './sseParser.js';
|
|
7
|
+
|
|
8
|
+
function defaultHeaders(cookie) {
|
|
9
|
+
const headers = {
|
|
10
|
+
'accept': 'text/event-stream, text/plain, */*',
|
|
11
|
+
'content-type': 'application/json',
|
|
12
|
+
'user-agent': 'perplexity-js/0.1',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
if (cookie) headers['cookie'] = typeof cookie === 'string' ? cookie : Object.entries(cookie).map(([k, v]) => `${k}=${v}`).join('; ');
|
|
16
|
+
return headers;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export default class PerplexityClient {
|
|
20
|
+
constructor(options = {}) {
|
|
21
|
+
// Perplexity access is done via session cookies (or anonymously). No API key is required.
|
|
22
|
+
this.base = options.base || 'https://www.perplexity.ai';
|
|
23
|
+
this.version = options.version || '2.18';
|
|
24
|
+
// optional cookies: either string or object map
|
|
25
|
+
this.cookies = options.cookies || null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Static mapping of modes -> available models
|
|
29
|
+
static modelMap() {
|
|
30
|
+
return {
|
|
31
|
+
auto: [null],
|
|
32
|
+
pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
|
|
33
|
+
reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking', 'claude37sonnetthinking'],
|
|
34
|
+
'deep research': [null]
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static getAvailableModels(mode) {
|
|
39
|
+
const map = PerplexityClient.modelMap();
|
|
40
|
+
return map[mode] || [];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
static getAvailableModels(mode = 'auto') {
|
|
44
|
+
const modelPreferences = {
|
|
45
|
+
auto: [null],
|
|
46
|
+
pro: [null, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
|
|
47
|
+
reasoning: [null, 'r1', 'o3-mini', 'claude 3.7 sonnet', 'gpt5', 'gpt5_thinking'],
|
|
48
|
+
'deep research': [null]
|
|
49
|
+
};
|
|
50
|
+
return modelPreferences[mode] ?? modelPreferences.auto;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Build the payload for the request
|
|
54
|
+
_buildPayload(query, opts = {}) {
|
|
55
|
+
const {
|
|
56
|
+
mode = 'auto', model = null, sources = ['web'], attachments = [], language = 'en-US', follow_up = null, incognito = false
|
|
57
|
+
} = opts;
|
|
58
|
+
|
|
59
|
+
const attachmentsFinal = attachments.concat(follow_up && follow_up.attachments ? follow_up.attachments : []);
|
|
60
|
+
|
|
61
|
+
const modelPreferences = {
|
|
62
|
+
auto: {
|
|
63
|
+
null: 'turbo'
|
|
64
|
+
},
|
|
65
|
+
pro: {
|
|
66
|
+
null: 'pplx_pro',
|
|
67
|
+
'sonar': 'experimental',
|
|
68
|
+
'gpt-4.5': 'gpt45',
|
|
69
|
+
'gpt-4o': 'gpt4o',
|
|
70
|
+
'claude 3.7 sonnet': 'claude2',
|
|
71
|
+
'gemini 2.0 flash': 'gemini2flash',
|
|
72
|
+
'grok-2': 'grok'
|
|
73
|
+
},
|
|
74
|
+
reasoning: {
|
|
75
|
+
null: 'pplx_reasoning',
|
|
76
|
+
'r1': 'r1',
|
|
77
|
+
'o3-mini': 'o3mini',
|
|
78
|
+
'claude 3.7 sonnet': 'claude37sonnetthinking',
|
|
79
|
+
'gpt5': 'gpt5',
|
|
80
|
+
'gpt5_thinking': 'gpt5thinking'
|
|
81
|
+
},
|
|
82
|
+
'deep research': {
|
|
83
|
+
null: 'pplx_alpha'
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// safe lookup: try to pick the exact key, else fallback to the first available value
|
|
88
|
+
const mpForMode = modelPreferences[mode] || modelPreferences.auto;
|
|
89
|
+
let modelPref = null;
|
|
90
|
+
if (mpForMode) {
|
|
91
|
+
// if model is null, treat as null key
|
|
92
|
+
if (model == null) modelPref = mpForMode.null ?? Object.values(mpForMode)[0];
|
|
93
|
+
else if (Object.prototype.hasOwnProperty.call(mpForMode, model)) modelPref = mpForMode[model];
|
|
94
|
+
else {
|
|
95
|
+
// invalid model for the chosen mode
|
|
96
|
+
const allowed = Object.keys(mpForMode).filter(k => k !== 'null');
|
|
97
|
+
throw new Error(`Invalid model '${model}' for mode '${mode}'. Allowed: ${allowed.join(', ') || '<none>'}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const params = {
|
|
102
|
+
attachments: attachmentsFinal,
|
|
103
|
+
frontend_context_uuid: cryptoRandomUUID(),
|
|
104
|
+
frontend_uuid: cryptoRandomUUID(),
|
|
105
|
+
is_incognito: incognito,
|
|
106
|
+
language,
|
|
107
|
+
last_backend_uuid: follow_up ? follow_up.backend_uuid : null,
|
|
108
|
+
mode: mode === 'auto' ? 'concise' : 'copilot',
|
|
109
|
+
model_preference: modelPref,
|
|
110
|
+
source: 'default',
|
|
111
|
+
sources,
|
|
112
|
+
version: this.version
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
query_str: query,
|
|
117
|
+
params
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Simple helper to generate UUID without depending on node <16 helpers
|
|
122
|
+
async _fetch(url, opts) {
|
|
123
|
+
const res = await request(url, opts);
|
|
124
|
+
const {
|
|
125
|
+
statusCode,
|
|
126
|
+
headers,
|
|
127
|
+
body
|
|
128
|
+
} = res;
|
|
129
|
+
return {
|
|
130
|
+
statusCode,
|
|
131
|
+
headers,
|
|
132
|
+
body
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Supports both: (query, opts) and positional signature:
|
|
137
|
+
// search(query, mode='auto', model=null, sources=['web'], files={}, stream=false, language='en-US', follow_up=null, incognito=false)
|
|
138
|
+
async search(...args) {
|
|
139
|
+
let query;
|
|
140
|
+
let opts = {};
|
|
141
|
+
|
|
142
|
+
if (args.length === 0) throw new Error('search requires at least a query string');
|
|
143
|
+
|
|
144
|
+
query = args[0];
|
|
145
|
+
|
|
146
|
+
// If second arg is an object, assume opts form
|
|
147
|
+
if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
|
|
148
|
+
opts = args[1];
|
|
149
|
+
} else if (args.length >= 2) {
|
|
150
|
+
// positional mapping for backwards compatibility
|
|
151
|
+
const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
|
|
152
|
+
opts = {
|
|
153
|
+
mode,
|
|
154
|
+
model,
|
|
155
|
+
sources,
|
|
156
|
+
files,
|
|
157
|
+
stream,
|
|
158
|
+
language,
|
|
159
|
+
follow_up,
|
|
160
|
+
incognito
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (opts.files && Object.keys(opts.files).length) {
|
|
165
|
+
throw new Error('File upload support is not implemented in this Node client yet');
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const payload = this._buildPayload(query, opts);
|
|
169
|
+
const url = `${this.base}/rest/sse/perplexity_ask`;
|
|
170
|
+
|
|
171
|
+
const {
|
|
172
|
+
statusCode,
|
|
173
|
+
headers,
|
|
174
|
+
body
|
|
175
|
+
} = await this._fetch(url, {
|
|
176
|
+
method: 'POST',
|
|
177
|
+
body: JSON.stringify(payload),
|
|
178
|
+
headers: defaultHeaders(this.cookies)
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
if (statusCode >= 400) {
|
|
182
|
+
const text = await body.text();
|
|
183
|
+
const err = new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
|
|
184
|
+
err.status = statusCode;
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// collect SSE messages
|
|
189
|
+
const messages = [];
|
|
190
|
+
for await (const msg of parseSSE(body)) {
|
|
191
|
+
if (msg.event === 'message') {
|
|
192
|
+
let data = msg.data;
|
|
193
|
+
try {
|
|
194
|
+
data = JSON.parse(data);
|
|
195
|
+
} catch (e) {}
|
|
196
|
+
if (data && data.text) {
|
|
197
|
+
try {
|
|
198
|
+
data.text = JSON.parse(data.text);
|
|
199
|
+
} catch (e) {}
|
|
200
|
+
}
|
|
201
|
+
messages.push(data);
|
|
202
|
+
} else if (msg.event === 'end_of_stream') {
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return messages.length ? messages[messages.length - 1] : null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// streamSearch supports same signatures as search
|
|
211
|
+
async * streamSearch(...args) {
|
|
212
|
+
let query;
|
|
213
|
+
let opts = {};
|
|
214
|
+
|
|
215
|
+
if (args.length === 0) throw new Error('streamSearch requires at least a query string');
|
|
216
|
+
|
|
217
|
+
query = args[0];
|
|
218
|
+
if (args.length >= 2 && typeof args[1] === 'object' && !Array.isArray(args[1])) {
|
|
219
|
+
opts = args[1];
|
|
220
|
+
} else if (args.length >= 2) {
|
|
221
|
+
const [, mode = 'auto', model = null, sources = ['web'], files = {}, stream = false, language = 'en-US', follow_up = null, incognito = false] = args;
|
|
222
|
+
opts = {
|
|
223
|
+
mode,
|
|
224
|
+
model,
|
|
225
|
+
sources,
|
|
226
|
+
files,
|
|
227
|
+
stream,
|
|
228
|
+
language,
|
|
229
|
+
follow_up,
|
|
230
|
+
incognito
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (opts.files && Object.keys(opts.files).length) {
|
|
235
|
+
throw new Error('File upload support is not implemented in this Node client yet');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const payload = this._buildPayload(query, opts);
|
|
239
|
+
const url = `${this.base}/rest/sse/perplexity_ask`;
|
|
240
|
+
|
|
241
|
+
const {
|
|
242
|
+
statusCode,
|
|
243
|
+
headers,
|
|
244
|
+
body
|
|
245
|
+
} = await this._fetch(url, {
|
|
246
|
+
method: 'POST',
|
|
247
|
+
body: JSON.stringify(payload),
|
|
248
|
+
headers: defaultHeaders(this.cookies)
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
if (statusCode >= 400) {
|
|
252
|
+
const text = await body.text();
|
|
253
|
+
throw new Error(`Request failed ${statusCode} - ${text.slice(0, 200)}`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
for await (const msg of parseSSE(body)) {
|
|
257
|
+
if (msg.event === 'message') {
|
|
258
|
+
let data = msg.data;
|
|
259
|
+
try {
|
|
260
|
+
data = JSON.parse(data);
|
|
261
|
+
} catch (e) {}
|
|
262
|
+
if (data && data.text) {
|
|
263
|
+
try {
|
|
264
|
+
data.text = JSON.parse(data.text);
|
|
265
|
+
} catch (e) {}
|
|
266
|
+
}
|
|
267
|
+
yield data;
|
|
268
|
+
} else if (msg.event === 'end_of_stream') {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function cryptoRandomUUID() {
|
|
276
|
+
// Use global crypto if available
|
|
277
|
+
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
|
|
278
|
+
|
|
279
|
+
// Fallback simple UUID v4 generator
|
|
280
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
|
281
|
+
const r = Math.random() * 16 | 0;
|
|
282
|
+
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
|
283
|
+
return v.toString(16);
|
|
284
|
+
});
|
|
285
|
+
}
|
package/src/index.js
ADDED
package/src/sseParser.js
ADDED
|
@@ -0,0 +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
|
+
}
|
|
48
|
+
}
|