@perplexity-ai/perplexity_ai 0.7.1 → 0.9.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/CHANGELOG.md +22 -0
- package/README.md +28 -6
- package/client.d.mts +2 -2
- package/client.d.mts.map +1 -1
- package/client.d.ts +2 -2
- package/client.d.ts.map +1 -1
- package/client.js.map +1 -1
- package/client.mjs.map +1 -1
- package/core/streaming.d.mts +33 -0
- package/core/streaming.d.mts.map +1 -0
- package/core/streaming.d.ts +33 -0
- package/core/streaming.d.ts.map +1 -0
- package/core/streaming.js +276 -0
- package/core/streaming.js.map +1 -0
- package/core/streaming.mjs +271 -0
- package/core/streaming.mjs.map +1 -0
- package/internal/decoders/line.d.mts +17 -0
- package/internal/decoders/line.d.mts.map +1 -0
- package/internal/decoders/line.d.ts +17 -0
- package/internal/decoders/line.d.ts.map +1 -0
- package/internal/decoders/line.js +113 -0
- package/internal/decoders/line.js.map +1 -0
- package/internal/decoders/line.mjs +108 -0
- package/internal/decoders/line.mjs.map +1 -0
- package/internal/parse.d.mts.map +1 -1
- package/internal/parse.d.ts.map +1 -1
- package/internal/parse.js +10 -0
- package/internal/parse.js.map +1 -1
- package/internal/parse.mjs +10 -0
- package/internal/parse.mjs.map +1 -1
- package/internal/request-options.d.mts +2 -0
- package/internal/request-options.d.mts.map +1 -1
- package/internal/request-options.d.ts +2 -0
- package/internal/request-options.d.ts.map +1 -1
- package/internal/request-options.js.map +1 -1
- package/internal/request-options.mjs.map +1 -1
- package/internal/to-file.d.mts +1 -1
- package/internal/to-file.d.ts +1 -1
- package/internal/to-file.js +1 -1
- package/internal/to-file.mjs +1 -1
- package/internal/tslib.js +18 -18
- package/package.json +11 -1
- package/resources/async/chat/completions.d.mts +15 -37
- package/resources/async/chat/completions.d.mts.map +1 -1
- package/resources/async/chat/completions.d.ts +15 -37
- package/resources/async/chat/completions.d.ts.map +1 -1
- package/resources/async/chat/completions.js +7 -7
- package/resources/async/chat/completions.js.map +1 -1
- package/resources/async/chat/completions.mjs +7 -7
- package/resources/async/chat/completions.mjs.map +1 -1
- package/resources/chat/chat.d.mts +16 -2
- package/resources/chat/chat.d.mts.map +1 -1
- package/resources/chat/chat.d.ts +16 -2
- package/resources/chat/chat.d.ts.map +1 -1
- package/resources/chat/chat.js.map +1 -1
- package/resources/chat/chat.mjs +1 -1
- package/resources/chat/chat.mjs.map +1 -1
- package/resources/chat/completions.d.mts +23 -17
- package/resources/chat/completions.d.mts.map +1 -1
- package/resources/chat/completions.d.ts +23 -17
- package/resources/chat/completions.d.ts.map +1 -1
- package/resources/chat/completions.js +1 -4
- package/resources/chat/completions.js.map +1 -1
- package/resources/chat/completions.mjs +1 -4
- package/resources/chat/completions.mjs.map +1 -1
- package/resources/chat/index.d.mts +2 -2
- package/resources/chat/index.d.mts.map +1 -1
- package/resources/chat/index.d.ts +2 -2
- package/resources/chat/index.d.ts.map +1 -1
- package/resources/chat/index.js.map +1 -1
- package/resources/chat/index.mjs +1 -1
- package/resources/chat/index.mjs.map +1 -1
- package/resources/index.d.mts +1 -1
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +1 -1
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js.map +1 -1
- package/resources/index.mjs.map +1 -1
- package/resources/search.d.mts +3 -2
- package/resources/search.d.mts.map +1 -1
- package/resources/search.d.ts +3 -2
- package/resources/search.d.ts.map +1 -1
- package/resources/search.js +1 -1
- package/resources/search.mjs +1 -1
- package/resources/shared.d.mts +1 -0
- package/resources/shared.d.mts.map +1 -1
- package/resources/shared.d.ts +1 -0
- package/resources/shared.d.ts.map +1 -1
- package/src/client.ts +2 -2
- package/src/core/streaming.ts +331 -0
- package/src/internal/decoders/line.ts +135 -0
- package/src/internal/parse.ts +14 -0
- package/src/internal/request-options.ts +2 -0
- package/src/internal/to-file.ts +1 -1
- package/src/resources/async/chat/completions.ts +24 -57
- package/src/resources/chat/chat.ts +33 -2
- package/src/resources/chat/completions.ts +44 -27
- package/src/resources/chat/index.ts +7 -2
- package/src/resources/index.ts +1 -1
- package/src/resources/search.ts +4 -2
- package/src/resources/shared.ts +2 -0
- package/src/streaming.ts +2 -0
- package/src/version.ts +1 -1
- package/streaming.d.mts +2 -0
- package/streaming.d.mts.map +1 -0
- package/streaming.d.ts +2 -0
- package/streaming.d.ts.map +1 -0
- package/streaming.js +6 -0
- package/streaming.js.map +1 -0
- package/streaming.mjs +2 -0
- package/streaming.mjs.map +1 -0
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { PerplexityError } from './error';
|
|
2
|
+
import { type ReadableStream } from '../internal/shim-types';
|
|
3
|
+
import { makeReadableStream } from '../internal/shims';
|
|
4
|
+
import { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line';
|
|
5
|
+
import { ReadableStreamToAsyncIterable } from '../internal/shims';
|
|
6
|
+
import { isAbortError } from '../internal/errors';
|
|
7
|
+
import { safeJSON } from '../internal/utils/values';
|
|
8
|
+
import { encodeUTF8 } from '../internal/utils/bytes';
|
|
9
|
+
import { loggerFor } from '../internal/utils/log';
|
|
10
|
+
import type { Perplexity } from '../client';
|
|
11
|
+
|
|
12
|
+
import { APIError } from './error';
|
|
13
|
+
|
|
14
|
+
type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;
|
|
15
|
+
|
|
16
|
+
export type ServerSentEvent = {
|
|
17
|
+
event: string | null;
|
|
18
|
+
data: string;
|
|
19
|
+
raw: string[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export class Stream<Item> implements AsyncIterable<Item> {
|
|
23
|
+
controller: AbortController;
|
|
24
|
+
#client: Perplexity | undefined;
|
|
25
|
+
|
|
26
|
+
constructor(
|
|
27
|
+
private iterator: () => AsyncIterator<Item>,
|
|
28
|
+
controller: AbortController,
|
|
29
|
+
client?: Perplexity,
|
|
30
|
+
) {
|
|
31
|
+
this.controller = controller;
|
|
32
|
+
this.#client = client;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
static fromSSEResponse<Item>(
|
|
36
|
+
response: Response,
|
|
37
|
+
controller: AbortController,
|
|
38
|
+
client?: Perplexity,
|
|
39
|
+
): Stream<Item> {
|
|
40
|
+
let consumed = false;
|
|
41
|
+
const logger = client ? loggerFor(client) : console;
|
|
42
|
+
|
|
43
|
+
async function* iterator(): AsyncIterator<Item, any, undefined> {
|
|
44
|
+
if (consumed) {
|
|
45
|
+
throw new PerplexityError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
46
|
+
}
|
|
47
|
+
consumed = true;
|
|
48
|
+
let done = false;
|
|
49
|
+
try {
|
|
50
|
+
for await (const sse of _iterSSEMessages(response, controller)) {
|
|
51
|
+
if (done) continue;
|
|
52
|
+
|
|
53
|
+
if (sse.data.startsWith('[DONE]')) {
|
|
54
|
+
done = true;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (sse.event === 'error') {
|
|
59
|
+
throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (sse.event === null) {
|
|
63
|
+
try {
|
|
64
|
+
yield JSON.parse(sse.data);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
67
|
+
logger.error(`From chunk:`, sse.raw);
|
|
68
|
+
throw e;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
done = true;
|
|
73
|
+
} catch (e) {
|
|
74
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
75
|
+
if (isAbortError(e)) return;
|
|
76
|
+
throw e;
|
|
77
|
+
} finally {
|
|
78
|
+
// If the user `break`s, abort the ongoing request.
|
|
79
|
+
if (!done) controller.abort();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return new Stream(iterator, controller, client);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Generates a Stream from a newline-separated ReadableStream
|
|
88
|
+
* where each item is a JSON value.
|
|
89
|
+
*/
|
|
90
|
+
static fromReadableStream<Item>(
|
|
91
|
+
readableStream: ReadableStream,
|
|
92
|
+
controller: AbortController,
|
|
93
|
+
client?: Perplexity,
|
|
94
|
+
): Stream<Item> {
|
|
95
|
+
let consumed = false;
|
|
96
|
+
|
|
97
|
+
async function* iterLines(): AsyncGenerator<string, void, unknown> {
|
|
98
|
+
const lineDecoder = new LineDecoder();
|
|
99
|
+
|
|
100
|
+
const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);
|
|
101
|
+
for await (const chunk of iter) {
|
|
102
|
+
for (const line of lineDecoder.decode(chunk)) {
|
|
103
|
+
yield line;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (const line of lineDecoder.flush()) {
|
|
108
|
+
yield line;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function* iterator(): AsyncIterator<Item, any, undefined> {
|
|
113
|
+
if (consumed) {
|
|
114
|
+
throw new PerplexityError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
115
|
+
}
|
|
116
|
+
consumed = true;
|
|
117
|
+
let done = false;
|
|
118
|
+
try {
|
|
119
|
+
for await (const line of iterLines()) {
|
|
120
|
+
if (done) continue;
|
|
121
|
+
if (line) yield JSON.parse(line);
|
|
122
|
+
}
|
|
123
|
+
done = true;
|
|
124
|
+
} catch (e) {
|
|
125
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
126
|
+
if (isAbortError(e)) return;
|
|
127
|
+
throw e;
|
|
128
|
+
} finally {
|
|
129
|
+
// If the user `break`s, abort the ongoing request.
|
|
130
|
+
if (!done) controller.abort();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return new Stream(iterator, controller, client);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
[Symbol.asyncIterator](): AsyncIterator<Item> {
|
|
138
|
+
return this.iterator();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Splits the stream into two streams which can be
|
|
143
|
+
* independently read from at different speeds.
|
|
144
|
+
*/
|
|
145
|
+
tee(): [Stream<Item>, Stream<Item>] {
|
|
146
|
+
const left: Array<Promise<IteratorResult<Item>>> = [];
|
|
147
|
+
const right: Array<Promise<IteratorResult<Item>>> = [];
|
|
148
|
+
const iterator = this.iterator();
|
|
149
|
+
|
|
150
|
+
const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {
|
|
151
|
+
return {
|
|
152
|
+
next: () => {
|
|
153
|
+
if (queue.length === 0) {
|
|
154
|
+
const result = iterator.next();
|
|
155
|
+
left.push(result);
|
|
156
|
+
right.push(result);
|
|
157
|
+
}
|
|
158
|
+
return queue.shift()!;
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
return [
|
|
164
|
+
new Stream(() => teeIterator(left), this.controller, this.#client),
|
|
165
|
+
new Stream(() => teeIterator(right), this.controller, this.#client),
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Converts this stream to a newline-separated ReadableStream of
|
|
171
|
+
* JSON stringified values in the stream
|
|
172
|
+
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
173
|
+
*/
|
|
174
|
+
toReadableStream(): ReadableStream {
|
|
175
|
+
const self = this;
|
|
176
|
+
let iter: AsyncIterator<Item>;
|
|
177
|
+
|
|
178
|
+
return makeReadableStream({
|
|
179
|
+
async start() {
|
|
180
|
+
iter = self[Symbol.asyncIterator]();
|
|
181
|
+
},
|
|
182
|
+
async pull(ctrl: any) {
|
|
183
|
+
try {
|
|
184
|
+
const { value, done } = await iter.next();
|
|
185
|
+
if (done) return ctrl.close();
|
|
186
|
+
|
|
187
|
+
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
|
|
188
|
+
|
|
189
|
+
ctrl.enqueue(bytes);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
ctrl.error(err);
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
async cancel() {
|
|
195
|
+
await iter.return?.();
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function* _iterSSEMessages(
|
|
202
|
+
response: Response,
|
|
203
|
+
controller: AbortController,
|
|
204
|
+
): AsyncGenerator<ServerSentEvent, void, unknown> {
|
|
205
|
+
if (!response.body) {
|
|
206
|
+
controller.abort();
|
|
207
|
+
if (
|
|
208
|
+
typeof (globalThis as any).navigator !== 'undefined' &&
|
|
209
|
+
(globalThis as any).navigator.product === 'ReactNative'
|
|
210
|
+
) {
|
|
211
|
+
throw new PerplexityError(
|
|
212
|
+
`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
throw new PerplexityError(`Attempted to iterate over a response with no body`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const sseDecoder = new SSEDecoder();
|
|
219
|
+
const lineDecoder = new LineDecoder();
|
|
220
|
+
|
|
221
|
+
const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);
|
|
222
|
+
for await (const sseChunk of iterSSEChunks(iter)) {
|
|
223
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
224
|
+
const sse = sseDecoder.decode(line);
|
|
225
|
+
if (sse) yield sse;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
for (const line of lineDecoder.flush()) {
|
|
230
|
+
const sse = sseDecoder.decode(line);
|
|
231
|
+
if (sse) yield sse;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
237
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
238
|
+
*/
|
|
239
|
+
async function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {
|
|
240
|
+
let data = new Uint8Array();
|
|
241
|
+
|
|
242
|
+
for await (const chunk of iterator) {
|
|
243
|
+
if (chunk == null) {
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const binaryChunk =
|
|
248
|
+
chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
249
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
250
|
+
: chunk;
|
|
251
|
+
|
|
252
|
+
let newData = new Uint8Array(data.length + binaryChunk.length);
|
|
253
|
+
newData.set(data);
|
|
254
|
+
newData.set(binaryChunk, data.length);
|
|
255
|
+
data = newData;
|
|
256
|
+
|
|
257
|
+
let patternIndex;
|
|
258
|
+
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
259
|
+
yield data.slice(0, patternIndex);
|
|
260
|
+
data = data.slice(patternIndex);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (data.length > 0) {
|
|
265
|
+
yield data;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
class SSEDecoder {
|
|
270
|
+
private data: string[];
|
|
271
|
+
private event: string | null;
|
|
272
|
+
private chunks: string[];
|
|
273
|
+
|
|
274
|
+
constructor() {
|
|
275
|
+
this.event = null;
|
|
276
|
+
this.data = [];
|
|
277
|
+
this.chunks = [];
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
decode(line: string) {
|
|
281
|
+
if (line.endsWith('\r')) {
|
|
282
|
+
line = line.substring(0, line.length - 1);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (!line) {
|
|
286
|
+
// empty line and we didn't previously encounter any messages
|
|
287
|
+
if (!this.event && !this.data.length) return null;
|
|
288
|
+
|
|
289
|
+
const sse: ServerSentEvent = {
|
|
290
|
+
event: this.event,
|
|
291
|
+
data: this.data.join('\n'),
|
|
292
|
+
raw: this.chunks,
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
this.event = null;
|
|
296
|
+
this.data = [];
|
|
297
|
+
this.chunks = [];
|
|
298
|
+
|
|
299
|
+
return sse;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
this.chunks.push(line);
|
|
303
|
+
|
|
304
|
+
if (line.startsWith(':')) {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
let [fieldname, _, value] = partition(line, ':');
|
|
309
|
+
|
|
310
|
+
if (value.startsWith(' ')) {
|
|
311
|
+
value = value.substring(1);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (fieldname === 'event') {
|
|
315
|
+
this.event = value;
|
|
316
|
+
} else if (fieldname === 'data') {
|
|
317
|
+
this.data.push(value);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function partition(str: string, delimiter: string): [string, string, string] {
|
|
325
|
+
const index = str.indexOf(delimiter);
|
|
326
|
+
if (index !== -1) {
|
|
327
|
+
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return [str, '', ''];
|
|
331
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { concatBytes, decodeUTF8, encodeUTF8 } from '../utils/bytes';
|
|
2
|
+
|
|
3
|
+
export type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
|
|
7
|
+
* reading lines from text.
|
|
8
|
+
*
|
|
9
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
10
|
+
*/
|
|
11
|
+
export class LineDecoder {
|
|
12
|
+
// prettier-ignore
|
|
13
|
+
static NEWLINE_CHARS = new Set(['\n', '\r']);
|
|
14
|
+
static NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
15
|
+
|
|
16
|
+
#buffer: Uint8Array;
|
|
17
|
+
#carriageReturnIndex: number | null;
|
|
18
|
+
|
|
19
|
+
constructor() {
|
|
20
|
+
this.#buffer = new Uint8Array();
|
|
21
|
+
this.#carriageReturnIndex = null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
decode(chunk: Bytes): string[] {
|
|
25
|
+
if (chunk == null) {
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const binaryChunk =
|
|
30
|
+
chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
31
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
32
|
+
: chunk;
|
|
33
|
+
|
|
34
|
+
this.#buffer = concatBytes([this.#buffer, binaryChunk]);
|
|
35
|
+
|
|
36
|
+
const lines: string[] = [];
|
|
37
|
+
let patternIndex;
|
|
38
|
+
while ((patternIndex = findNewlineIndex(this.#buffer, this.#carriageReturnIndex)) != null) {
|
|
39
|
+
if (patternIndex.carriage && this.#carriageReturnIndex == null) {
|
|
40
|
+
// skip until we either get a corresponding `\n`, a new `\r` or nothing
|
|
41
|
+
this.#carriageReturnIndex = patternIndex.index;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// we got double \r or \rtext\n
|
|
46
|
+
if (
|
|
47
|
+
this.#carriageReturnIndex != null &&
|
|
48
|
+
(patternIndex.index !== this.#carriageReturnIndex + 1 || patternIndex.carriage)
|
|
49
|
+
) {
|
|
50
|
+
lines.push(decodeUTF8(this.#buffer.subarray(0, this.#carriageReturnIndex - 1)));
|
|
51
|
+
this.#buffer = this.#buffer.subarray(this.#carriageReturnIndex);
|
|
52
|
+
this.#carriageReturnIndex = null;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const endIndex =
|
|
57
|
+
this.#carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
|
|
58
|
+
|
|
59
|
+
const line = decodeUTF8(this.#buffer.subarray(0, endIndex));
|
|
60
|
+
lines.push(line);
|
|
61
|
+
|
|
62
|
+
this.#buffer = this.#buffer.subarray(patternIndex.index);
|
|
63
|
+
this.#carriageReturnIndex = null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
flush(): string[] {
|
|
70
|
+
if (!this.#buffer.length) {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
return this.decode('\n');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* This function searches the buffer for the end patterns, (\r or \n)
|
|
79
|
+
* and returns an object with the index preceding the matched newline and the
|
|
80
|
+
* index after the newline char. `null` is returned if no new line is found.
|
|
81
|
+
*
|
|
82
|
+
* ```ts
|
|
83
|
+
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
function findNewlineIndex(
|
|
87
|
+
buffer: Uint8Array,
|
|
88
|
+
startIndex: number | null,
|
|
89
|
+
): { preceding: number; index: number; carriage: boolean } | null {
|
|
90
|
+
const newline = 0x0a; // \n
|
|
91
|
+
const carriage = 0x0d; // \r
|
|
92
|
+
|
|
93
|
+
for (let i = startIndex ?? 0; i < buffer.length; i++) {
|
|
94
|
+
if (buffer[i] === newline) {
|
|
95
|
+
return { preceding: i, index: i + 1, carriage: false };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (buffer[i] === carriage) {
|
|
99
|
+
return { preceding: i, index: i + 1, carriage: true };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function findDoubleNewlineIndex(buffer: Uint8Array): number {
|
|
107
|
+
// This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
|
|
108
|
+
// and returns the index right after the first occurrence of any pattern,
|
|
109
|
+
// or -1 if none of the patterns are found.
|
|
110
|
+
const newline = 0x0a; // \n
|
|
111
|
+
const carriage = 0x0d; // \r
|
|
112
|
+
|
|
113
|
+
for (let i = 0; i < buffer.length - 1; i++) {
|
|
114
|
+
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
115
|
+
// \n\n
|
|
116
|
+
return i + 2;
|
|
117
|
+
}
|
|
118
|
+
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
119
|
+
// \r\r
|
|
120
|
+
return i + 2;
|
|
121
|
+
}
|
|
122
|
+
if (
|
|
123
|
+
buffer[i] === carriage &&
|
|
124
|
+
buffer[i + 1] === newline &&
|
|
125
|
+
i + 3 < buffer.length &&
|
|
126
|
+
buffer[i + 2] === carriage &&
|
|
127
|
+
buffer[i + 3] === newline
|
|
128
|
+
) {
|
|
129
|
+
// \r\n\r\n
|
|
130
|
+
return i + 4;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return -1;
|
|
135
|
+
}
|
package/src/internal/parse.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
2
|
|
|
3
3
|
import type { FinalRequestOptions } from './request-options';
|
|
4
|
+
import { Stream } from '../core/streaming';
|
|
4
5
|
import { type Perplexity } from '../client';
|
|
5
6
|
import { formatRequestDetails, loggerFor } from './utils/log';
|
|
6
7
|
|
|
@@ -16,6 +17,19 @@ export type APIResponseProps = {
|
|
|
16
17
|
export async function defaultParseResponse<T>(client: Perplexity, props: APIResponseProps): Promise<T> {
|
|
17
18
|
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
18
19
|
const body = await (async () => {
|
|
20
|
+
if (props.options.stream) {
|
|
21
|
+
loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
|
|
22
|
+
|
|
23
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
24
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
25
|
+
|
|
26
|
+
if (props.options.__streamClass) {
|
|
27
|
+
return props.options.__streamClass.fromSSEResponse(response, props.controller, client) as any;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return Stream.fromSSEResponse(response, props.controller, client) as any;
|
|
31
|
+
}
|
|
32
|
+
|
|
19
33
|
// fetch refuses to read the body when the status code is 204.
|
|
20
34
|
if (response.status === 204) {
|
|
21
35
|
return null as T;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { NullableHeaders } from './headers';
|
|
4
4
|
|
|
5
5
|
import type { BodyInit } from './builtin-types';
|
|
6
|
+
import { Stream } from '../core/streaming';
|
|
6
7
|
import type { HTTPMethod, MergedRequestInit } from './types';
|
|
7
8
|
import { type HeadersLike } from './headers';
|
|
8
9
|
|
|
@@ -76,6 +77,7 @@ export type RequestOptions = {
|
|
|
76
77
|
defaultBaseURL?: string | undefined;
|
|
77
78
|
|
|
78
79
|
__binaryResponse?: boolean | undefined;
|
|
80
|
+
__streamClass?: typeof Stream;
|
|
79
81
|
};
|
|
80
82
|
|
|
81
83
|
export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit };
|
package/src/internal/to-file.ts
CHANGED
|
@@ -73,7 +73,7 @@ export type ToFileInput =
|
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
75
|
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
76
|
-
* @param value the raw content of the file.
|
|
76
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
|
|
77
77
|
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
78
78
|
* @param {Object=} options additional properties
|
|
79
79
|
* @param {string=} options.type the MIME type of the content
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { APIResource } from '../../../core/resource';
|
|
4
4
|
import * as Shared from '../../shared';
|
|
5
|
+
import * as ChatAPI from '../../chat/chat';
|
|
5
6
|
import { APIPromise } from '../../../core/api-promise';
|
|
6
7
|
import { buildHeaders } from '../../../internal/headers';
|
|
7
8
|
import { RequestOptions } from '../../../internal/request-options';
|
|
@@ -9,24 +10,21 @@ import { path } from '../../../internal/utils/path';
|
|
|
9
10
|
|
|
10
11
|
export class Completions extends APIResource {
|
|
11
12
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* This endpoint creates an asynchronous chat completion job and returns a job ID
|
|
15
|
-
* that can be used to poll for results.
|
|
13
|
+
* Submit an asynchronous chat completion request.
|
|
16
14
|
*/
|
|
17
15
|
create(body: CompletionCreateParams, options?: RequestOptions): APIPromise<CompletionCreateResponse> {
|
|
18
16
|
return this._client.post('/async/chat/completions', { body, ...options });
|
|
19
17
|
}
|
|
20
18
|
|
|
21
19
|
/**
|
|
22
|
-
* list all
|
|
20
|
+
* Retrieve a list of all asynchronous chat completion requests for a given user.
|
|
23
21
|
*/
|
|
24
22
|
list(options?: RequestOptions): APIPromise<CompletionListResponse> {
|
|
25
23
|
return this._client.get('/async/chat/completions', options);
|
|
26
24
|
}
|
|
27
25
|
|
|
28
26
|
/**
|
|
29
|
-
*
|
|
27
|
+
* Retrieve the response for a given asynchronous chat completion request.
|
|
30
28
|
*/
|
|
31
29
|
get(
|
|
32
30
|
apiRequest: string,
|
|
@@ -36,6 +34,7 @@ export class Completions extends APIResource {
|
|
|
36
34
|
const {
|
|
37
35
|
'x-client-env': xClientEnv,
|
|
38
36
|
'x-client-name': xClientName,
|
|
37
|
+
'x-created-at-epoch-seconds': xCreatedAtEpochSeconds,
|
|
39
38
|
'x-request-time': xRequestTime,
|
|
40
39
|
'x-usage-tier': xUsageTier,
|
|
41
40
|
'x-user-id': xUserID,
|
|
@@ -48,6 +47,9 @@ export class Completions extends APIResource {
|
|
|
48
47
|
{
|
|
49
48
|
...(xClientEnv != null ? { 'x-client-env': xClientEnv } : undefined),
|
|
50
49
|
...(xClientName != null ? { 'x-client-name': xClientName } : undefined),
|
|
50
|
+
...(xCreatedAtEpochSeconds != null ?
|
|
51
|
+
{ 'x-created-at-epoch-seconds': xCreatedAtEpochSeconds }
|
|
52
|
+
: undefined),
|
|
51
53
|
...(xRequestTime != null ? { 'x-request-time': xRequestTime } : undefined),
|
|
52
54
|
...(xUsageTier != null ? { 'x-usage-tier': xUsageTier } : undefined),
|
|
53
55
|
...(xUserID != null ? { 'x-user-id': xUserID } : undefined),
|
|
@@ -76,35 +78,11 @@ export interface CompletionCreateResponse {
|
|
|
76
78
|
|
|
77
79
|
failed_at?: number | null;
|
|
78
80
|
|
|
79
|
-
response?:
|
|
81
|
+
response?: ChatAPI.StreamChunk | null;
|
|
80
82
|
|
|
81
83
|
started_at?: number | null;
|
|
82
84
|
}
|
|
83
85
|
|
|
84
|
-
export namespace CompletionCreateResponse {
|
|
85
|
-
export interface Response {
|
|
86
|
-
id: string;
|
|
87
|
-
|
|
88
|
-
choices: Array<Shared.Choice>;
|
|
89
|
-
|
|
90
|
-
created: number;
|
|
91
|
-
|
|
92
|
-
model: string;
|
|
93
|
-
|
|
94
|
-
usage: Shared.UsageInfo;
|
|
95
|
-
|
|
96
|
-
citations?: Array<string> | null;
|
|
97
|
-
|
|
98
|
-
object?: string;
|
|
99
|
-
|
|
100
|
-
search_results?: Array<Shared.APIPublicSearchResult> | null;
|
|
101
|
-
|
|
102
|
-
status?: 'PENDING' | 'COMPLETED' | null;
|
|
103
|
-
|
|
104
|
-
type?: 'message' | 'info' | 'end_of_stream' | null;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
86
|
export interface CompletionListResponse {
|
|
109
87
|
requests: Array<CompletionListResponse.Request>;
|
|
110
88
|
|
|
@@ -150,35 +128,11 @@ export interface CompletionGetResponse {
|
|
|
150
128
|
|
|
151
129
|
failed_at?: number | null;
|
|
152
130
|
|
|
153
|
-
response?:
|
|
131
|
+
response?: ChatAPI.StreamChunk | null;
|
|
154
132
|
|
|
155
133
|
started_at?: number | null;
|
|
156
134
|
}
|
|
157
135
|
|
|
158
|
-
export namespace CompletionGetResponse {
|
|
159
|
-
export interface Response {
|
|
160
|
-
id: string;
|
|
161
|
-
|
|
162
|
-
choices: Array<Shared.Choice>;
|
|
163
|
-
|
|
164
|
-
created: number;
|
|
165
|
-
|
|
166
|
-
model: string;
|
|
167
|
-
|
|
168
|
-
usage: Shared.UsageInfo;
|
|
169
|
-
|
|
170
|
-
citations?: Array<string> | null;
|
|
171
|
-
|
|
172
|
-
object?: string;
|
|
173
|
-
|
|
174
|
-
search_results?: Array<Shared.APIPublicSearchResult> | null;
|
|
175
|
-
|
|
176
|
-
status?: 'PENDING' | 'COMPLETED' | null;
|
|
177
|
-
|
|
178
|
-
type?: 'message' | 'info' | 'end_of_stream' | null;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
136
|
export interface CompletionCreateParams {
|
|
183
137
|
request: CompletionCreateParams.Request;
|
|
184
138
|
|
|
@@ -223,6 +177,8 @@ export namespace CompletionCreateParams {
|
|
|
223
177
|
|
|
224
178
|
image_format_filter?: Array<string> | null;
|
|
225
179
|
|
|
180
|
+
language_preference?: string | null;
|
|
181
|
+
|
|
226
182
|
last_updated_after_filter?: string | null;
|
|
227
183
|
|
|
228
184
|
last_updated_before_filter?: string | null;
|
|
@@ -281,8 +237,12 @@ export namespace CompletionCreateParams {
|
|
|
281
237
|
|
|
282
238
|
stream?: boolean | null;
|
|
283
239
|
|
|
240
|
+
stream_mode?: 'full' | 'concise';
|
|
241
|
+
|
|
284
242
|
temperature?: number | null;
|
|
285
243
|
|
|
244
|
+
thread_id?: string | null;
|
|
245
|
+
|
|
286
246
|
tool_choice?: 'none' | 'auto' | 'required' | null;
|
|
287
247
|
|
|
288
248
|
tools?: Array<Request.Tool> | null;
|
|
@@ -297,6 +257,8 @@ export namespace CompletionCreateParams {
|
|
|
297
257
|
|
|
298
258
|
updated_before_timestamp?: number | null;
|
|
299
259
|
|
|
260
|
+
use_threads?: boolean | null;
|
|
261
|
+
|
|
300
262
|
web_search_options?: Request.WebSearchOptions;
|
|
301
263
|
}
|
|
302
264
|
|
|
@@ -382,7 +344,7 @@ export namespace CompletionCreateParams {
|
|
|
382
344
|
|
|
383
345
|
search_context_size?: 'low' | 'medium' | 'high';
|
|
384
346
|
|
|
385
|
-
search_type?: 'fast' | 'pro' | 'auto';
|
|
347
|
+
search_type?: 'fast' | 'pro' | 'auto' | null;
|
|
386
348
|
|
|
387
349
|
user_location?: WebSearchOptions.UserLocation | null;
|
|
388
350
|
}
|
|
@@ -419,6 +381,11 @@ export interface CompletionGetParams {
|
|
|
419
381
|
*/
|
|
420
382
|
'x-client-name'?: string;
|
|
421
383
|
|
|
384
|
+
/**
|
|
385
|
+
* Header param:
|
|
386
|
+
*/
|
|
387
|
+
'x-created-at-epoch-seconds'?: string;
|
|
388
|
+
|
|
422
389
|
/**
|
|
423
390
|
* Header param:
|
|
424
391
|
*/
|