ai 2.2.29 → 2.2.30
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/dist/index.d.ts +310 -130
- package/dist/index.js +705 -554
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +706 -556
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -4
- package/prompts/dist/index.d.ts +23 -2
- package/prompts/dist/index.js +14 -0
- package/prompts/dist/index.js.map +1 -1
- package/prompts/dist/index.mjs +14 -0
- package/prompts/dist/index.mjs.map +1 -1
- package/react/dist/index.d.ts +92 -10
- package/react/dist/index.js +121 -11
- package/react/dist/index.js.map +1 -1
- package/react/dist/index.mjs +121 -11
- package/react/dist/index.mjs.map +1 -1
- package/solid/dist/index.d.ts +61 -6
- package/solid/dist/index.js +136 -21
- package/solid/dist/index.js.map +1 -1
- package/solid/dist/index.mjs +136 -21
- package/solid/dist/index.mjs.map +1 -1
- package/svelte/dist/index.d.ts +52 -3
- package/svelte/dist/index.js +163 -25
- package/svelte/dist/index.js.map +1 -1
- package/svelte/dist/index.mjs +163 -25
- package/svelte/dist/index.mjs.map +1 -1
- package/vue/dist/index.d.ts +60 -5
- package/vue/dist/index.js +135 -20
- package/vue/dist/index.js.map +1 -1
- package/vue/dist/index.mjs +135 -20
- package/vue/dist/index.mjs.map +1 -1
package/dist/index.mjs
CHANGED
@@ -1,120 +1,5 @@
|
|
1
|
-
//
|
2
|
-
import {
|
3
|
-
createParser
|
4
|
-
} from "eventsource-parser";
|
5
|
-
function createEventStreamTransformer(customParser) {
|
6
|
-
const textDecoder = new TextDecoder();
|
7
|
-
let eventSourceParser;
|
8
|
-
return new TransformStream({
|
9
|
-
async start(controller) {
|
10
|
-
eventSourceParser = createParser(
|
11
|
-
(event) => {
|
12
|
-
if ("data" in event && event.type === "event" && event.data === "[DONE]" || // Replicate doesn't send [DONE] but does send a 'done' event
|
13
|
-
// @see https://replicate.com/docs/streaming
|
14
|
-
event.event === "done") {
|
15
|
-
controller.terminate();
|
16
|
-
return;
|
17
|
-
}
|
18
|
-
if ("data" in event) {
|
19
|
-
const parsedMessage = customParser ? customParser(event.data) : event.data;
|
20
|
-
if (parsedMessage)
|
21
|
-
controller.enqueue(parsedMessage);
|
22
|
-
}
|
23
|
-
}
|
24
|
-
);
|
25
|
-
},
|
26
|
-
transform(chunk) {
|
27
|
-
eventSourceParser.feed(textDecoder.decode(chunk));
|
28
|
-
}
|
29
|
-
});
|
30
|
-
}
|
31
|
-
function createCallbacksTransformer(cb) {
|
32
|
-
const textEncoder = new TextEncoder();
|
33
|
-
let aggregatedResponse = "";
|
34
|
-
const callbacks = cb || {};
|
35
|
-
return new TransformStream({
|
36
|
-
async start() {
|
37
|
-
if (callbacks.onStart)
|
38
|
-
await callbacks.onStart();
|
39
|
-
},
|
40
|
-
async transform(message, controller) {
|
41
|
-
controller.enqueue(textEncoder.encode(message));
|
42
|
-
aggregatedResponse += message;
|
43
|
-
if (callbacks.onToken)
|
44
|
-
await callbacks.onToken(message);
|
45
|
-
},
|
46
|
-
async flush() {
|
47
|
-
const isOpenAICallbacks = isOfTypeOpenAIStreamCallbacks(callbacks);
|
48
|
-
if (callbacks.onCompletion) {
|
49
|
-
await callbacks.onCompletion(aggregatedResponse);
|
50
|
-
}
|
51
|
-
if (callbacks.onFinal && !isOpenAICallbacks) {
|
52
|
-
await callbacks.onFinal(aggregatedResponse);
|
53
|
-
}
|
54
|
-
}
|
55
|
-
});
|
56
|
-
}
|
57
|
-
function isOfTypeOpenAIStreamCallbacks(callbacks) {
|
58
|
-
return "experimental_onFunctionCall" in callbacks;
|
59
|
-
}
|
60
|
-
function trimStartOfStreamHelper() {
|
61
|
-
let isStreamStart = true;
|
62
|
-
return (text) => {
|
63
|
-
if (isStreamStart) {
|
64
|
-
text = text.trimStart();
|
65
|
-
if (text)
|
66
|
-
isStreamStart = false;
|
67
|
-
}
|
68
|
-
return text;
|
69
|
-
};
|
70
|
-
}
|
71
|
-
function AIStream(response, customParser, callbacks) {
|
72
|
-
if (!response.ok) {
|
73
|
-
if (response.body) {
|
74
|
-
const reader = response.body.getReader();
|
75
|
-
return new ReadableStream({
|
76
|
-
async start(controller) {
|
77
|
-
const { done, value } = await reader.read();
|
78
|
-
if (!done) {
|
79
|
-
const errorText = new TextDecoder().decode(value);
|
80
|
-
controller.error(new Error(`Response error: ${errorText}`));
|
81
|
-
}
|
82
|
-
}
|
83
|
-
});
|
84
|
-
} else {
|
85
|
-
return new ReadableStream({
|
86
|
-
start(controller) {
|
87
|
-
controller.error(new Error("Response error: No response body"));
|
88
|
-
}
|
89
|
-
});
|
90
|
-
}
|
91
|
-
}
|
92
|
-
const responseBodyStream = response.body || createEmptyReadableStream();
|
93
|
-
return responseBodyStream.pipeThrough(createEventStreamTransformer(customParser)).pipeThrough(createCallbacksTransformer(callbacks));
|
94
|
-
}
|
95
|
-
function createEmptyReadableStream() {
|
96
|
-
return new ReadableStream({
|
97
|
-
start(controller) {
|
98
|
-
controller.close();
|
99
|
-
}
|
100
|
-
});
|
101
|
-
}
|
102
|
-
function readableFromAsyncIterable(iterable) {
|
103
|
-
let it = iterable[Symbol.asyncIterator]();
|
104
|
-
return new ReadableStream({
|
105
|
-
async pull(controller) {
|
106
|
-
const { done, value } = await it.next();
|
107
|
-
if (done)
|
108
|
-
controller.close();
|
109
|
-
else
|
110
|
-
controller.enqueue(value);
|
111
|
-
},
|
112
|
-
async cancel(reason) {
|
113
|
-
var _a;
|
114
|
-
await ((_a = it.return) == null ? void 0 : _a.call(it, reason));
|
115
|
-
}
|
116
|
-
});
|
117
|
-
}
|
1
|
+
// shared/utils.ts
|
2
|
+
import { customAlphabet } from "nanoid/non-secure";
|
118
3
|
|
119
4
|
// shared/stream-parts.ts
|
120
5
|
var textStreamPart = {
|
@@ -212,6 +97,23 @@ var dataMessageStreamPart = {
|
|
212
97
|
};
|
213
98
|
}
|
214
99
|
};
|
100
|
+
var toolCallStreamPart = {
|
101
|
+
code: "7",
|
102
|
+
name: "tool_calls",
|
103
|
+
parse: (value) => {
|
104
|
+
if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some((tc) => {
|
105
|
+
tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string";
|
106
|
+
})) {
|
107
|
+
throw new Error(
|
108
|
+
'"tool_calls" parts expect an object with a ToolCallPayload.'
|
109
|
+
);
|
110
|
+
}
|
111
|
+
return {
|
112
|
+
type: "tool_calls",
|
113
|
+
value
|
114
|
+
};
|
115
|
+
}
|
116
|
+
};
|
215
117
|
var streamParts = [
|
216
118
|
textStreamPart,
|
217
119
|
functionCallStreamPart,
|
@@ -219,7 +121,8 @@ var streamParts = [
|
|
219
121
|
errorStreamPart,
|
220
122
|
assistantMessageStreamPart,
|
221
123
|
assistantControlDataStreamPart,
|
222
|
-
dataMessageStreamPart
|
124
|
+
dataMessageStreamPart,
|
125
|
+
toolCallStreamPart
|
223
126
|
];
|
224
127
|
var streamPartsByCode = {
|
225
128
|
[textStreamPart.code]: textStreamPart,
|
@@ -228,7 +131,8 @@ var streamPartsByCode = {
|
|
228
131
|
[errorStreamPart.code]: errorStreamPart,
|
229
132
|
[assistantMessageStreamPart.code]: assistantMessageStreamPart,
|
230
133
|
[assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
|
231
|
-
[dataMessageStreamPart.code]: dataMessageStreamPart
|
134
|
+
[dataMessageStreamPart.code]: dataMessageStreamPart,
|
135
|
+
[toolCallStreamPart.code]: toolCallStreamPart
|
232
136
|
};
|
233
137
|
var StreamStringPrefixes = {
|
234
138
|
[textStreamPart.name]: textStreamPart.code,
|
@@ -237,7 +141,8 @@ var StreamStringPrefixes = {
|
|
237
141
|
[errorStreamPart.name]: errorStreamPart.code,
|
238
142
|
[assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
|
239
143
|
[assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
|
240
|
-
[dataMessageStreamPart.name]: dataMessageStreamPart.code
|
144
|
+
[dataMessageStreamPart.name]: dataMessageStreamPart.code,
|
145
|
+
[toolCallStreamPart.name]: toolCallStreamPart.code
|
241
146
|
};
|
242
147
|
var validCodes = streamParts.map((part) => part.code);
|
243
148
|
var parseStreamPart = (line) => {
|
@@ -263,135 +168,7 @@ function formatStreamPart(type, value) {
|
|
263
168
|
`;
|
264
169
|
}
|
265
170
|
|
266
|
-
// streams/stream-data.ts
|
267
|
-
var experimental_StreamData = class {
|
268
|
-
constructor() {
|
269
|
-
this.encoder = new TextEncoder();
|
270
|
-
this.controller = null;
|
271
|
-
// closing the stream is synchronous, but we want to return a promise
|
272
|
-
// in case we're doing async work
|
273
|
-
this.isClosedPromise = null;
|
274
|
-
this.isClosedPromiseResolver = void 0;
|
275
|
-
this.isClosed = false;
|
276
|
-
// array to store appended data
|
277
|
-
this.data = [];
|
278
|
-
this.isClosedPromise = new Promise((resolve) => {
|
279
|
-
this.isClosedPromiseResolver = resolve;
|
280
|
-
});
|
281
|
-
const self = this;
|
282
|
-
this.stream = new TransformStream({
|
283
|
-
start: async (controller) => {
|
284
|
-
self.controller = controller;
|
285
|
-
},
|
286
|
-
transform: async (chunk, controller) => {
|
287
|
-
if (self.data.length > 0) {
|
288
|
-
const encodedData = self.encoder.encode(
|
289
|
-
formatStreamPart("data", self.data)
|
290
|
-
);
|
291
|
-
self.data = [];
|
292
|
-
controller.enqueue(encodedData);
|
293
|
-
}
|
294
|
-
controller.enqueue(chunk);
|
295
|
-
},
|
296
|
-
async flush(controller) {
|
297
|
-
const warningTimeout = process.env.NODE_ENV === "development" ? setTimeout(() => {
|
298
|
-
console.warn(
|
299
|
-
"The data stream is hanging. Did you forget to close it with `data.close()`?"
|
300
|
-
);
|
301
|
-
}, 3e3) : null;
|
302
|
-
await self.isClosedPromise;
|
303
|
-
if (warningTimeout !== null) {
|
304
|
-
clearTimeout(warningTimeout);
|
305
|
-
}
|
306
|
-
if (self.data.length) {
|
307
|
-
const encodedData = self.encoder.encode(
|
308
|
-
formatStreamPart("data", self.data)
|
309
|
-
);
|
310
|
-
controller.enqueue(encodedData);
|
311
|
-
}
|
312
|
-
}
|
313
|
-
});
|
314
|
-
}
|
315
|
-
async close() {
|
316
|
-
var _a;
|
317
|
-
if (this.isClosed) {
|
318
|
-
throw new Error("Data Stream has already been closed.");
|
319
|
-
}
|
320
|
-
if (!this.controller) {
|
321
|
-
throw new Error("Stream controller is not initialized.");
|
322
|
-
}
|
323
|
-
(_a = this.isClosedPromiseResolver) == null ? void 0 : _a.call(this);
|
324
|
-
this.isClosed = true;
|
325
|
-
}
|
326
|
-
append(value) {
|
327
|
-
if (this.isClosed) {
|
328
|
-
throw new Error("Data Stream has already been closed.");
|
329
|
-
}
|
330
|
-
this.data.push(value);
|
331
|
-
}
|
332
|
-
};
|
333
|
-
function createStreamDataTransformer(experimental_streamData) {
|
334
|
-
if (!experimental_streamData) {
|
335
|
-
return new TransformStream({
|
336
|
-
transform: async (chunk, controller) => {
|
337
|
-
controller.enqueue(chunk);
|
338
|
-
}
|
339
|
-
});
|
340
|
-
}
|
341
|
-
const encoder = new TextEncoder();
|
342
|
-
const decoder = new TextDecoder();
|
343
|
-
return new TransformStream({
|
344
|
-
transform: async (chunk, controller) => {
|
345
|
-
const message = decoder.decode(chunk);
|
346
|
-
controller.enqueue(encoder.encode(formatStreamPart("text", message)));
|
347
|
-
}
|
348
|
-
});
|
349
|
-
}
|
350
|
-
|
351
|
-
// streams/aws-bedrock-stream.ts
|
352
|
-
async function* asDeltaIterable(response, extractTextDeltaFromChunk) {
|
353
|
-
var _a, _b;
|
354
|
-
const decoder = new TextDecoder();
|
355
|
-
for await (const chunk of (_a = response.body) != null ? _a : []) {
|
356
|
-
const bytes = (_b = chunk.chunk) == null ? void 0 : _b.bytes;
|
357
|
-
if (bytes != null) {
|
358
|
-
const chunkText = decoder.decode(bytes);
|
359
|
-
const chunkJSON = JSON.parse(chunkText);
|
360
|
-
const delta = extractTextDeltaFromChunk(chunkJSON);
|
361
|
-
if (delta != null) {
|
362
|
-
yield delta;
|
363
|
-
}
|
364
|
-
}
|
365
|
-
}
|
366
|
-
}
|
367
|
-
function AWSBedrockAnthropicStream(response, callbacks) {
|
368
|
-
return AWSBedrockStream(response, callbacks, (chunk) => chunk.completion);
|
369
|
-
}
|
370
|
-
function AWSBedrockCohereStream(response, callbacks) {
|
371
|
-
return AWSBedrockStream(
|
372
|
-
response,
|
373
|
-
callbacks,
|
374
|
-
// As of 2023-11-17, Bedrock does not support streaming for Cohere,
|
375
|
-
// so we take the full generation:
|
376
|
-
(chunk) => {
|
377
|
-
var _a, _b;
|
378
|
-
return (_b = (_a = chunk.generations) == null ? void 0 : _a[0]) == null ? void 0 : _b.text;
|
379
|
-
}
|
380
|
-
);
|
381
|
-
}
|
382
|
-
function AWSBedrockLlama2Stream(response, callbacks) {
|
383
|
-
return AWSBedrockStream(response, callbacks, (chunk) => chunk.generation);
|
384
|
-
}
|
385
|
-
function AWSBedrockStream(response, callbacks, extractTextDeltaFromChunk) {
|
386
|
-
return readableFromAsyncIterable(
|
387
|
-
asDeltaIterable(response, extractTextDeltaFromChunk)
|
388
|
-
).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
|
389
|
-
createStreamDataTransformer(callbacks == null ? void 0 : callbacks.experimental_streamData)
|
390
|
-
);
|
391
|
-
}
|
392
|
-
|
393
171
|
// shared/utils.ts
|
394
|
-
import { customAlphabet } from "nanoid/non-secure";
|
395
172
|
var nanoid = customAlphabet(
|
396
173
|
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
397
174
|
7
|
@@ -413,255 +190,348 @@ function createChunkDecoder(complex) {
|
|
413
190
|
var isStreamStringEqualToType = (type, value) => value.startsWith(`${StreamStringPrefixes[type]}:`) && value.endsWith("\n");
|
414
191
|
var COMPLEX_HEADER = "X-Experimental-Stream-Data";
|
415
192
|
|
416
|
-
// streams/
|
417
|
-
|
418
|
-
|
419
|
-
|
420
|
-
|
421
|
-
|
193
|
+
// streams/ai-stream.ts
|
194
|
+
import {
|
195
|
+
createParser
|
196
|
+
} from "eventsource-parser";
|
197
|
+
function createEventStreamTransformer(customParser) {
|
198
|
+
const textDecoder = new TextDecoder();
|
199
|
+
let eventSourceParser;
|
200
|
+
return new TransformStream({
|
201
|
+
async start(controller) {
|
202
|
+
eventSourceParser = createParser(
|
203
|
+
(event) => {
|
204
|
+
if ("data" in event && event.type === "event" && event.data === "[DONE]" || // Replicate doesn't send [DONE] but does send a 'done' event
|
205
|
+
// @see https://replicate.com/docs/streaming
|
206
|
+
event.event === "done") {
|
207
|
+
controller.terminate();
|
208
|
+
return;
|
209
|
+
}
|
210
|
+
if ("data" in event) {
|
211
|
+
const parsedMessage = customParser ? customParser(event.data) : event.data;
|
212
|
+
if (parsedMessage)
|
213
|
+
controller.enqueue(parsedMessage);
|
214
|
+
}
|
215
|
+
}
|
216
|
+
);
|
217
|
+
},
|
218
|
+
transform(chunk) {
|
219
|
+
eventSourceParser.feed(textDecoder.decode(chunk));
|
220
|
+
}
|
221
|
+
});
|
422
222
|
}
|
423
|
-
|
424
|
-
const
|
425
|
-
|
426
|
-
|
427
|
-
|
428
|
-
|
429
|
-
|
223
|
+
function createCallbacksTransformer(cb) {
|
224
|
+
const textEncoder = new TextEncoder();
|
225
|
+
let aggregatedResponse = "";
|
226
|
+
const callbacks = cb || {};
|
227
|
+
return new TransformStream({
|
228
|
+
async start() {
|
229
|
+
if (callbacks.onStart)
|
230
|
+
await callbacks.onStart();
|
231
|
+
},
|
232
|
+
async transform(message, controller) {
|
233
|
+
controller.enqueue(textEncoder.encode(message));
|
234
|
+
aggregatedResponse += message;
|
235
|
+
if (callbacks.onToken)
|
236
|
+
await callbacks.onToken(message);
|
237
|
+
},
|
238
|
+
async flush() {
|
239
|
+
const isOpenAICallbacks = isOfTypeOpenAIStreamCallbacks(callbacks);
|
240
|
+
if (callbacks.onCompletion) {
|
241
|
+
await callbacks.onCompletion(aggregatedResponse);
|
242
|
+
}
|
243
|
+
if (callbacks.onFinal && !isOpenAICallbacks) {
|
244
|
+
await callbacks.onFinal(aggregatedResponse);
|
245
|
+
}
|
246
|
+
}
|
247
|
+
});
|
430
248
|
}
|
431
|
-
function
|
432
|
-
|
433
|
-
|
434
|
-
|
435
|
-
|
436
|
-
|
437
|
-
|
438
|
-
|
439
|
-
|
440
|
-
|
441
|
-
let escapedPartialJson = argumentChunk.replace(/\\/g, "\\\\").replace(/\//g, "\\/").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\f/g, "\\f");
|
442
|
-
return `${escapedPartialJson}`;
|
443
|
-
} else if (isFunctionStreamingIn && (((_i = json.choices[0]) == null ? void 0 : _i.finish_reason) === "function_call" || ((_j = json.choices[0]) == null ? void 0 : _j.finish_reason) === "stop")) {
|
444
|
-
isFunctionStreamingIn = false;
|
445
|
-
return '"}}';
|
249
|
+
function isOfTypeOpenAIStreamCallbacks(callbacks) {
|
250
|
+
return "experimental_onFunctionCall" in callbacks;
|
251
|
+
}
|
252
|
+
function trimStartOfStreamHelper() {
|
253
|
+
let isStreamStart = true;
|
254
|
+
return (text) => {
|
255
|
+
if (isStreamStart) {
|
256
|
+
text = text.trimStart();
|
257
|
+
if (text)
|
258
|
+
isStreamStart = false;
|
446
259
|
}
|
447
|
-
const text = trimStartOfStream(
|
448
|
-
isChatCompletionChunk(json) && json.choices[0].delta.content ? json.choices[0].delta.content : isCompletion(json) ? json.choices[0].text : ""
|
449
|
-
);
|
450
260
|
return text;
|
451
261
|
};
|
452
262
|
}
|
453
|
-
|
454
|
-
|
455
|
-
)
|
456
|
-
|
457
|
-
|
263
|
+
function AIStream(response, customParser, callbacks) {
|
264
|
+
if (!response.ok) {
|
265
|
+
if (response.body) {
|
266
|
+
const reader = response.body.getReader();
|
267
|
+
return new ReadableStream({
|
268
|
+
async start(controller) {
|
269
|
+
const { done, value } = await reader.read();
|
270
|
+
if (!done) {
|
271
|
+
const errorText = new TextDecoder().decode(value);
|
272
|
+
controller.error(new Error(`Response error: ${errorText}`));
|
273
|
+
}
|
274
|
+
}
|
275
|
+
});
|
276
|
+
} else {
|
277
|
+
return new ReadableStream({
|
278
|
+
start(controller) {
|
279
|
+
controller.error(new Error("Response error: No response body"));
|
280
|
+
}
|
281
|
+
});
|
282
|
+
}
|
283
|
+
}
|
284
|
+
const responseBodyStream = response.body || createEmptyReadableStream();
|
285
|
+
return responseBodyStream.pipeThrough(createEventStreamTransformer(customParser)).pipeThrough(createCallbacksTransformer(callbacks));
|
458
286
|
}
|
459
|
-
function
|
460
|
-
return
|
287
|
+
function createEmptyReadableStream() {
|
288
|
+
return new ReadableStream({
|
289
|
+
start(controller) {
|
290
|
+
controller.close();
|
291
|
+
}
|
292
|
+
});
|
461
293
|
}
|
462
|
-
function
|
463
|
-
|
464
|
-
|
465
|
-
|
466
|
-
|
467
|
-
|
468
|
-
(
|
469
|
-
|
470
|
-
|
471
|
-
|
472
|
-
|
294
|
+
function readableFromAsyncIterable(iterable) {
|
295
|
+
let it = iterable[Symbol.asyncIterator]();
|
296
|
+
return new ReadableStream({
|
297
|
+
async pull(controller) {
|
298
|
+
const { done, value } = await it.next();
|
299
|
+
if (done)
|
300
|
+
controller.close();
|
301
|
+
else
|
302
|
+
controller.enqueue(value);
|
303
|
+
},
|
304
|
+
async cancel(reason) {
|
305
|
+
var _a;
|
306
|
+
await ((_a = it.return) == null ? void 0 : _a.call(it, reason));
|
307
|
+
}
|
308
|
+
});
|
309
|
+
}
|
310
|
+
|
311
|
+
// streams/stream-data.ts
|
312
|
+
var experimental_StreamData = class {
|
313
|
+
constructor() {
|
314
|
+
this.encoder = new TextEncoder();
|
315
|
+
this.controller = null;
|
316
|
+
// closing the stream is synchronous, but we want to return a promise
|
317
|
+
// in case we're doing async work
|
318
|
+
this.isClosedPromise = null;
|
319
|
+
this.isClosedPromiseResolver = void 0;
|
320
|
+
this.isClosed = false;
|
321
|
+
// array to store appended data
|
322
|
+
this.data = [];
|
323
|
+
this.isClosedPromise = new Promise((resolve) => {
|
324
|
+
this.isClosedPromiseResolver = resolve;
|
325
|
+
});
|
326
|
+
const self = this;
|
327
|
+
this.stream = new TransformStream({
|
328
|
+
start: async (controller) => {
|
329
|
+
self.controller = controller;
|
330
|
+
},
|
331
|
+
transform: async (chunk, controller) => {
|
332
|
+
if (self.data.length > 0) {
|
333
|
+
const encodedData = self.encoder.encode(
|
334
|
+
formatStreamPart("data", self.data)
|
335
|
+
);
|
336
|
+
self.data = [];
|
337
|
+
controller.enqueue(encodedData);
|
338
|
+
}
|
339
|
+
controller.enqueue(chunk);
|
340
|
+
},
|
341
|
+
async flush(controller) {
|
342
|
+
const warningTimeout = process.env.NODE_ENV === "development" ? setTimeout(() => {
|
343
|
+
console.warn(
|
344
|
+
"The data stream is hanging. Did you forget to close it with `data.close()`?"
|
345
|
+
);
|
346
|
+
}, 3e3) : null;
|
347
|
+
await self.isClosedPromise;
|
348
|
+
if (warningTimeout !== null) {
|
349
|
+
clearTimeout(warningTimeout);
|
350
|
+
}
|
351
|
+
if (self.data.length) {
|
352
|
+
const encodedData = self.encoder.encode(
|
353
|
+
formatStreamPart("data", self.data)
|
354
|
+
);
|
355
|
+
controller.enqueue(encodedData);
|
473
356
|
}
|
474
|
-
)
|
475
|
-
);
|
476
|
-
} else {
|
477
|
-
stream = AIStream(
|
478
|
-
res,
|
479
|
-
parseOpenAIStream(),
|
480
|
-
(cb == null ? void 0 : cb.experimental_onFunctionCall) ? {
|
481
|
-
...cb,
|
482
|
-
onFinal: void 0
|
483
|
-
} : {
|
484
|
-
...cb
|
485
357
|
}
|
486
|
-
);
|
358
|
+
});
|
487
359
|
}
|
488
|
-
|
489
|
-
|
490
|
-
|
360
|
+
async close() {
|
361
|
+
var _a;
|
362
|
+
if (this.isClosed) {
|
363
|
+
throw new Error("Data Stream has already been closed.");
|
364
|
+
}
|
365
|
+
if (!this.controller) {
|
366
|
+
throw new Error("Stream controller is not initialized.");
|
367
|
+
}
|
368
|
+
(_a = this.isClosedPromiseResolver) == null ? void 0 : _a.call(this);
|
369
|
+
this.isClosed = true;
|
370
|
+
}
|
371
|
+
append(value) {
|
372
|
+
if (this.isClosed) {
|
373
|
+
throw new Error("Data Stream has already been closed.");
|
374
|
+
}
|
375
|
+
this.data.push(value);
|
376
|
+
}
|
377
|
+
};
|
378
|
+
function createStreamDataTransformer(experimental_streamData) {
|
379
|
+
if (!experimental_streamData) {
|
380
|
+
return new TransformStream({
|
381
|
+
transform: async (chunk, controller) => {
|
382
|
+
controller.enqueue(chunk);
|
383
|
+
}
|
384
|
+
});
|
385
|
+
}
|
386
|
+
const encoder = new TextEncoder();
|
387
|
+
const decoder = new TextDecoder();
|
388
|
+
return new TransformStream({
|
389
|
+
transform: async (chunk, controller) => {
|
390
|
+
const message = decoder.decode(chunk);
|
391
|
+
controller.enqueue(encoder.encode(formatStreamPart("text", message)));
|
392
|
+
}
|
393
|
+
});
|
394
|
+
}
|
395
|
+
|
396
|
+
// streams/anthropic-stream.ts
|
397
|
+
function parseAnthropicStream() {
|
398
|
+
let previous = "";
|
399
|
+
return (data) => {
|
400
|
+
const json = JSON.parse(data);
|
401
|
+
if ("error" in json) {
|
402
|
+
throw new Error(`${json.error.type}: ${json.error.message}`);
|
403
|
+
}
|
404
|
+
if (!("completion" in json)) {
|
405
|
+
return;
|
406
|
+
}
|
407
|
+
const text = json.completion;
|
408
|
+
if (!previous || text.length > previous.length && text.startsWith(previous)) {
|
409
|
+
const delta = text.slice(previous.length);
|
410
|
+
previous = text;
|
411
|
+
return delta;
|
412
|
+
}
|
413
|
+
return text;
|
414
|
+
};
|
415
|
+
}
|
416
|
+
async function* streamable(stream) {
|
417
|
+
for await (const chunk of stream) {
|
418
|
+
if ("completion" in chunk) {
|
419
|
+
const text = chunk.completion;
|
420
|
+
if (text)
|
421
|
+
yield text;
|
422
|
+
} else if ("delta" in chunk) {
|
423
|
+
const { delta } = chunk;
|
424
|
+
if ("text" in delta) {
|
425
|
+
const text = delta.text;
|
426
|
+
if (text)
|
427
|
+
yield text;
|
428
|
+
}
|
429
|
+
}
|
430
|
+
}
|
431
|
+
}
|
432
|
+
function AnthropicStream(res, cb) {
|
433
|
+
if (Symbol.asyncIterator in res) {
|
434
|
+
return readableFromAsyncIterable(streamable(res)).pipeThrough(createCallbacksTransformer(cb)).pipeThrough(createStreamDataTransformer(cb == null ? void 0 : cb.experimental_streamData));
|
491
435
|
} else {
|
492
|
-
return
|
436
|
+
return AIStream(res, parseAnthropicStream(), cb).pipeThrough(
|
493
437
|
createStreamDataTransformer(cb == null ? void 0 : cb.experimental_streamData)
|
494
438
|
);
|
495
439
|
}
|
496
440
|
}
|
497
|
-
|
498
|
-
|
499
|
-
|
500
|
-
|
501
|
-
|
502
|
-
|
503
|
-
|
504
|
-
|
505
|
-
const decode = createChunkDecoder();
|
506
|
-
return new TransformStream({
|
507
|
-
async transform(chunk, controller) {
|
508
|
-
const message = decode(chunk);
|
509
|
-
aggregatedFinalCompletionResponse += message;
|
510
|
-
const shouldHandleAsFunction = isFirstChunk && message.startsWith('{"function_call":');
|
511
|
-
if (shouldHandleAsFunction) {
|
512
|
-
isFunctionStreamingIn = true;
|
513
|
-
aggregatedResponse += message;
|
514
|
-
isFirstChunk = false;
|
515
|
-
return;
|
516
|
-
}
|
517
|
-
if (!isFunctionStreamingIn) {
|
441
|
+
|
442
|
+
// streams/assistant-response.ts
|
443
|
+
function experimental_AssistantResponse({ threadId, messageId }, process2) {
|
444
|
+
const stream = new ReadableStream({
|
445
|
+
async start(controller) {
|
446
|
+
var _a;
|
447
|
+
const textEncoder = new TextEncoder();
|
448
|
+
const sendMessage = (message) => {
|
518
449
|
controller.enqueue(
|
519
|
-
|
450
|
+
textEncoder.encode(formatStreamPart("assistant_message", message))
|
520
451
|
);
|
521
|
-
|
522
|
-
|
523
|
-
|
524
|
-
|
525
|
-
|
526
|
-
|
452
|
+
};
|
453
|
+
const sendDataMessage = (message) => {
|
454
|
+
controller.enqueue(
|
455
|
+
textEncoder.encode(formatStreamPart("data_message", message))
|
456
|
+
);
|
457
|
+
};
|
458
|
+
const sendError = (errorMessage) => {
|
459
|
+
controller.enqueue(
|
460
|
+
textEncoder.encode(formatStreamPart("error", errorMessage))
|
461
|
+
);
|
462
|
+
};
|
463
|
+
controller.enqueue(
|
464
|
+
textEncoder.encode(
|
465
|
+
formatStreamPart("assistant_control_data", {
|
466
|
+
threadId,
|
467
|
+
messageId
|
468
|
+
})
|
469
|
+
)
|
470
|
+
);
|
527
471
|
try {
|
528
|
-
|
529
|
-
|
530
|
-
|
531
|
-
|
532
|
-
|
533
|
-
|
534
|
-
|
535
|
-
|
536
|
-
const functionResponse = await callbacks.experimental_onFunctionCall(
|
537
|
-
{
|
538
|
-
name: payload.function_call.name,
|
539
|
-
arguments: argumentsPayload
|
540
|
-
},
|
541
|
-
(result) => {
|
542
|
-
newFunctionCallMessages = [
|
543
|
-
...functionCallMessages,
|
544
|
-
{
|
545
|
-
role: "assistant",
|
546
|
-
content: "",
|
547
|
-
function_call: payload.function_call
|
548
|
-
},
|
549
|
-
{
|
550
|
-
role: "function",
|
551
|
-
name: payload.function_call.name,
|
552
|
-
content: JSON.stringify(result)
|
553
|
-
}
|
554
|
-
];
|
555
|
-
return newFunctionCallMessages;
|
556
|
-
}
|
557
|
-
);
|
558
|
-
if (!functionResponse) {
|
559
|
-
controller.enqueue(
|
560
|
-
textEncoder.encode(
|
561
|
-
isComplexMode ? formatStreamPart(
|
562
|
-
"function_call",
|
563
|
-
// parse to prevent double-encoding:
|
564
|
-
JSON.parse(aggregatedResponse)
|
565
|
-
) : aggregatedResponse
|
566
|
-
)
|
567
|
-
);
|
568
|
-
return;
|
569
|
-
} else if (typeof functionResponse === "string") {
|
570
|
-
controller.enqueue(
|
571
|
-
isComplexMode ? textEncoder.encode(formatStreamPart("text", functionResponse)) : textEncoder.encode(functionResponse)
|
572
|
-
);
|
573
|
-
return;
|
574
|
-
}
|
575
|
-
const filteredCallbacks = {
|
576
|
-
...callbacks,
|
577
|
-
onStart: void 0
|
578
|
-
};
|
579
|
-
callbacks.onFinal = void 0;
|
580
|
-
const openAIStream = OpenAIStream(functionResponse, {
|
581
|
-
...filteredCallbacks,
|
582
|
-
[__internal__OpenAIFnMessagesSymbol]: newFunctionCallMessages
|
583
|
-
});
|
584
|
-
const reader = openAIStream.getReader();
|
585
|
-
while (true) {
|
586
|
-
const { done, value } = await reader.read();
|
587
|
-
if (done) {
|
588
|
-
break;
|
589
|
-
}
|
590
|
-
controller.enqueue(value);
|
591
|
-
}
|
592
|
-
}
|
472
|
+
await process2({
|
473
|
+
threadId,
|
474
|
+
messageId,
|
475
|
+
sendMessage,
|
476
|
+
sendDataMessage
|
477
|
+
});
|
478
|
+
} catch (error) {
|
479
|
+
sendError((_a = error.message) != null ? _a : `${error}`);
|
593
480
|
} finally {
|
594
|
-
|
595
|
-
await callbacks.onFinal(aggregatedFinalCompletionResponse);
|
596
|
-
}
|
481
|
+
controller.close();
|
597
482
|
}
|
483
|
+
},
|
484
|
+
pull(controller) {
|
485
|
+
},
|
486
|
+
cancel() {
|
598
487
|
}
|
599
488
|
});
|
600
|
-
|
601
|
-
|
602
|
-
|
603
|
-
|
604
|
-
constructor(res, init, data) {
|
605
|
-
let processedStream = res;
|
606
|
-
if (data) {
|
607
|
-
processedStream = res.pipeThrough(data.stream);
|
489
|
+
return new Response(stream, {
|
490
|
+
status: 200,
|
491
|
+
headers: {
|
492
|
+
"Content-Type": "text/plain; charset=utf-8"
|
608
493
|
}
|
609
|
-
super(processedStream, {
|
610
|
-
...init,
|
611
|
-
status: 200,
|
612
|
-
headers: {
|
613
|
-
"Content-Type": "text/plain; charset=utf-8",
|
614
|
-
[COMPLEX_HEADER]: data ? "true" : "false",
|
615
|
-
...init == null ? void 0 : init.headers
|
616
|
-
}
|
617
|
-
});
|
618
|
-
}
|
619
|
-
};
|
620
|
-
function streamToResponse(res, response, init) {
|
621
|
-
response.writeHead((init == null ? void 0 : init.status) || 200, {
|
622
|
-
"Content-Type": "text/plain; charset=utf-8",
|
623
|
-
...init == null ? void 0 : init.headers
|
624
494
|
});
|
625
|
-
|
626
|
-
|
627
|
-
|
628
|
-
|
629
|
-
|
630
|
-
|
495
|
+
}
|
496
|
+
|
497
|
+
// streams/aws-bedrock-stream.ts
|
498
|
+
async function* asDeltaIterable(response, extractTextDeltaFromChunk) {
|
499
|
+
var _a, _b;
|
500
|
+
const decoder = new TextDecoder();
|
501
|
+
for await (const chunk of (_a = response.body) != null ? _a : []) {
|
502
|
+
const bytes = (_b = chunk.chunk) == null ? void 0 : _b.bytes;
|
503
|
+
if (bytes != null) {
|
504
|
+
const chunkText = decoder.decode(bytes);
|
505
|
+
const chunkJSON = JSON.parse(chunkText);
|
506
|
+
const delta = extractTextDeltaFromChunk(chunkJSON);
|
507
|
+
if (delta != null) {
|
508
|
+
yield delta;
|
631
509
|
}
|
632
|
-
|
633
|
-
read();
|
634
|
-
});
|
510
|
+
}
|
635
511
|
}
|
636
|
-
read();
|
637
512
|
}
|
638
|
-
|
639
|
-
|
640
|
-
|
641
|
-
|
642
|
-
return
|
643
|
-
|
513
|
+
function AWSBedrockAnthropicStream(response, callbacks) {
|
514
|
+
return AWSBedrockStream(response, callbacks, (chunk) => chunk.completion);
|
515
|
+
}
|
516
|
+
function AWSBedrockCohereStream(response, callbacks) {
|
517
|
+
return AWSBedrockStream(
|
518
|
+
response,
|
519
|
+
callbacks,
|
520
|
+
// As of 2023-11-17, Bedrock does not support streaming for Cohere,
|
521
|
+
// so we take the full generation:
|
522
|
+
(chunk) => {
|
644
523
|
var _a, _b;
|
645
|
-
|
646
|
-
if (done) {
|
647
|
-
controller.close();
|
648
|
-
return;
|
649
|
-
}
|
650
|
-
const text = trimStartOfStream((_b = (_a = value.token) == null ? void 0 : _a.text) != null ? _b : "");
|
651
|
-
if (!text)
|
652
|
-
return;
|
653
|
-
if (value.generated_text != null && value.generated_text.length > 0) {
|
654
|
-
return;
|
655
|
-
}
|
656
|
-
if (text === "</s>" || text === "<|endoftext|>" || text === "<|end|>") {
|
657
|
-
return;
|
658
|
-
}
|
659
|
-
controller.enqueue(text);
|
524
|
+
return (_b = (_a = chunk.generations) == null ? void 0 : _a[0]) == null ? void 0 : _b.text;
|
660
525
|
}
|
661
|
-
|
526
|
+
);
|
662
527
|
}
|
663
|
-
function
|
664
|
-
return
|
528
|
+
function AWSBedrockLlama2Stream(response, callbacks) {
|
529
|
+
return AWSBedrockStream(response, callbacks, (chunk) => chunk.generation);
|
530
|
+
}
|
531
|
+
function AWSBedrockStream(response, callbacks, extractTextDeltaFromChunk) {
|
532
|
+
return readableFromAsyncIterable(
|
533
|
+
asDeltaIterable(response, extractTextDeltaFromChunk)
|
534
|
+
).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
|
665
535
|
createStreamDataTransformer(callbacks == null ? void 0 : callbacks.experimental_streamData)
|
666
536
|
);
|
667
537
|
}
|
@@ -694,7 +564,7 @@ async function readAndProcessLines(reader, controller) {
|
|
694
564
|
}
|
695
565
|
controller.close();
|
696
566
|
}
|
697
|
-
function
|
567
|
+
function createParser2(res) {
|
698
568
|
var _a;
|
699
569
|
const reader = (_a = res.body) == null ? void 0 : _a.getReader();
|
700
570
|
return new ReadableStream({
|
@@ -708,46 +578,57 @@ function createParser3(res) {
|
|
708
578
|
});
|
709
579
|
}
|
710
580
|
function CohereStream(reader, callbacks) {
|
711
|
-
return
|
581
|
+
return createParser2(reader).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
|
712
582
|
createStreamDataTransformer(callbacks == null ? void 0 : callbacks.experimental_streamData)
|
713
583
|
);
|
714
584
|
}
|
715
585
|
|
716
|
-
// streams/
|
717
|
-
function
|
718
|
-
|
719
|
-
|
720
|
-
const
|
721
|
-
if (
|
722
|
-
|
586
|
+
// streams/google-generative-ai-stream.ts
|
587
|
+
async function* streamable2(response) {
|
588
|
+
var _a, _b, _c;
|
589
|
+
for await (const chunk of response.stream) {
|
590
|
+
const parts = (_c = (_b = (_a = chunk.candidates) == null ? void 0 : _a[0]) == null ? void 0 : _b.content) == null ? void 0 : _c.parts;
|
591
|
+
if (parts === void 0) {
|
592
|
+
continue;
|
723
593
|
}
|
724
|
-
|
725
|
-
|
726
|
-
|
727
|
-
const text = json.completion;
|
728
|
-
if (!previous || text.length > previous.length && text.startsWith(previous)) {
|
729
|
-
const delta = text.slice(previous.length);
|
730
|
-
previous = text;
|
731
|
-
return delta;
|
594
|
+
const firstPart = parts[0];
|
595
|
+
if (typeof firstPart.text === "string") {
|
596
|
+
yield firstPart.text;
|
732
597
|
}
|
733
|
-
return text;
|
734
|
-
};
|
735
|
-
}
|
736
|
-
async function* streamable2(stream) {
|
737
|
-
for await (const chunk of stream) {
|
738
|
-
const text = chunk.completion;
|
739
|
-
if (text)
|
740
|
-
yield text;
|
741
598
|
}
|
742
599
|
}
|
743
|
-
function
|
744
|
-
|
745
|
-
|
746
|
-
|
747
|
-
|
748
|
-
|
749
|
-
|
750
|
-
|
600
|
+
function GoogleGenerativeAIStream(response, cb) {
|
601
|
+
return readableFromAsyncIterable(streamable2(response)).pipeThrough(createCallbacksTransformer(cb)).pipeThrough(createStreamDataTransformer(cb == null ? void 0 : cb.experimental_streamData));
|
602
|
+
}
|
603
|
+
|
604
|
+
// streams/huggingface-stream.ts
|
605
|
+
function createParser3(res) {
|
606
|
+
const trimStartOfStream = trimStartOfStreamHelper();
|
607
|
+
return new ReadableStream({
|
608
|
+
async pull(controller) {
|
609
|
+
var _a, _b;
|
610
|
+
const { value, done } = await res.next();
|
611
|
+
if (done) {
|
612
|
+
controller.close();
|
613
|
+
return;
|
614
|
+
}
|
615
|
+
const text = trimStartOfStream((_b = (_a = value.token) == null ? void 0 : _a.text) != null ? _b : "");
|
616
|
+
if (!text)
|
617
|
+
return;
|
618
|
+
if (value.generated_text != null && value.generated_text.length > 0) {
|
619
|
+
return;
|
620
|
+
}
|
621
|
+
if (text === "</s>" || text === "<|endoftext|>" || text === "<|end|>") {
|
622
|
+
return;
|
623
|
+
}
|
624
|
+
controller.enqueue(text);
|
625
|
+
}
|
626
|
+
});
|
627
|
+
}
|
628
|
+
function HuggingFaceStream(res, callbacks) {
|
629
|
+
return createParser3(res).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(
|
630
|
+
createStreamDataTransformer(callbacks == null ? void 0 : callbacks.experimental_streamData)
|
631
|
+
);
|
751
632
|
}
|
752
633
|
|
753
634
|
// streams/langchain-stream.ts
|
@@ -811,6 +692,277 @@ function LangChainStream(callbacks) {
|
|
811
692
|
};
|
812
693
|
}
|
813
694
|
|
695
|
+
// streams/openai-stream.ts
|
696
|
+
function parseOpenAIStream() {
|
697
|
+
const extract = chunkToText();
|
698
|
+
return (data) => extract(JSON.parse(data));
|
699
|
+
}
|
700
|
+
async function* streamable3(stream) {
|
701
|
+
const extract = chunkToText();
|
702
|
+
for await (const chunk of stream) {
|
703
|
+
const text = extract(chunk);
|
704
|
+
if (text)
|
705
|
+
yield text;
|
706
|
+
}
|
707
|
+
}
|
708
|
+
function chunkToText() {
|
709
|
+
const trimStartOfStream = trimStartOfStreamHelper();
|
710
|
+
let isFunctionStreamingIn;
|
711
|
+
return (json) => {
|
712
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
|
713
|
+
if (isChatCompletionChunk(json)) {
|
714
|
+
const delta = (_a = json.choices[0]) == null ? void 0 : _a.delta;
|
715
|
+
if ((_b = delta.function_call) == null ? void 0 : _b.name) {
|
716
|
+
isFunctionStreamingIn = true;
|
717
|
+
return `{"function_call": {"name": "${delta.function_call.name}", "arguments": "`;
|
718
|
+
} else if ((_e = (_d = (_c = delta.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.name) {
|
719
|
+
isFunctionStreamingIn = true;
|
720
|
+
const toolCall = delta.tool_calls[0];
|
721
|
+
if (toolCall.index === 0) {
|
722
|
+
return `{"tool_calls":[ {"id": "${toolCall.id}", "type": "function", "function": {"name": "${(_f = toolCall.function) == null ? void 0 : _f.name}", "arguments": "`;
|
723
|
+
} else {
|
724
|
+
return `"}}, {"id": "${toolCall.id}", "type": "function", "function": {"name": "${(_g = toolCall.function) == null ? void 0 : _g.name}", "arguments": "`;
|
725
|
+
}
|
726
|
+
} else if ((_h = delta.function_call) == null ? void 0 : _h.arguments) {
|
727
|
+
return cleanupArguments((_i = delta.function_call) == null ? void 0 : _i.arguments);
|
728
|
+
} else if ((_k = (_j = delta.tool_calls) == null ? void 0 : _j[0].function) == null ? void 0 : _k.arguments) {
|
729
|
+
return cleanupArguments((_n = (_m = (_l = delta.tool_calls) == null ? void 0 : _l[0]) == null ? void 0 : _m.function) == null ? void 0 : _n.arguments);
|
730
|
+
} else if (isFunctionStreamingIn && (((_o = json.choices[0]) == null ? void 0 : _o.finish_reason) === "function_call" || ((_p = json.choices[0]) == null ? void 0 : _p.finish_reason) === "stop")) {
|
731
|
+
isFunctionStreamingIn = false;
|
732
|
+
return '"}}';
|
733
|
+
} else if (isFunctionStreamingIn && ((_q = json.choices[0]) == null ? void 0 : _q.finish_reason) === "tool_calls") {
|
734
|
+
isFunctionStreamingIn = false;
|
735
|
+
return '"}}]}';
|
736
|
+
}
|
737
|
+
}
|
738
|
+
const text = trimStartOfStream(
|
739
|
+
isChatCompletionChunk(json) && json.choices[0].delta.content ? json.choices[0].delta.content : isCompletion(json) ? json.choices[0].text : ""
|
740
|
+
);
|
741
|
+
return text;
|
742
|
+
};
|
743
|
+
function cleanupArguments(argumentChunk) {
|
744
|
+
let escapedPartialJson = argumentChunk.replace(/\\/g, "\\\\").replace(/\//g, "\\/").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\f/g, "\\f");
|
745
|
+
return `${escapedPartialJson}`;
|
746
|
+
}
|
747
|
+
}
|
748
|
+
var __internal__OpenAIFnMessagesSymbol = Symbol(
|
749
|
+
"internal_openai_fn_messages"
|
750
|
+
);
|
751
|
+
function isChatCompletionChunk(data) {
|
752
|
+
return "choices" in data && data.choices && data.choices[0] && "delta" in data.choices[0];
|
753
|
+
}
|
754
|
+
function isCompletion(data) {
|
755
|
+
return "choices" in data && data.choices && data.choices[0] && "text" in data.choices[0];
|
756
|
+
}
|
757
|
+
function OpenAIStream(res, callbacks) {
|
758
|
+
const cb = callbacks;
|
759
|
+
let stream;
|
760
|
+
if (Symbol.asyncIterator in res) {
|
761
|
+
stream = readableFromAsyncIterable(streamable3(res)).pipeThrough(
|
762
|
+
createCallbacksTransformer(
|
763
|
+
(cb == null ? void 0 : cb.experimental_onFunctionCall) || (cb == null ? void 0 : cb.experimental_onToolCall) ? {
|
764
|
+
...cb,
|
765
|
+
onFinal: void 0
|
766
|
+
} : {
|
767
|
+
...cb
|
768
|
+
}
|
769
|
+
)
|
770
|
+
);
|
771
|
+
} else {
|
772
|
+
stream = AIStream(
|
773
|
+
res,
|
774
|
+
parseOpenAIStream(),
|
775
|
+
(cb == null ? void 0 : cb.experimental_onFunctionCall) || (cb == null ? void 0 : cb.experimental_onToolCall) ? {
|
776
|
+
...cb,
|
777
|
+
onFinal: void 0
|
778
|
+
} : {
|
779
|
+
...cb
|
780
|
+
}
|
781
|
+
);
|
782
|
+
}
|
783
|
+
if (cb && (cb.experimental_onFunctionCall || cb.experimental_onToolCall)) {
|
784
|
+
const functionCallTransformer = createFunctionCallTransformer(cb);
|
785
|
+
return stream.pipeThrough(functionCallTransformer);
|
786
|
+
} else {
|
787
|
+
return stream.pipeThrough(
|
788
|
+
createStreamDataTransformer(cb == null ? void 0 : cb.experimental_streamData)
|
789
|
+
);
|
790
|
+
}
|
791
|
+
}
|
792
|
+
function createFunctionCallTransformer(callbacks) {
|
793
|
+
const textEncoder = new TextEncoder();
|
794
|
+
let isFirstChunk = true;
|
795
|
+
let aggregatedResponse = "";
|
796
|
+
let aggregatedFinalCompletionResponse = "";
|
797
|
+
let isFunctionStreamingIn = false;
|
798
|
+
let functionCallMessages = callbacks[__internal__OpenAIFnMessagesSymbol] || [];
|
799
|
+
const isComplexMode = callbacks == null ? void 0 : callbacks.experimental_streamData;
|
800
|
+
const decode = createChunkDecoder();
|
801
|
+
return new TransformStream({
|
802
|
+
async transform(chunk, controller) {
|
803
|
+
const message = decode(chunk);
|
804
|
+
aggregatedFinalCompletionResponse += message;
|
805
|
+
const shouldHandleAsFunction = isFirstChunk && (message.startsWith('{"function_call":') || message.startsWith('{"tool_calls":'));
|
806
|
+
if (shouldHandleAsFunction) {
|
807
|
+
isFunctionStreamingIn = true;
|
808
|
+
aggregatedResponse += message;
|
809
|
+
isFirstChunk = false;
|
810
|
+
return;
|
811
|
+
}
|
812
|
+
if (!isFunctionStreamingIn) {
|
813
|
+
controller.enqueue(
|
814
|
+
isComplexMode ? textEncoder.encode(formatStreamPart("text", message)) : chunk
|
815
|
+
);
|
816
|
+
return;
|
817
|
+
} else {
|
818
|
+
aggregatedResponse += message;
|
819
|
+
}
|
820
|
+
},
|
821
|
+
async flush(controller) {
|
822
|
+
try {
|
823
|
+
if (!isFirstChunk && isFunctionStreamingIn && (callbacks.experimental_onFunctionCall || callbacks.experimental_onToolCall)) {
|
824
|
+
isFunctionStreamingIn = false;
|
825
|
+
const payload = JSON.parse(aggregatedResponse);
|
826
|
+
let newFunctionCallMessages = [
|
827
|
+
...functionCallMessages
|
828
|
+
];
|
829
|
+
let functionResponse = void 0;
|
830
|
+
if (callbacks.experimental_onFunctionCall) {
|
831
|
+
if (payload.function_call === void 0) {
|
832
|
+
console.warn(
|
833
|
+
"experimental_onFunctionCall should not be defined when using tools"
|
834
|
+
);
|
835
|
+
}
|
836
|
+
const argumentsPayload = JSON.parse(
|
837
|
+
payload.function_call.arguments
|
838
|
+
);
|
839
|
+
functionResponse = await callbacks.experimental_onFunctionCall(
|
840
|
+
{
|
841
|
+
name: payload.function_call.name,
|
842
|
+
arguments: argumentsPayload
|
843
|
+
},
|
844
|
+
(result) => {
|
845
|
+
newFunctionCallMessages = [
|
846
|
+
...functionCallMessages,
|
847
|
+
{
|
848
|
+
role: "assistant",
|
849
|
+
content: "",
|
850
|
+
function_call: payload.function_call
|
851
|
+
},
|
852
|
+
{
|
853
|
+
role: "function",
|
854
|
+
name: payload.function_call.name,
|
855
|
+
content: JSON.stringify(result)
|
856
|
+
}
|
857
|
+
];
|
858
|
+
return newFunctionCallMessages;
|
859
|
+
}
|
860
|
+
);
|
861
|
+
}
|
862
|
+
if (callbacks.experimental_onToolCall) {
|
863
|
+
const toolCalls = {
|
864
|
+
tools: []
|
865
|
+
};
|
866
|
+
for (const tool of payload.tool_calls) {
|
867
|
+
toolCalls.tools.push({
|
868
|
+
id: tool.id,
|
869
|
+
type: "function",
|
870
|
+
func: {
|
871
|
+
name: tool.function.name,
|
872
|
+
arguments: tool.function.arguments
|
873
|
+
}
|
874
|
+
});
|
875
|
+
}
|
876
|
+
let responseIndex = 0;
|
877
|
+
try {
|
878
|
+
functionResponse = await callbacks.experimental_onToolCall(
|
879
|
+
toolCalls,
|
880
|
+
(result) => {
|
881
|
+
if (result) {
|
882
|
+
const { tool_call_id, function_name, tool_call_result } = result;
|
883
|
+
newFunctionCallMessages = [
|
884
|
+
...newFunctionCallMessages,
|
885
|
+
// Only append the assistant message if it's the first response
|
886
|
+
...responseIndex === 0 ? [
|
887
|
+
{
|
888
|
+
role: "assistant",
|
889
|
+
content: "",
|
890
|
+
tool_calls: payload.tool_calls.map(
|
891
|
+
(tc) => ({
|
892
|
+
id: tc.id,
|
893
|
+
type: "function",
|
894
|
+
function: {
|
895
|
+
name: tc.function.name,
|
896
|
+
// we send the arguments an object to the user, but as the API expects a string, we need to stringify it
|
897
|
+
arguments: JSON.stringify(
|
898
|
+
tc.function.arguments
|
899
|
+
)
|
900
|
+
}
|
901
|
+
})
|
902
|
+
)
|
903
|
+
}
|
904
|
+
] : [],
|
905
|
+
// Append the function call result message
|
906
|
+
{
|
907
|
+
role: "tool",
|
908
|
+
tool_call_id,
|
909
|
+
name: function_name,
|
910
|
+
content: JSON.stringify(tool_call_result)
|
911
|
+
}
|
912
|
+
];
|
913
|
+
responseIndex++;
|
914
|
+
}
|
915
|
+
return newFunctionCallMessages;
|
916
|
+
}
|
917
|
+
);
|
918
|
+
} catch (e) {
|
919
|
+
console.error("Error calling experimental_onToolCall:", e);
|
920
|
+
}
|
921
|
+
}
|
922
|
+
if (!functionResponse) {
|
923
|
+
controller.enqueue(
|
924
|
+
textEncoder.encode(
|
925
|
+
isComplexMode ? formatStreamPart(
|
926
|
+
payload.function_call ? "function_call" : "tool_calls",
|
927
|
+
// parse to prevent double-encoding:
|
928
|
+
JSON.parse(aggregatedResponse)
|
929
|
+
) : aggregatedResponse
|
930
|
+
)
|
931
|
+
);
|
932
|
+
return;
|
933
|
+
} else if (typeof functionResponse === "string") {
|
934
|
+
controller.enqueue(
|
935
|
+
isComplexMode ? textEncoder.encode(formatStreamPart("text", functionResponse)) : textEncoder.encode(functionResponse)
|
936
|
+
);
|
937
|
+
return;
|
938
|
+
}
|
939
|
+
const filteredCallbacks = {
|
940
|
+
...callbacks,
|
941
|
+
onStart: void 0
|
942
|
+
};
|
943
|
+
callbacks.onFinal = void 0;
|
944
|
+
const openAIStream = OpenAIStream(functionResponse, {
|
945
|
+
...filteredCallbacks,
|
946
|
+
[__internal__OpenAIFnMessagesSymbol]: newFunctionCallMessages
|
947
|
+
});
|
948
|
+
const reader = openAIStream.getReader();
|
949
|
+
while (true) {
|
950
|
+
const { done, value } = await reader.read();
|
951
|
+
if (done) {
|
952
|
+
break;
|
953
|
+
}
|
954
|
+
controller.enqueue(value);
|
955
|
+
}
|
956
|
+
}
|
957
|
+
} finally {
|
958
|
+
if (callbacks.onFinal && aggregatedFinalCompletionResponse) {
|
959
|
+
await callbacks.onFinal(aggregatedFinalCompletionResponse);
|
960
|
+
}
|
961
|
+
}
|
962
|
+
}
|
963
|
+
});
|
964
|
+
}
|
965
|
+
|
814
966
|
// streams/replicate-stream.ts
|
815
967
|
async function ReplicateStream(res, cb, options) {
|
816
968
|
var _a;
|
@@ -919,20 +1071,35 @@ async function parseComplexResponse({
|
|
919
1071
|
};
|
920
1072
|
functionCallMessage = prefixMap["function_call"];
|
921
1073
|
}
|
1074
|
+
let toolCallMessage = null;
|
1075
|
+
if (type === "tool_calls") {
|
1076
|
+
prefixMap["tool_calls"] = {
|
1077
|
+
id: generateId(),
|
1078
|
+
role: "assistant",
|
1079
|
+
content: "",
|
1080
|
+
tool_calls: value.tool_calls,
|
1081
|
+
createdAt
|
1082
|
+
};
|
1083
|
+
toolCallMessage = prefixMap["tool_calls"];
|
1084
|
+
}
|
922
1085
|
if (type === "data") {
|
923
1086
|
prefixMap["data"].push(...value);
|
924
1087
|
}
|
925
1088
|
const responseMessage = prefixMap["text"];
|
926
|
-
const merged = [
|
927
|
-
|
928
|
-
|
1089
|
+
const merged = [
|
1090
|
+
functionCallMessage,
|
1091
|
+
toolCallMessage,
|
1092
|
+
responseMessage
|
1093
|
+
].filter(Boolean);
|
929
1094
|
update(merged, [...prefixMap["data"]]);
|
930
1095
|
}
|
931
1096
|
onFinish == null ? void 0 : onFinish(prefixMap);
|
932
1097
|
return {
|
933
|
-
messages: [
|
934
|
-
|
935
|
-
|
1098
|
+
messages: [
|
1099
|
+
prefixMap.text,
|
1100
|
+
prefixMap.function_call,
|
1101
|
+
prefixMap.tool_calls
|
1102
|
+
].filter(Boolean),
|
936
1103
|
data: prefixMap.data
|
937
1104
|
};
|
938
1105
|
}
|
@@ -1012,59 +1179,41 @@ var experimental_StreamingReactResponse = class {
|
|
1012
1179
|
}
|
1013
1180
|
};
|
1014
1181
|
|
1015
|
-
// streams/
|
1016
|
-
|
1017
|
-
|
1018
|
-
|
1019
|
-
|
1020
|
-
|
1021
|
-
const sendMessage = (message) => {
|
1022
|
-
controller.enqueue(
|
1023
|
-
textEncoder.encode(formatStreamPart("assistant_message", message))
|
1024
|
-
);
|
1025
|
-
};
|
1026
|
-
const sendDataMessage = (message) => {
|
1027
|
-
controller.enqueue(
|
1028
|
-
textEncoder.encode(formatStreamPart("data_message", message))
|
1029
|
-
);
|
1030
|
-
};
|
1031
|
-
const sendError = (errorMessage) => {
|
1032
|
-
controller.enqueue(
|
1033
|
-
textEncoder.encode(formatStreamPart("error", errorMessage))
|
1034
|
-
);
|
1035
|
-
};
|
1036
|
-
controller.enqueue(
|
1037
|
-
textEncoder.encode(
|
1038
|
-
formatStreamPart("assistant_control_data", {
|
1039
|
-
threadId,
|
1040
|
-
messageId
|
1041
|
-
})
|
1042
|
-
)
|
1043
|
-
);
|
1044
|
-
try {
|
1045
|
-
await process2({
|
1046
|
-
threadId,
|
1047
|
-
messageId,
|
1048
|
-
sendMessage,
|
1049
|
-
sendDataMessage
|
1050
|
-
});
|
1051
|
-
} catch (error) {
|
1052
|
-
sendError((_a = error.message) != null ? _a : `${error}`);
|
1053
|
-
} finally {
|
1054
|
-
controller.close();
|
1055
|
-
}
|
1056
|
-
},
|
1057
|
-
pull(controller) {
|
1058
|
-
},
|
1059
|
-
cancel() {
|
1060
|
-
}
|
1061
|
-
});
|
1062
|
-
return new Response(stream, {
|
1063
|
-
status: 200,
|
1064
|
-
headers: {
|
1065
|
-
"Content-Type": "text/plain; charset=utf-8"
|
1182
|
+
// streams/streaming-text-response.ts
|
1183
|
+
var StreamingTextResponse = class extends Response {
|
1184
|
+
constructor(res, init, data) {
|
1185
|
+
let processedStream = res;
|
1186
|
+
if (data) {
|
1187
|
+
processedStream = res.pipeThrough(data.stream);
|
1066
1188
|
}
|
1189
|
+
super(processedStream, {
|
1190
|
+
...init,
|
1191
|
+
status: 200,
|
1192
|
+
headers: {
|
1193
|
+
"Content-Type": "text/plain; charset=utf-8",
|
1194
|
+
[COMPLEX_HEADER]: data ? "true" : "false",
|
1195
|
+
...init == null ? void 0 : init.headers
|
1196
|
+
}
|
1197
|
+
});
|
1198
|
+
}
|
1199
|
+
};
|
1200
|
+
function streamToResponse(res, response, init) {
|
1201
|
+
response.writeHead((init == null ? void 0 : init.status) || 200, {
|
1202
|
+
"Content-Type": "text/plain; charset=utf-8",
|
1203
|
+
...init == null ? void 0 : init.headers
|
1067
1204
|
});
|
1205
|
+
const reader = res.getReader();
|
1206
|
+
function read() {
|
1207
|
+
reader.read().then(({ done, value }) => {
|
1208
|
+
if (done) {
|
1209
|
+
response.end();
|
1210
|
+
return;
|
1211
|
+
}
|
1212
|
+
response.write(value);
|
1213
|
+
read();
|
1214
|
+
});
|
1215
|
+
}
|
1216
|
+
read();
|
1068
1217
|
}
|
1069
1218
|
export {
|
1070
1219
|
AIStream,
|
@@ -1075,6 +1224,7 @@ export {
|
|
1075
1224
|
AnthropicStream,
|
1076
1225
|
COMPLEX_HEADER,
|
1077
1226
|
CohereStream,
|
1227
|
+
GoogleGenerativeAIStream,
|
1078
1228
|
HuggingFaceStream,
|
1079
1229
|
LangChainStream,
|
1080
1230
|
OpenAIStream,
|