@perplexity-ai/perplexity_ai 0.7.1 → 0.8.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 +8 -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/tslib.js +18 -18
- package/package.json +11 -1
- package/resources/async/chat/completions.d.mts +3 -30
- package/resources/async/chat/completions.d.mts.map +1 -1
- package/resources/async/chat/completions.d.ts +3 -30
- package/resources/async/chat/completions.d.ts.map +1 -1
- package/resources/async/chat/completions.js.map +1 -1
- 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 +17 -15
- package/resources/chat/completions.d.mts.map +1 -1
- package/resources/chat/completions.d.ts +17 -15
- 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/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/resources/async/chat/completions.ts +3 -50
- package/src/resources/chat/chat.ts +33 -2
- package/src/resources/chat/completions.ts +34 -25
- package/src/resources/chat/index.ts +7 -2
- package/src/resources/index.ts +1 -1
- 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 };
|
|
@@ -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';
|
|
@@ -76,35 +77,11 @@ export interface CompletionCreateResponse {
|
|
|
76
77
|
|
|
77
78
|
failed_at?: number | null;
|
|
78
79
|
|
|
79
|
-
response?:
|
|
80
|
+
response?: ChatAPI.StreamChunk | null;
|
|
80
81
|
|
|
81
82
|
started_at?: number | null;
|
|
82
83
|
}
|
|
83
84
|
|
|
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
85
|
export interface CompletionListResponse {
|
|
109
86
|
requests: Array<CompletionListResponse.Request>;
|
|
110
87
|
|
|
@@ -150,35 +127,11 @@ export interface CompletionGetResponse {
|
|
|
150
127
|
|
|
151
128
|
failed_at?: number | null;
|
|
152
129
|
|
|
153
|
-
response?:
|
|
130
|
+
response?: ChatAPI.StreamChunk | null;
|
|
154
131
|
|
|
155
132
|
started_at?: number | null;
|
|
156
133
|
}
|
|
157
134
|
|
|
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
135
|
export interface CompletionCreateParams {
|
|
183
136
|
request: CompletionCreateParams.Request;
|
|
184
137
|
|
|
@@ -1,19 +1,50 @@
|
|
|
1
1
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
2
|
|
|
3
3
|
import { APIResource } from '../../core/resource';
|
|
4
|
+
import * as Shared from '../shared';
|
|
4
5
|
import * as CompletionsAPI from './completions';
|
|
5
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
CompletionCreateParams,
|
|
8
|
+
CompletionCreateParamsNonStreaming,
|
|
9
|
+
CompletionCreateParamsStreaming,
|
|
10
|
+
Completions,
|
|
11
|
+
} from './completions';
|
|
6
12
|
|
|
7
13
|
export class Chat extends APIResource {
|
|
8
14
|
completions: CompletionsAPI.Completions = new CompletionsAPI.Completions(this._client);
|
|
9
15
|
}
|
|
10
16
|
|
|
17
|
+
export interface StreamChunk {
|
|
18
|
+
id: string;
|
|
19
|
+
|
|
20
|
+
choices: Array<Shared.Choice>;
|
|
21
|
+
|
|
22
|
+
created: number;
|
|
23
|
+
|
|
24
|
+
model: string;
|
|
25
|
+
|
|
26
|
+
usage: Shared.UsageInfo;
|
|
27
|
+
|
|
28
|
+
citations?: Array<string> | null;
|
|
29
|
+
|
|
30
|
+
object?: string;
|
|
31
|
+
|
|
32
|
+
search_results?: Array<Shared.APIPublicSearchResult> | null;
|
|
33
|
+
|
|
34
|
+
status?: 'PENDING' | 'COMPLETED' | null;
|
|
35
|
+
|
|
36
|
+
type?: 'message' | 'info' | 'end_of_stream' | null;
|
|
37
|
+
}
|
|
38
|
+
|
|
11
39
|
Chat.Completions = Completions;
|
|
12
40
|
|
|
13
41
|
export declare namespace Chat {
|
|
42
|
+
export { type StreamChunk as StreamChunk };
|
|
43
|
+
|
|
14
44
|
export {
|
|
15
45
|
Completions as Completions,
|
|
16
|
-
type CompletionCreateResponse as CompletionCreateResponse,
|
|
17
46
|
type CompletionCreateParams as CompletionCreateParams,
|
|
47
|
+
type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming,
|
|
48
|
+
type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming,
|
|
18
49
|
};
|
|
19
50
|
}
|