ai 5.0.0-canary.20 → 5.0.0-canary.22
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 +60 -0
- package/README.md +1 -1
- package/dist/index.d.mts +731 -795
- package/dist/index.d.ts +731 -795
- package/dist/index.js +1244 -1678
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1167 -1600
- package/dist/index.mjs.map +1 -1
- package/dist/internal/index.d.mts +7 -13
- package/dist/internal/index.d.ts +7 -13
- package/dist/internal/index.js +126 -126
- package/dist/internal/index.js.map +1 -1
- package/dist/internal/index.mjs +119 -119
- package/dist/internal/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
@@ -12,406 +12,6 @@ import {
|
|
12
12
|
jsonSchema as jsonSchema2
|
13
13
|
} from "@ai-sdk/provider-utils";
|
14
14
|
|
15
|
-
// src/data-stream/create-data-stream.ts
|
16
|
-
function createDataStream({
|
17
|
-
execute,
|
18
|
-
onError = () => "An error occurred."
|
19
|
-
// mask error messages for safety by default
|
20
|
-
}) {
|
21
|
-
let controller;
|
22
|
-
const ongoingStreamPromises = [];
|
23
|
-
const stream = new ReadableStream({
|
24
|
-
start(controllerArg) {
|
25
|
-
controller = controllerArg;
|
26
|
-
}
|
27
|
-
});
|
28
|
-
function safeEnqueue(data) {
|
29
|
-
try {
|
30
|
-
controller.enqueue(data);
|
31
|
-
} catch (error) {
|
32
|
-
}
|
33
|
-
}
|
34
|
-
try {
|
35
|
-
const result = execute({
|
36
|
-
write(part) {
|
37
|
-
safeEnqueue(part);
|
38
|
-
},
|
39
|
-
merge(streamArg) {
|
40
|
-
ongoingStreamPromises.push(
|
41
|
-
(async () => {
|
42
|
-
const reader = streamArg.getReader();
|
43
|
-
while (true) {
|
44
|
-
const { done, value } = await reader.read();
|
45
|
-
if (done)
|
46
|
-
break;
|
47
|
-
safeEnqueue(value);
|
48
|
-
}
|
49
|
-
})().catch((error) => {
|
50
|
-
safeEnqueue({ type: "error", value: onError(error) });
|
51
|
-
})
|
52
|
-
);
|
53
|
-
},
|
54
|
-
onError
|
55
|
-
});
|
56
|
-
if (result) {
|
57
|
-
ongoingStreamPromises.push(
|
58
|
-
result.catch((error) => {
|
59
|
-
safeEnqueue({ type: "error", value: onError(error) });
|
60
|
-
})
|
61
|
-
);
|
62
|
-
}
|
63
|
-
} catch (error) {
|
64
|
-
safeEnqueue({ type: "error", value: onError(error) });
|
65
|
-
}
|
66
|
-
const waitForStreams = new Promise(async (resolve) => {
|
67
|
-
while (ongoingStreamPromises.length > 0) {
|
68
|
-
await ongoingStreamPromises.shift();
|
69
|
-
}
|
70
|
-
resolve();
|
71
|
-
});
|
72
|
-
waitForStreams.finally(() => {
|
73
|
-
try {
|
74
|
-
controller.close();
|
75
|
-
} catch (error) {
|
76
|
-
}
|
77
|
-
});
|
78
|
-
return stream;
|
79
|
-
}
|
80
|
-
|
81
|
-
// src/util/prepare-headers.ts
|
82
|
-
function prepareHeaders(headers, defaultHeaders) {
|
83
|
-
const responseHeaders = new Headers(headers != null ? headers : {});
|
84
|
-
for (const [key, value] of Object.entries(defaultHeaders)) {
|
85
|
-
if (!responseHeaders.has(key)) {
|
86
|
-
responseHeaders.set(key, value);
|
87
|
-
}
|
88
|
-
}
|
89
|
-
return responseHeaders;
|
90
|
-
}
|
91
|
-
|
92
|
-
// src/data-stream/data-stream-headers.ts
|
93
|
-
var dataStreamHeaders = {
|
94
|
-
"content-type": "text/event-stream",
|
95
|
-
"cache-control": "no-cache",
|
96
|
-
connection: "keep-alive",
|
97
|
-
"x-vercel-ai-data-stream": "v2",
|
98
|
-
"x-accel-buffering": "no"
|
99
|
-
// disable nginx buffering
|
100
|
-
};
|
101
|
-
|
102
|
-
// src/data-stream/json-to-sse-transform-stream.ts
|
103
|
-
var JsonToSseTransformStream = class extends TransformStream {
|
104
|
-
constructor() {
|
105
|
-
super({
|
106
|
-
transform(part, controller) {
|
107
|
-
controller.enqueue(`data: ${JSON.stringify(part)}
|
108
|
-
|
109
|
-
`);
|
110
|
-
},
|
111
|
-
flush(controller) {
|
112
|
-
controller.enqueue("data: [DONE]\n\n");
|
113
|
-
}
|
114
|
-
});
|
115
|
-
}
|
116
|
-
};
|
117
|
-
|
118
|
-
// src/data-stream/create-data-stream-response.ts
|
119
|
-
function createDataStreamResponse({
|
120
|
-
status,
|
121
|
-
statusText,
|
122
|
-
headers,
|
123
|
-
dataStream
|
124
|
-
}) {
|
125
|
-
return new Response(
|
126
|
-
dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream()),
|
127
|
-
{
|
128
|
-
status,
|
129
|
-
statusText,
|
130
|
-
headers: prepareHeaders(headers, dataStreamHeaders)
|
131
|
-
}
|
132
|
-
);
|
133
|
-
}
|
134
|
-
|
135
|
-
// src/util/write-to-server-response.ts
|
136
|
-
function writeToServerResponse({
|
137
|
-
response,
|
138
|
-
status,
|
139
|
-
statusText,
|
140
|
-
headers,
|
141
|
-
stream
|
142
|
-
}) {
|
143
|
-
response.writeHead(status != null ? status : 200, statusText, headers);
|
144
|
-
const reader = stream.getReader();
|
145
|
-
const read = async () => {
|
146
|
-
try {
|
147
|
-
while (true) {
|
148
|
-
const { done, value } = await reader.read();
|
149
|
-
if (done)
|
150
|
-
break;
|
151
|
-
response.write(value);
|
152
|
-
}
|
153
|
-
} catch (error) {
|
154
|
-
throw error;
|
155
|
-
} finally {
|
156
|
-
response.end();
|
157
|
-
}
|
158
|
-
};
|
159
|
-
read();
|
160
|
-
}
|
161
|
-
|
162
|
-
// src/data-stream/pipe-data-stream-to-response.ts
|
163
|
-
function pipeDataStreamToResponse({
|
164
|
-
response,
|
165
|
-
status,
|
166
|
-
statusText,
|
167
|
-
headers,
|
168
|
-
dataStream
|
169
|
-
}) {
|
170
|
-
writeToServerResponse({
|
171
|
-
response,
|
172
|
-
status,
|
173
|
-
statusText,
|
174
|
-
headers: Object.fromEntries(
|
175
|
-
prepareHeaders(headers, dataStreamHeaders).entries()
|
176
|
-
),
|
177
|
-
stream: dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
|
178
|
-
});
|
179
|
-
}
|
180
|
-
|
181
|
-
// src/data-stream/process-data-stream.ts
|
182
|
-
import {
|
183
|
-
createEventSourceParserStream,
|
184
|
-
safeParseJSON
|
185
|
-
} from "@ai-sdk/provider-utils";
|
186
|
-
|
187
|
-
// src/util/async-iterable-stream.ts
|
188
|
-
function createAsyncIterableStream(source) {
|
189
|
-
const stream = source.pipeThrough(new TransformStream());
|
190
|
-
stream[Symbol.asyncIterator] = () => {
|
191
|
-
const reader = stream.getReader();
|
192
|
-
return {
|
193
|
-
async next() {
|
194
|
-
const { done, value } = await reader.read();
|
195
|
-
return done ? { done: true, value: void 0 } : { done: false, value };
|
196
|
-
}
|
197
|
-
};
|
198
|
-
};
|
199
|
-
return stream;
|
200
|
-
}
|
201
|
-
|
202
|
-
// src/data-stream/data-stream-parts.ts
|
203
|
-
import { z } from "zod";
|
204
|
-
var languageModelUsageSchema = z.object({
|
205
|
-
inputTokens: z.number().optional(),
|
206
|
-
outputTokens: z.number().optional(),
|
207
|
-
totalTokens: z.number().optional(),
|
208
|
-
reasoningTokens: z.number().optional(),
|
209
|
-
cachedInputTokens: z.number().optional()
|
210
|
-
});
|
211
|
-
var finishReasonSchema = z.enum([
|
212
|
-
"stop",
|
213
|
-
"length",
|
214
|
-
"tool-calls",
|
215
|
-
"content-filter",
|
216
|
-
"other",
|
217
|
-
"error",
|
218
|
-
"unknown"
|
219
|
-
]);
|
220
|
-
var toolCallSchema = z.object({
|
221
|
-
toolCallId: z.string(),
|
222
|
-
toolName: z.string(),
|
223
|
-
args: z.unknown()
|
224
|
-
});
|
225
|
-
var toolResultValueSchema = z.object({
|
226
|
-
toolCallId: z.string(),
|
227
|
-
result: z.unknown(),
|
228
|
-
providerMetadata: z.any().optional()
|
229
|
-
});
|
230
|
-
var sourceSchema = z.object({
|
231
|
-
type: z.literal("source"),
|
232
|
-
sourceType: z.literal("url"),
|
233
|
-
id: z.string(),
|
234
|
-
url: z.string(),
|
235
|
-
title: z.string().optional(),
|
236
|
-
providerMetadata: z.any().optional()
|
237
|
-
// Use z.any() for generic metadata
|
238
|
-
});
|
239
|
-
var dataStreamPartSchema = z.discriminatedUnion("type", [
|
240
|
-
z.object({
|
241
|
-
type: z.literal("text"),
|
242
|
-
value: z.string()
|
243
|
-
}),
|
244
|
-
z.object({
|
245
|
-
type: z.literal("data"),
|
246
|
-
value: z.array(z.any())
|
247
|
-
// TODO json validation
|
248
|
-
}),
|
249
|
-
z.object({
|
250
|
-
type: z.literal("error"),
|
251
|
-
value: z.string()
|
252
|
-
}),
|
253
|
-
z.object({
|
254
|
-
type: z.literal("message-annotations"),
|
255
|
-
value: z.array(z.any())
|
256
|
-
// TODO json validation
|
257
|
-
}),
|
258
|
-
z.object({
|
259
|
-
type: z.literal("tool-call"),
|
260
|
-
value: toolCallSchema
|
261
|
-
}),
|
262
|
-
z.object({
|
263
|
-
type: z.literal("tool-result"),
|
264
|
-
value: toolResultValueSchema
|
265
|
-
}),
|
266
|
-
z.object({
|
267
|
-
type: z.literal("tool-call-streaming-start"),
|
268
|
-
value: z.object({ toolCallId: z.string(), toolName: z.string() })
|
269
|
-
}),
|
270
|
-
z.object({
|
271
|
-
type: z.literal("tool-call-delta"),
|
272
|
-
value: z.object({ toolCallId: z.string(), argsTextDelta: z.string() })
|
273
|
-
}),
|
274
|
-
z.object({
|
275
|
-
type: z.literal("finish-message"),
|
276
|
-
value: z.object({
|
277
|
-
finishReason: finishReasonSchema,
|
278
|
-
// TODO v5 remove usage from finish event (only on step-finish)
|
279
|
-
usage: languageModelUsageSchema.optional()
|
280
|
-
})
|
281
|
-
}),
|
282
|
-
z.object({
|
283
|
-
type: z.literal("finish-step"),
|
284
|
-
value: z.object({
|
285
|
-
isContinued: z.boolean(),
|
286
|
-
finishReason: finishReasonSchema,
|
287
|
-
usage: languageModelUsageSchema.optional()
|
288
|
-
})
|
289
|
-
}),
|
290
|
-
z.object({
|
291
|
-
type: z.literal("start-step"),
|
292
|
-
value: z.object({
|
293
|
-
messageId: z.string()
|
294
|
-
})
|
295
|
-
}),
|
296
|
-
z.object({
|
297
|
-
type: z.literal("reasoning"),
|
298
|
-
value: z.object({
|
299
|
-
text: z.string(),
|
300
|
-
providerMetadata: z.record(z.any()).optional()
|
301
|
-
})
|
302
|
-
}),
|
303
|
-
z.object({
|
304
|
-
type: z.literal("source"),
|
305
|
-
value: sourceSchema
|
306
|
-
}),
|
307
|
-
z.object({
|
308
|
-
type: z.literal("file"),
|
309
|
-
value: z.object({
|
310
|
-
url: z.string(),
|
311
|
-
mediaType: z.string()
|
312
|
-
})
|
313
|
-
}),
|
314
|
-
z.object({
|
315
|
-
type: z.literal("reasoning-part-finish"),
|
316
|
-
value: z.null()
|
317
|
-
})
|
318
|
-
]);
|
319
|
-
|
320
|
-
// src/data-stream/process-data-stream.ts
|
321
|
-
async function processDataStream({
|
322
|
-
stream,
|
323
|
-
onTextPart,
|
324
|
-
onReasoningPart,
|
325
|
-
onReasoningPartFinish,
|
326
|
-
onSourcePart,
|
327
|
-
onFilePart,
|
328
|
-
onDataPart,
|
329
|
-
onErrorPart,
|
330
|
-
onToolCallStreamingStartPart,
|
331
|
-
onToolCallDeltaPart,
|
332
|
-
onToolCallPart,
|
333
|
-
onToolResultPart,
|
334
|
-
onMessageAnnotationsPart,
|
335
|
-
onFinishMessagePart,
|
336
|
-
onFinishStepPart,
|
337
|
-
onStartStepPart
|
338
|
-
}) {
|
339
|
-
const streamParts = createAsyncIterableStream(
|
340
|
-
stream.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
|
341
|
-
new TransformStream({
|
342
|
-
async transform({ data }, controller) {
|
343
|
-
if (data === "[DONE]") {
|
344
|
-
return;
|
345
|
-
}
|
346
|
-
controller.enqueue(
|
347
|
-
await safeParseJSON({
|
348
|
-
text: data,
|
349
|
-
schema: dataStreamPartSchema
|
350
|
-
})
|
351
|
-
);
|
352
|
-
}
|
353
|
-
})
|
354
|
-
)
|
355
|
-
);
|
356
|
-
for await (const parseResult of streamParts) {
|
357
|
-
if (!parseResult.success) {
|
358
|
-
throw new Error("Failed to parse data stream part");
|
359
|
-
}
|
360
|
-
const { type, value } = parseResult.value;
|
361
|
-
switch (type) {
|
362
|
-
case "text":
|
363
|
-
await (onTextPart == null ? void 0 : onTextPart(value));
|
364
|
-
break;
|
365
|
-
case "reasoning":
|
366
|
-
await (onReasoningPart == null ? void 0 : onReasoningPart(value));
|
367
|
-
break;
|
368
|
-
case "reasoning-part-finish":
|
369
|
-
await (onReasoningPartFinish == null ? void 0 : onReasoningPartFinish(value));
|
370
|
-
break;
|
371
|
-
case "file":
|
372
|
-
await (onFilePart == null ? void 0 : onFilePart(value));
|
373
|
-
break;
|
374
|
-
case "source":
|
375
|
-
await (onSourcePart == null ? void 0 : onSourcePart(value));
|
376
|
-
break;
|
377
|
-
case "data":
|
378
|
-
await (onDataPart == null ? void 0 : onDataPart(value));
|
379
|
-
break;
|
380
|
-
case "error":
|
381
|
-
await (onErrorPart == null ? void 0 : onErrorPart(value));
|
382
|
-
break;
|
383
|
-
case "message-annotations":
|
384
|
-
await (onMessageAnnotationsPart == null ? void 0 : onMessageAnnotationsPart(value));
|
385
|
-
break;
|
386
|
-
case "tool-call-streaming-start":
|
387
|
-
await (onToolCallStreamingStartPart == null ? void 0 : onToolCallStreamingStartPart(value));
|
388
|
-
break;
|
389
|
-
case "tool-call-delta":
|
390
|
-
await (onToolCallDeltaPart == null ? void 0 : onToolCallDeltaPart(value));
|
391
|
-
break;
|
392
|
-
case "tool-call":
|
393
|
-
await (onToolCallPart == null ? void 0 : onToolCallPart(value));
|
394
|
-
break;
|
395
|
-
case "tool-result":
|
396
|
-
await (onToolResultPart == null ? void 0 : onToolResultPart(value));
|
397
|
-
break;
|
398
|
-
case "finish-message":
|
399
|
-
await (onFinishMessagePart == null ? void 0 : onFinishMessagePart(value));
|
400
|
-
break;
|
401
|
-
case "finish-step":
|
402
|
-
await (onFinishStepPart == null ? void 0 : onFinishStepPart(value));
|
403
|
-
break;
|
404
|
-
case "start-step":
|
405
|
-
await (onStartStepPart == null ? void 0 : onStartStepPart(value));
|
406
|
-
break;
|
407
|
-
default: {
|
408
|
-
const exhaustiveCheck = type;
|
409
|
-
throw new Error(`Unknown stream part type: ${exhaustiveCheck}`);
|
410
|
-
}
|
411
|
-
}
|
412
|
-
}
|
413
|
-
}
|
414
|
-
|
415
15
|
// src/error/index.ts
|
416
16
|
import {
|
417
17
|
AISDKError as AISDKError16,
|
@@ -774,6 +374,17 @@ var RetryError = class extends AISDKError15 {
|
|
774
374
|
};
|
775
375
|
_a15 = symbol15;
|
776
376
|
|
377
|
+
// src/util/prepare-headers.ts
|
378
|
+
function prepareHeaders(headers, defaultHeaders) {
|
379
|
+
const responseHeaders = new Headers(headers != null ? headers : {});
|
380
|
+
for (const [key, value] of Object.entries(defaultHeaders)) {
|
381
|
+
if (!responseHeaders.has(key)) {
|
382
|
+
responseHeaders.set(key, value);
|
383
|
+
}
|
384
|
+
}
|
385
|
+
return responseHeaders;
|
386
|
+
}
|
387
|
+
|
777
388
|
// src/text-stream/create-text-stream-response.ts
|
778
389
|
function createTextStreamResponse({
|
779
390
|
status,
|
@@ -790,6 +401,33 @@ function createTextStreamResponse({
|
|
790
401
|
});
|
791
402
|
}
|
792
403
|
|
404
|
+
// src/util/write-to-server-response.ts
|
405
|
+
function writeToServerResponse({
|
406
|
+
response,
|
407
|
+
status,
|
408
|
+
statusText,
|
409
|
+
headers,
|
410
|
+
stream
|
411
|
+
}) {
|
412
|
+
response.writeHead(status != null ? status : 200, statusText, headers);
|
413
|
+
const reader = stream.getReader();
|
414
|
+
const read = async () => {
|
415
|
+
try {
|
416
|
+
while (true) {
|
417
|
+
const { done, value } = await reader.read();
|
418
|
+
if (done)
|
419
|
+
break;
|
420
|
+
response.write(value);
|
421
|
+
}
|
422
|
+
} catch (error) {
|
423
|
+
throw error;
|
424
|
+
} finally {
|
425
|
+
response.end();
|
426
|
+
}
|
427
|
+
};
|
428
|
+
read();
|
429
|
+
}
|
430
|
+
|
793
431
|
// src/text-stream/pipe-text-stream-to-response.ts
|
794
432
|
function pipeTextStreamToResponse({
|
795
433
|
response,
|
@@ -821,271 +459,170 @@ function appendClientMessage({
|
|
821
459
|
message
|
822
460
|
];
|
823
461
|
}
|
824
|
-
|
825
|
-
// src/ui/
|
826
|
-
import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
|
827
|
-
|
828
|
-
// src/ui/extract-max-tool-invocation-step.ts
|
829
|
-
function extractMaxToolInvocationStep(toolInvocations) {
|
830
|
-
return toolInvocations == null ? void 0 : toolInvocations.reduce((max, toolInvocation) => {
|
831
|
-
var _a17;
|
832
|
-
return Math.max(max, (_a17 = toolInvocation.step) != null ? _a17 : 0);
|
833
|
-
}, 0);
|
834
|
-
}
|
835
|
-
|
836
|
-
// src/ui/get-tool-invocations.ts
|
837
|
-
function getToolInvocations(message) {
|
838
|
-
return message.parts.filter(
|
839
|
-
(part) => part.type === "tool-invocation"
|
840
|
-
).map((part) => part.toolInvocation);
|
841
|
-
}
|
842
|
-
|
843
|
-
// core/prompt/data-content.ts
|
844
|
-
import { AISDKError as AISDKError17 } from "@ai-sdk/provider";
|
462
|
+
|
463
|
+
// src/ui/call-chat-api.ts
|
845
464
|
import {
|
846
|
-
|
847
|
-
convertUint8ArrayToBase64
|
465
|
+
parseJsonEventStream
|
848
466
|
} from "@ai-sdk/provider-utils";
|
849
|
-
import { z as z2 } from "zod";
|
850
467
|
|
851
|
-
//
|
852
|
-
|
468
|
+
// src/ui-message-stream/ui-message-stream-parts.ts
|
469
|
+
import { z } from "zod";
|
470
|
+
var toolCallSchema = z.object({
|
471
|
+
toolCallId: z.string(),
|
472
|
+
toolName: z.string(),
|
473
|
+
args: z.unknown()
|
474
|
+
});
|
475
|
+
var toolResultValueSchema = z.object({
|
476
|
+
toolCallId: z.string(),
|
477
|
+
result: z.unknown(),
|
478
|
+
providerMetadata: z.any().optional()
|
479
|
+
});
|
480
|
+
var sourceSchema = z.object({
|
481
|
+
type: z.literal("source"),
|
482
|
+
sourceType: z.literal("url"),
|
483
|
+
id: z.string(),
|
484
|
+
url: z.string(),
|
485
|
+
title: z.string().optional(),
|
486
|
+
providerMetadata: z.any().optional()
|
487
|
+
// Use z.any() for generic metadata
|
488
|
+
});
|
489
|
+
var uiMessageStreamPartSchema = z.discriminatedUnion("type", [
|
490
|
+
z.object({
|
491
|
+
type: z.literal("text"),
|
492
|
+
value: z.string()
|
493
|
+
}),
|
494
|
+
z.object({
|
495
|
+
type: z.literal("error"),
|
496
|
+
value: z.string()
|
497
|
+
}),
|
498
|
+
z.object({
|
499
|
+
type: z.literal("tool-call"),
|
500
|
+
value: toolCallSchema
|
501
|
+
}),
|
502
|
+
z.object({
|
503
|
+
type: z.literal("tool-result"),
|
504
|
+
value: toolResultValueSchema
|
505
|
+
}),
|
506
|
+
z.object({
|
507
|
+
type: z.literal("tool-call-streaming-start"),
|
508
|
+
value: z.object({ toolCallId: z.string(), toolName: z.string() })
|
509
|
+
}),
|
510
|
+
z.object({
|
511
|
+
type: z.literal("tool-call-delta"),
|
512
|
+
value: z.object({ toolCallId: z.string(), argsTextDelta: z.string() })
|
513
|
+
}),
|
514
|
+
z.object({
|
515
|
+
type: z.literal("reasoning"),
|
516
|
+
value: z.object({
|
517
|
+
text: z.string(),
|
518
|
+
providerMetadata: z.record(z.any()).optional()
|
519
|
+
})
|
520
|
+
}),
|
521
|
+
z.object({
|
522
|
+
type: z.literal("source"),
|
523
|
+
value: sourceSchema
|
524
|
+
}),
|
525
|
+
z.object({
|
526
|
+
type: z.literal("file"),
|
527
|
+
value: z.object({
|
528
|
+
url: z.string(),
|
529
|
+
mediaType: z.string()
|
530
|
+
})
|
531
|
+
}),
|
532
|
+
z.object({
|
533
|
+
type: z.literal("metadata"),
|
534
|
+
value: z.object({
|
535
|
+
metadata: z.unknown()
|
536
|
+
})
|
537
|
+
}),
|
538
|
+
z.object({
|
539
|
+
type: z.literal("start-step"),
|
540
|
+
value: z.object({
|
541
|
+
metadata: z.unknown()
|
542
|
+
})
|
543
|
+
}),
|
544
|
+
z.object({
|
545
|
+
type: z.literal("finish-step"),
|
546
|
+
value: z.object({
|
547
|
+
metadata: z.unknown()
|
548
|
+
})
|
549
|
+
}),
|
550
|
+
z.object({
|
551
|
+
type: z.literal("start"),
|
552
|
+
value: z.object({
|
553
|
+
messageId: z.string().optional(),
|
554
|
+
metadata: z.unknown()
|
555
|
+
})
|
556
|
+
}),
|
557
|
+
z.object({
|
558
|
+
type: z.literal("finish"),
|
559
|
+
value: z.object({
|
560
|
+
metadata: z.unknown()
|
561
|
+
})
|
562
|
+
}),
|
563
|
+
z.object({
|
564
|
+
type: z.literal("reasoning-part-finish"),
|
565
|
+
value: z.null()
|
566
|
+
})
|
567
|
+
]);
|
568
|
+
|
569
|
+
// src/util/consume-stream.ts
|
570
|
+
async function consumeStream({
|
571
|
+
stream,
|
572
|
+
onError
|
573
|
+
}) {
|
574
|
+
const reader = stream.getReader();
|
853
575
|
try {
|
854
|
-
|
855
|
-
|
856
|
-
|
857
|
-
|
858
|
-
}
|
576
|
+
while (true) {
|
577
|
+
const { done } = await reader.read();
|
578
|
+
if (done)
|
579
|
+
break;
|
580
|
+
}
|
859
581
|
} catch (error) {
|
860
|
-
|
861
|
-
|
862
|
-
|
863
|
-
};
|
582
|
+
onError == null ? void 0 : onError(error);
|
583
|
+
} finally {
|
584
|
+
reader.releaseLock();
|
864
585
|
}
|
865
586
|
}
|
866
587
|
|
867
|
-
//
|
868
|
-
|
869
|
-
|
870
|
-
|
871
|
-
|
872
|
-
|
873
|
-
|
874
|
-
(value) => {
|
875
|
-
var _a17, _b;
|
876
|
-
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
877
|
-
},
|
878
|
-
{ message: "Must be a Buffer" }
|
879
|
-
)
|
880
|
-
]);
|
881
|
-
function convertToLanguageModelV2DataContent(content) {
|
882
|
-
if (content instanceof Uint8Array) {
|
883
|
-
return { data: content, mediaType: void 0 };
|
884
|
-
}
|
885
|
-
if (content instanceof ArrayBuffer) {
|
886
|
-
return { data: new Uint8Array(content), mediaType: void 0 };
|
887
|
-
}
|
888
|
-
if (typeof content === "string") {
|
889
|
-
try {
|
890
|
-
content = new URL(content);
|
891
|
-
} catch (error) {
|
892
|
-
}
|
893
|
-
}
|
894
|
-
if (content instanceof URL && content.protocol === "data:") {
|
895
|
-
const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
|
896
|
-
content.toString()
|
897
|
-
);
|
898
|
-
if (dataUrlMediaType == null || base64Content == null) {
|
899
|
-
throw new AISDKError17({
|
900
|
-
name: "InvalidDataContentError",
|
901
|
-
message: `Invalid data URL format in content ${content.toString()}`
|
902
|
-
});
|
903
|
-
}
|
904
|
-
return { data: base64Content, mediaType: dataUrlMediaType };
|
905
|
-
}
|
906
|
-
return { data: content, mediaType: void 0 };
|
907
|
-
}
|
908
|
-
function convertDataContentToBase64String(content) {
|
909
|
-
if (typeof content === "string") {
|
910
|
-
return content;
|
911
|
-
}
|
912
|
-
if (content instanceof ArrayBuffer) {
|
913
|
-
return convertUint8ArrayToBase64(new Uint8Array(content));
|
914
|
-
}
|
915
|
-
return convertUint8ArrayToBase64(content);
|
916
|
-
}
|
917
|
-
function convertDataContentToUint8Array(content) {
|
918
|
-
if (content instanceof Uint8Array) {
|
919
|
-
return content;
|
588
|
+
// src/ui/process-ui-message-stream.ts
|
589
|
+
import { validateTypes } from "@ai-sdk/provider-utils";
|
590
|
+
|
591
|
+
// src/util/merge-objects.ts
|
592
|
+
function mergeObjects(base, overrides) {
|
593
|
+
if (base === void 0 && overrides === void 0) {
|
594
|
+
return void 0;
|
920
595
|
}
|
921
|
-
if (
|
922
|
-
|
923
|
-
return convertBase64ToUint8Array(content);
|
924
|
-
} catch (error) {
|
925
|
-
throw new InvalidDataContentError({
|
926
|
-
message: "Invalid data content. Content string is not a base64-encoded media.",
|
927
|
-
content,
|
928
|
-
cause: error
|
929
|
-
});
|
930
|
-
}
|
596
|
+
if (base === void 0) {
|
597
|
+
return overrides;
|
931
598
|
}
|
932
|
-
if (
|
933
|
-
return
|
599
|
+
if (overrides === void 0) {
|
600
|
+
return base;
|
934
601
|
}
|
935
|
-
|
936
|
-
|
937
|
-
|
938
|
-
|
939
|
-
|
940
|
-
|
941
|
-
|
942
|
-
|
943
|
-
|
944
|
-
|
945
|
-
|
946
|
-
|
947
|
-
|
948
|
-
|
949
|
-
|
950
|
-
|
951
|
-
case "assistant": {
|
952
|
-
let getToolInvocationsForStep2 = function(step) {
|
953
|
-
return (typeof message.content === "string" ? [] : message.content.filter((part) => part.type === "tool-call")).map((call) => ({
|
954
|
-
state: "call",
|
955
|
-
step,
|
956
|
-
args: call.args,
|
957
|
-
toolCallId: call.toolCallId,
|
958
|
-
toolName: call.toolName
|
959
|
-
}));
|
960
|
-
};
|
961
|
-
var getToolInvocationsForStep = getToolInvocationsForStep2;
|
962
|
-
const parts = [{ type: "step-start" }];
|
963
|
-
let textContent = "";
|
964
|
-
let reasoningTextContent = void 0;
|
965
|
-
if (typeof message.content === "string") {
|
966
|
-
textContent = message.content;
|
967
|
-
parts.push({
|
968
|
-
type: "text",
|
969
|
-
text: message.content
|
970
|
-
});
|
971
|
-
} else {
|
972
|
-
let reasoningPart = void 0;
|
973
|
-
for (const part of message.content) {
|
974
|
-
switch (part.type) {
|
975
|
-
case "text": {
|
976
|
-
reasoningPart = void 0;
|
977
|
-
textContent += part.text;
|
978
|
-
parts.push({
|
979
|
-
type: "text",
|
980
|
-
text: part.text
|
981
|
-
});
|
982
|
-
break;
|
983
|
-
}
|
984
|
-
case "reasoning": {
|
985
|
-
if (reasoningPart == null) {
|
986
|
-
reasoningPart = {
|
987
|
-
type: "reasoning",
|
988
|
-
text: ""
|
989
|
-
};
|
990
|
-
parts.push(reasoningPart);
|
991
|
-
}
|
992
|
-
reasoningTextContent = (reasoningTextContent != null ? reasoningTextContent : "") + part.text;
|
993
|
-
reasoningPart.text += part.text;
|
994
|
-
reasoningPart.providerMetadata = part.providerOptions;
|
995
|
-
break;
|
996
|
-
}
|
997
|
-
case "tool-call":
|
998
|
-
break;
|
999
|
-
case "file":
|
1000
|
-
if (part.data instanceof URL) {
|
1001
|
-
throw new AISDKError18({
|
1002
|
-
name: "InvalidAssistantFileData",
|
1003
|
-
message: "File data cannot be a URL"
|
1004
|
-
});
|
1005
|
-
}
|
1006
|
-
parts.push({
|
1007
|
-
type: "file",
|
1008
|
-
mediaType: part.mediaType,
|
1009
|
-
url: `data:${part.mediaType};base64,${convertDataContentToBase64String(part.data)}`
|
1010
|
-
});
|
1011
|
-
break;
|
1012
|
-
}
|
1013
|
-
}
|
1014
|
-
}
|
1015
|
-
if (isLastMessageAssistant) {
|
1016
|
-
const maxStep = extractMaxToolInvocationStep(
|
1017
|
-
getToolInvocations(lastMessage)
|
1018
|
-
);
|
1019
|
-
(_a17 = lastMessage.parts) != null ? _a17 : lastMessage.parts = [];
|
1020
|
-
lastMessage.parts.push(...parts);
|
1021
|
-
getToolInvocationsForStep2(maxStep === void 0 ? 0 : maxStep + 1).map((call) => ({
|
1022
|
-
type: "tool-invocation",
|
1023
|
-
toolInvocation: call
|
1024
|
-
})).forEach((part) => {
|
1025
|
-
lastMessage.parts.push(part);
|
1026
|
-
});
|
1027
|
-
} else {
|
1028
|
-
clonedMessages.push({
|
1029
|
-
role: "assistant",
|
1030
|
-
id: message.id,
|
1031
|
-
createdAt: currentDate(),
|
1032
|
-
// generate a createdAt date for the message, will be overridden by the client
|
1033
|
-
parts: [
|
1034
|
-
...parts,
|
1035
|
-
...getToolInvocationsForStep2(0).map((call) => ({
|
1036
|
-
type: "tool-invocation",
|
1037
|
-
toolInvocation: call
|
1038
|
-
}))
|
1039
|
-
]
|
1040
|
-
});
|
1041
|
-
}
|
1042
|
-
break;
|
1043
|
-
}
|
1044
|
-
case "tool": {
|
1045
|
-
if (lastMessage.role !== "assistant") {
|
1046
|
-
throw new Error(
|
1047
|
-
`Tool result must follow an assistant message: ${lastMessage.role}`
|
1048
|
-
);
|
1049
|
-
}
|
1050
|
-
(_b = lastMessage.parts) != null ? _b : lastMessage.parts = [];
|
1051
|
-
for (const contentPart of message.content) {
|
1052
|
-
const toolCall = getToolInvocations(lastMessage).find(
|
1053
|
-
(call) => call.toolCallId === contentPart.toolCallId
|
1054
|
-
);
|
1055
|
-
const toolCallPart = lastMessage.parts.find(
|
1056
|
-
(part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === contentPart.toolCallId
|
1057
|
-
);
|
1058
|
-
if (!toolCall) {
|
1059
|
-
throw new Error("Tool call not found in previous message");
|
1060
|
-
}
|
1061
|
-
toolCall.state = "result";
|
1062
|
-
const toolResult = toolCall;
|
1063
|
-
toolResult.result = contentPart.result;
|
1064
|
-
if (toolCallPart) {
|
1065
|
-
toolCallPart.toolInvocation = toolResult;
|
1066
|
-
} else {
|
1067
|
-
lastMessage.parts.push({
|
1068
|
-
type: "tool-invocation",
|
1069
|
-
toolInvocation: toolResult
|
1070
|
-
});
|
1071
|
-
}
|
1072
|
-
}
|
1073
|
-
break;
|
1074
|
-
}
|
1075
|
-
default: {
|
1076
|
-
const _exhaustiveCheck = role;
|
1077
|
-
throw new Error(`Unsupported message role: ${_exhaustiveCheck}`);
|
602
|
+
const result = { ...base };
|
603
|
+
for (const key in overrides) {
|
604
|
+
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
|
605
|
+
const overridesValue = overrides[key];
|
606
|
+
if (overridesValue === void 0)
|
607
|
+
continue;
|
608
|
+
const baseValue = key in base ? base[key] : void 0;
|
609
|
+
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
|
610
|
+
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
|
611
|
+
if (isSourceObject && isTargetObject) {
|
612
|
+
result[key] = mergeObjects(
|
613
|
+
baseValue,
|
614
|
+
overridesValue
|
615
|
+
);
|
616
|
+
} else {
|
617
|
+
result[key] = overridesValue;
|
1078
618
|
}
|
1079
619
|
}
|
1080
620
|
}
|
1081
|
-
return
|
621
|
+
return result;
|
1082
622
|
}
|
1083
623
|
|
1084
|
-
// src/ui/process-chat-response.ts
|
1085
|
-
import { generateId as generateIdFunction } from "@ai-sdk/provider-utils";
|
1086
|
-
|
1087
624
|
// src/util/parse-partial-json.ts
|
1088
|
-
import { safeParseJSON
|
625
|
+
import { safeParseJSON } from "@ai-sdk/provider-utils";
|
1089
626
|
|
1090
627
|
// src/util/fix-json.ts
|
1091
628
|
function fixJson(input) {
|
@@ -1410,33 +947,48 @@ async function parsePartialJson(jsonText) {
|
|
1410
947
|
if (jsonText === void 0) {
|
1411
948
|
return { value: void 0, state: "undefined-input" };
|
1412
949
|
}
|
1413
|
-
let result = await
|
950
|
+
let result = await safeParseJSON({ text: jsonText });
|
1414
951
|
if (result.success) {
|
1415
952
|
return { value: result.value, state: "successful-parse" };
|
1416
953
|
}
|
1417
|
-
result = await
|
954
|
+
result = await safeParseJSON({ text: fixJson(jsonText) });
|
1418
955
|
if (result.success) {
|
1419
956
|
return { value: result.value, state: "repaired-parse" };
|
1420
957
|
}
|
1421
958
|
return { value: void 0, state: "failed-parse" };
|
1422
959
|
}
|
1423
960
|
|
1424
|
-
// src/ui/
|
1425
|
-
|
961
|
+
// src/ui/extract-max-tool-invocation-step.ts
|
962
|
+
function extractMaxToolInvocationStep(toolInvocations) {
|
963
|
+
return toolInvocations == null ? void 0 : toolInvocations.reduce((max, toolInvocation) => {
|
964
|
+
var _a17;
|
965
|
+
return Math.max(max, (_a17 = toolInvocation.step) != null ? _a17 : 0);
|
966
|
+
}, 0);
|
967
|
+
}
|
968
|
+
|
969
|
+
// src/ui/get-tool-invocations.ts
|
970
|
+
function getToolInvocations(message) {
|
971
|
+
return message.parts.filter(
|
972
|
+
(part) => part.type === "tool-invocation"
|
973
|
+
).map((part) => part.toolInvocation);
|
974
|
+
}
|
975
|
+
|
976
|
+
// src/ui/process-ui-message-stream.ts
|
977
|
+
function processUIMessageStream({
|
1426
978
|
stream,
|
1427
|
-
|
979
|
+
onUpdate,
|
1428
980
|
onToolCall,
|
1429
981
|
onFinish,
|
1430
|
-
|
1431
|
-
|
1432
|
-
|
982
|
+
lastMessage,
|
983
|
+
newMessageId,
|
984
|
+
messageMetadataSchema
|
1433
985
|
}) {
|
1434
986
|
var _a17;
|
1435
|
-
const
|
1436
|
-
let step =
|
1437
|
-
const message =
|
1438
|
-
id:
|
1439
|
-
|
987
|
+
const isContinuation = (lastMessage == null ? void 0 : lastMessage.role) === "assistant";
|
988
|
+
let step = isContinuation ? 1 + ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) : 0;
|
989
|
+
const message = isContinuation ? structuredClone(lastMessage) : {
|
990
|
+
id: newMessageId,
|
991
|
+
metadata: {},
|
1440
992
|
role: "assistant",
|
1441
993
|
parts: []
|
1442
994
|
};
|
@@ -1455,198 +1007,214 @@ async function processChatResponse({
|
|
1455
1007
|
});
|
1456
1008
|
}
|
1457
1009
|
}
|
1458
|
-
const data = [];
|
1459
|
-
let messageAnnotations = replaceLastMessage ? lastMessage == null ? void 0 : lastMessage.annotations : void 0;
|
1460
1010
|
const partialToolCalls = {};
|
1461
|
-
|
1462
|
-
|
1463
|
-
|
1464
|
-
|
1465
|
-
|
1466
|
-
|
1467
|
-
|
1468
|
-
const copiedData = [...data];
|
1469
|
-
if (messageAnnotations == null ? void 0 : messageAnnotations.length) {
|
1470
|
-
message.annotations = messageAnnotations;
|
1471
|
-
}
|
1472
|
-
const copiedMessage = {
|
1473
|
-
// deep copy the message to ensure that deep changes (msg attachments) are updated
|
1474
|
-
// with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
|
1475
|
-
...structuredClone(message),
|
1476
|
-
// add a revision id to ensure that the message is updated with SWR. SWR uses a
|
1477
|
-
// hashing approach by default to detect changes, but it only works for shallow
|
1478
|
-
// changes. This is why we need to add a revision id to ensure that the message
|
1479
|
-
// is updated with SWR (without it, the changes get stuck in SWR and are not
|
1480
|
-
// forwarded to rendering):
|
1481
|
-
revisionId: generateId3()
|
1482
|
-
};
|
1483
|
-
update({
|
1484
|
-
message: copiedMessage,
|
1485
|
-
data: copiedData,
|
1486
|
-
replaceLastMessage
|
1487
|
-
});
|
1488
|
-
}
|
1489
|
-
await processDataStream({
|
1490
|
-
stream,
|
1491
|
-
onTextPart(value) {
|
1492
|
-
if (currentTextPart == null) {
|
1493
|
-
currentTextPart = {
|
1494
|
-
type: "text",
|
1495
|
-
text: value
|
1496
|
-
};
|
1497
|
-
message.parts.push(currentTextPart);
|
1498
|
-
} else {
|
1499
|
-
currentTextPart.text += value;
|
1500
|
-
}
|
1501
|
-
execUpdate();
|
1502
|
-
},
|
1503
|
-
onReasoningPart(value) {
|
1504
|
-
if (currentReasoningPart == null) {
|
1505
|
-
currentReasoningPart = {
|
1506
|
-
type: "reasoning",
|
1507
|
-
text: value.text,
|
1508
|
-
providerMetadata: value.providerMetadata
|
1509
|
-
};
|
1510
|
-
message.parts.push(currentReasoningPart);
|
1511
|
-
} else {
|
1512
|
-
currentReasoningPart.text += value.text;
|
1513
|
-
currentReasoningPart.providerMetadata = value.providerMetadata;
|
1514
|
-
}
|
1515
|
-
execUpdate();
|
1516
|
-
},
|
1517
|
-
onReasoningPartFinish(value) {
|
1518
|
-
if (currentReasoningPart != null) {
|
1519
|
-
currentReasoningPart = void 0;
|
1520
|
-
}
|
1521
|
-
},
|
1522
|
-
onFilePart(value) {
|
1523
|
-
message.parts.push({
|
1524
|
-
type: "file",
|
1525
|
-
mediaType: value.mediaType,
|
1526
|
-
url: value.url
|
1527
|
-
});
|
1528
|
-
execUpdate();
|
1529
|
-
},
|
1530
|
-
onSourcePart(value) {
|
1531
|
-
message.parts.push({
|
1532
|
-
type: "source",
|
1533
|
-
source: value
|
1534
|
-
});
|
1535
|
-
execUpdate();
|
1536
|
-
},
|
1537
|
-
onToolCallStreamingStartPart(value) {
|
1538
|
-
const toolInvocations = getToolInvocations(message);
|
1539
|
-
partialToolCalls[value.toolCallId] = {
|
1540
|
-
text: "",
|
1541
|
-
step,
|
1542
|
-
toolName: value.toolName,
|
1543
|
-
index: toolInvocations.length
|
1544
|
-
};
|
1545
|
-
updateToolInvocationPart(value.toolCallId, {
|
1546
|
-
state: "partial-call",
|
1547
|
-
step,
|
1548
|
-
toolCallId: value.toolCallId,
|
1549
|
-
toolName: value.toolName,
|
1550
|
-
args: void 0
|
1551
|
-
});
|
1552
|
-
execUpdate();
|
1553
|
-
},
|
1554
|
-
async onToolCallDeltaPart(value) {
|
1555
|
-
const partialToolCall = partialToolCalls[value.toolCallId];
|
1556
|
-
partialToolCall.text += value.argsTextDelta;
|
1557
|
-
const { value: partialArgs } = await parsePartialJson(
|
1558
|
-
partialToolCall.text
|
1559
|
-
);
|
1560
|
-
updateToolInvocationPart(value.toolCallId, {
|
1561
|
-
state: "partial-call",
|
1562
|
-
step: partialToolCall.step,
|
1563
|
-
toolCallId: value.toolCallId,
|
1564
|
-
toolName: partialToolCall.toolName,
|
1565
|
-
args: partialArgs
|
1566
|
-
});
|
1567
|
-
execUpdate();
|
1568
|
-
},
|
1569
|
-
async onToolCallPart(value) {
|
1570
|
-
updateToolInvocationPart(value.toolCallId, {
|
1571
|
-
state: "call",
|
1572
|
-
step,
|
1573
|
-
...value
|
1574
|
-
});
|
1575
|
-
execUpdate();
|
1576
|
-
if (onToolCall) {
|
1577
|
-
const result = await onToolCall({
|
1578
|
-
toolCall: value
|
1011
|
+
async function updateMessageMetadata(metadata) {
|
1012
|
+
if (metadata != null) {
|
1013
|
+
const mergedMetadata = message.metadata != null ? mergeObjects(message.metadata, metadata) : metadata;
|
1014
|
+
if (messageMetadataSchema != null) {
|
1015
|
+
await validateTypes({
|
1016
|
+
value: mergedMetadata,
|
1017
|
+
schema: messageMetadataSchema
|
1579
1018
|
});
|
1580
|
-
if (result != null) {
|
1581
|
-
updateToolInvocationPart(value.toolCallId, {
|
1582
|
-
state: "result",
|
1583
|
-
step,
|
1584
|
-
...value,
|
1585
|
-
result
|
1586
|
-
});
|
1587
|
-
execUpdate();
|
1588
|
-
}
|
1589
|
-
}
|
1590
|
-
},
|
1591
|
-
onToolResultPart(value) {
|
1592
|
-
const toolInvocations = getToolInvocations(message);
|
1593
|
-
if (toolInvocations == null) {
|
1594
|
-
throw new Error("tool_result must be preceded by a tool_call");
|
1595
|
-
}
|
1596
|
-
const toolInvocationIndex = toolInvocations.findIndex(
|
1597
|
-
(invocation) => invocation.toolCallId === value.toolCallId
|
1598
|
-
);
|
1599
|
-
if (toolInvocationIndex === -1) {
|
1600
|
-
throw new Error(
|
1601
|
-
"tool_result must be preceded by a tool_call with the same toolCallId"
|
1602
|
-
);
|
1603
|
-
}
|
1604
|
-
updateToolInvocationPart(value.toolCallId, {
|
1605
|
-
...toolInvocations[toolInvocationIndex],
|
1606
|
-
state: "result",
|
1607
|
-
...value
|
1608
|
-
});
|
1609
|
-
execUpdate();
|
1610
|
-
},
|
1611
|
-
onDataPart(value) {
|
1612
|
-
data.push(...value);
|
1613
|
-
execUpdate();
|
1614
|
-
},
|
1615
|
-
onMessageAnnotationsPart(value) {
|
1616
|
-
if (messageAnnotations == null) {
|
1617
|
-
messageAnnotations = [...value];
|
1618
|
-
} else {
|
1619
|
-
messageAnnotations.push(...value);
|
1620
1019
|
}
|
1621
|
-
|
1622
|
-
},
|
1623
|
-
onFinishStepPart(value) {
|
1624
|
-
step += 1;
|
1625
|
-
currentTextPart = value.isContinued ? currentTextPart : void 0;
|
1626
|
-
currentReasoningPart = void 0;
|
1627
|
-
},
|
1628
|
-
onStartStepPart(value) {
|
1629
|
-
if (!replaceLastMessage) {
|
1630
|
-
message.id = value.messageId;
|
1631
|
-
}
|
1632
|
-
message.parts.push({ type: "step-start" });
|
1633
|
-
execUpdate();
|
1634
|
-
},
|
1635
|
-
onFinishMessagePart(value) {
|
1636
|
-
finishReason = value.finishReason;
|
1637
|
-
if (value.usage != null) {
|
1638
|
-
usage = value.usage;
|
1639
|
-
}
|
1640
|
-
},
|
1641
|
-
onErrorPart(error) {
|
1642
|
-
throw new Error(error);
|
1020
|
+
message.metadata = mergedMetadata;
|
1643
1021
|
}
|
1644
|
-
}
|
1645
|
-
|
1022
|
+
}
|
1023
|
+
return stream.pipeThrough(
|
1024
|
+
new TransformStream({
|
1025
|
+
async transform(chunk, controller) {
|
1026
|
+
const { type, value } = chunk;
|
1027
|
+
switch (type) {
|
1028
|
+
case "text": {
|
1029
|
+
if (currentTextPart == null) {
|
1030
|
+
currentTextPart = {
|
1031
|
+
type: "text",
|
1032
|
+
text: value
|
1033
|
+
};
|
1034
|
+
message.parts.push(currentTextPart);
|
1035
|
+
} else {
|
1036
|
+
currentTextPart.text += value;
|
1037
|
+
}
|
1038
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1039
|
+
break;
|
1040
|
+
}
|
1041
|
+
case "reasoning": {
|
1042
|
+
if (currentReasoningPart == null) {
|
1043
|
+
currentReasoningPart = {
|
1044
|
+
type: "reasoning",
|
1045
|
+
text: value.text,
|
1046
|
+
providerMetadata: value.providerMetadata
|
1047
|
+
};
|
1048
|
+
message.parts.push(currentReasoningPart);
|
1049
|
+
} else {
|
1050
|
+
currentReasoningPart.text += value.text;
|
1051
|
+
currentReasoningPart.providerMetadata = value.providerMetadata;
|
1052
|
+
}
|
1053
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1054
|
+
break;
|
1055
|
+
}
|
1056
|
+
case "reasoning-part-finish": {
|
1057
|
+
if (currentReasoningPart != null) {
|
1058
|
+
currentReasoningPart = void 0;
|
1059
|
+
}
|
1060
|
+
break;
|
1061
|
+
}
|
1062
|
+
case "file": {
|
1063
|
+
message.parts.push({
|
1064
|
+
type: "file",
|
1065
|
+
mediaType: value.mediaType,
|
1066
|
+
url: value.url
|
1067
|
+
});
|
1068
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1069
|
+
break;
|
1070
|
+
}
|
1071
|
+
case "source": {
|
1072
|
+
message.parts.push({
|
1073
|
+
type: "source",
|
1074
|
+
source: value
|
1075
|
+
});
|
1076
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1077
|
+
break;
|
1078
|
+
}
|
1079
|
+
case "tool-call-streaming-start": {
|
1080
|
+
const toolInvocations = getToolInvocations(message);
|
1081
|
+
partialToolCalls[value.toolCallId] = {
|
1082
|
+
text: "",
|
1083
|
+
step,
|
1084
|
+
toolName: value.toolName,
|
1085
|
+
index: toolInvocations.length
|
1086
|
+
};
|
1087
|
+
updateToolInvocationPart(value.toolCallId, {
|
1088
|
+
state: "partial-call",
|
1089
|
+
step,
|
1090
|
+
toolCallId: value.toolCallId,
|
1091
|
+
toolName: value.toolName,
|
1092
|
+
args: void 0
|
1093
|
+
});
|
1094
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1095
|
+
break;
|
1096
|
+
}
|
1097
|
+
case "tool-call-delta": {
|
1098
|
+
const partialToolCall = partialToolCalls[value.toolCallId];
|
1099
|
+
partialToolCall.text += value.argsTextDelta;
|
1100
|
+
const { value: partialArgs } = await parsePartialJson(
|
1101
|
+
partialToolCall.text
|
1102
|
+
);
|
1103
|
+
updateToolInvocationPart(value.toolCallId, {
|
1104
|
+
state: "partial-call",
|
1105
|
+
step: partialToolCall.step,
|
1106
|
+
toolCallId: value.toolCallId,
|
1107
|
+
toolName: partialToolCall.toolName,
|
1108
|
+
args: partialArgs
|
1109
|
+
});
|
1110
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1111
|
+
break;
|
1112
|
+
}
|
1113
|
+
case "tool-call": {
|
1114
|
+
const call = { args: value.args, ...value };
|
1115
|
+
updateToolInvocationPart(value.toolCallId, {
|
1116
|
+
state: "call",
|
1117
|
+
step,
|
1118
|
+
...call
|
1119
|
+
});
|
1120
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1121
|
+
if (onToolCall) {
|
1122
|
+
const result = await onToolCall({
|
1123
|
+
toolCall: call
|
1124
|
+
});
|
1125
|
+
if (result != null) {
|
1126
|
+
updateToolInvocationPart(value.toolCallId, {
|
1127
|
+
state: "result",
|
1128
|
+
step,
|
1129
|
+
...call,
|
1130
|
+
result
|
1131
|
+
});
|
1132
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1133
|
+
}
|
1134
|
+
}
|
1135
|
+
break;
|
1136
|
+
}
|
1137
|
+
case "tool-result": {
|
1138
|
+
const toolInvocations = getToolInvocations(message);
|
1139
|
+
if (toolInvocations == null) {
|
1140
|
+
throw new Error("tool_result must be preceded by a tool_call");
|
1141
|
+
}
|
1142
|
+
const toolInvocationIndex = toolInvocations.findIndex(
|
1143
|
+
(invocation) => invocation.toolCallId === value.toolCallId
|
1144
|
+
);
|
1145
|
+
if (toolInvocationIndex === -1) {
|
1146
|
+
throw new Error(
|
1147
|
+
"tool_result must be preceded by a tool_call with the same toolCallId"
|
1148
|
+
);
|
1149
|
+
}
|
1150
|
+
const result = { result: value.result, ...value };
|
1151
|
+
updateToolInvocationPart(value.toolCallId, {
|
1152
|
+
...toolInvocations[toolInvocationIndex],
|
1153
|
+
state: "result",
|
1154
|
+
...result
|
1155
|
+
});
|
1156
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1157
|
+
break;
|
1158
|
+
}
|
1159
|
+
case "start-step": {
|
1160
|
+
message.parts.push({ type: "step-start" });
|
1161
|
+
await updateMessageMetadata(value.metadata);
|
1162
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1163
|
+
break;
|
1164
|
+
}
|
1165
|
+
case "finish-step": {
|
1166
|
+
step += 1;
|
1167
|
+
currentTextPart = void 0;
|
1168
|
+
currentReasoningPart = void 0;
|
1169
|
+
await updateMessageMetadata(value.metadata);
|
1170
|
+
if (value.metadata != null) {
|
1171
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1172
|
+
}
|
1173
|
+
break;
|
1174
|
+
}
|
1175
|
+
case "start": {
|
1176
|
+
if (value.messageId != null) {
|
1177
|
+
message.id = value.messageId;
|
1178
|
+
}
|
1179
|
+
await updateMessageMetadata(value.metadata);
|
1180
|
+
if (value.messageId != null || value.metadata != null) {
|
1181
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1182
|
+
}
|
1183
|
+
break;
|
1184
|
+
}
|
1185
|
+
case "finish": {
|
1186
|
+
await updateMessageMetadata(value.metadata);
|
1187
|
+
if (value.metadata != null) {
|
1188
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1189
|
+
}
|
1190
|
+
break;
|
1191
|
+
}
|
1192
|
+
case "metadata": {
|
1193
|
+
await updateMessageMetadata(value.metadata);
|
1194
|
+
if (value.metadata != null) {
|
1195
|
+
onUpdate == null ? void 0 : onUpdate({ message });
|
1196
|
+
}
|
1197
|
+
break;
|
1198
|
+
}
|
1199
|
+
case "error": {
|
1200
|
+
throw new Error(value);
|
1201
|
+
}
|
1202
|
+
default: {
|
1203
|
+
const _exhaustiveCheck = type;
|
1204
|
+
throw new Error(`Unhandled stream part: ${_exhaustiveCheck}`);
|
1205
|
+
}
|
1206
|
+
}
|
1207
|
+
controller.enqueue(chunk);
|
1208
|
+
},
|
1209
|
+
flush() {
|
1210
|
+
onFinish == null ? void 0 : onFinish({ message });
|
1211
|
+
}
|
1212
|
+
})
|
1213
|
+
);
|
1646
1214
|
}
|
1647
1215
|
|
1648
1216
|
// src/ui/process-chat-text-response.ts
|
1649
|
-
import { generateId as
|
1217
|
+
import { generateId as generateIdFunction } from "@ai-sdk/provider-utils";
|
1650
1218
|
|
1651
1219
|
// src/ui/process-text-stream.ts
|
1652
1220
|
async function processTextStream({
|
@@ -1668,13 +1236,11 @@ async function processChatTextResponse({
|
|
1668
1236
|
stream,
|
1669
1237
|
update,
|
1670
1238
|
onFinish,
|
1671
|
-
|
1672
|
-
generateId: generateId3 = generateIdFunction2
|
1239
|
+
generateId: generateId3 = generateIdFunction
|
1673
1240
|
}) {
|
1674
1241
|
const textPart = { type: "text", text: "" };
|
1675
1242
|
const resultMessage = {
|
1676
1243
|
id: generateId3(),
|
1677
|
-
createdAt: getCurrentDate(),
|
1678
1244
|
role: "assistant",
|
1679
1245
|
parts: [textPart]
|
1680
1246
|
};
|
@@ -1682,21 +1248,10 @@ async function processChatTextResponse({
|
|
1682
1248
|
stream,
|
1683
1249
|
onTextPart: (chunk) => {
|
1684
1250
|
textPart.text += chunk;
|
1685
|
-
update({
|
1686
|
-
message: { ...resultMessage },
|
1687
|
-
data: [],
|
1688
|
-
replaceLastMessage: false
|
1689
|
-
});
|
1251
|
+
update({ message: { ...resultMessage } });
|
1690
1252
|
}
|
1691
1253
|
});
|
1692
|
-
onFinish == null ? void 0 : onFinish(resultMessage
|
1693
|
-
usage: {
|
1694
|
-
inputTokens: void 0,
|
1695
|
-
outputTokens: void 0,
|
1696
|
-
totalTokens: void 0
|
1697
|
-
},
|
1698
|
-
finishReason: "unknown"
|
1699
|
-
});
|
1254
|
+
onFinish == null ? void 0 : onFinish({ message: resultMessage });
|
1700
1255
|
}
|
1701
1256
|
|
1702
1257
|
// src/ui/call-chat-api.ts
|
@@ -1704,19 +1259,18 @@ var getOriginalFetch = () => fetch;
|
|
1704
1259
|
async function callChatApi({
|
1705
1260
|
api,
|
1706
1261
|
body,
|
1707
|
-
streamProtocol = "
|
1262
|
+
streamProtocol = "ui-message",
|
1708
1263
|
credentials,
|
1709
1264
|
headers,
|
1710
1265
|
abortController,
|
1711
|
-
onResponse,
|
1712
1266
|
onUpdate,
|
1713
1267
|
onFinish,
|
1714
1268
|
onToolCall,
|
1715
1269
|
generateId: generateId3,
|
1716
1270
|
fetch: fetch2 = getOriginalFetch(),
|
1717
1271
|
lastMessage,
|
1718
|
-
|
1719
|
-
|
1272
|
+
requestType = "generate",
|
1273
|
+
messageMetadataSchema
|
1720
1274
|
}) {
|
1721
1275
|
var _a17, _b, _c;
|
1722
1276
|
const response = requestType === "resume" ? await fetch2(`${api}?chatId=${body.id}`, {
|
@@ -1737,9 +1291,6 @@ async function callChatApi({
|
|
1737
1291
|
signal: (_b = abortController == null ? void 0 : abortController()) == null ? void 0 : _b.signal,
|
1738
1292
|
credentials
|
1739
1293
|
});
|
1740
|
-
if (onResponse != null) {
|
1741
|
-
await onResponse(response);
|
1742
|
-
}
|
1743
1294
|
if (!response.ok) {
|
1744
1295
|
throw new Error(
|
1745
1296
|
(_c = await response.text()) != null ? _c : "Failed to fetch the chat response."
|
@@ -1754,24 +1305,49 @@ async function callChatApi({
|
|
1754
1305
|
stream: response.body,
|
1755
1306
|
update: onUpdate,
|
1756
1307
|
onFinish,
|
1757
|
-
generateId: generateId3
|
1758
|
-
getCurrentDate
|
1308
|
+
generateId: generateId3
|
1759
1309
|
});
|
1760
1310
|
return;
|
1761
1311
|
}
|
1762
|
-
case "
|
1763
|
-
await
|
1764
|
-
stream:
|
1765
|
-
|
1766
|
-
|
1767
|
-
|
1768
|
-
|
1769
|
-
|
1770
|
-
|
1771
|
-
|
1772
|
-
|
1773
|
-
|
1774
|
-
|
1312
|
+
case "ui-message": {
|
1313
|
+
await consumeStream({
|
1314
|
+
stream: processUIMessageStream({
|
1315
|
+
stream: parseJsonEventStream({
|
1316
|
+
stream: response.body,
|
1317
|
+
schema: uiMessageStreamPartSchema
|
1318
|
+
}).pipeThrough(
|
1319
|
+
new TransformStream({
|
1320
|
+
async transform(part, controller) {
|
1321
|
+
if (!part.success) {
|
1322
|
+
throw part.error;
|
1323
|
+
}
|
1324
|
+
controller.enqueue(part.value);
|
1325
|
+
}
|
1326
|
+
})
|
1327
|
+
),
|
1328
|
+
onUpdate({ message }) {
|
1329
|
+
const copiedMessage = {
|
1330
|
+
// deep copy the message to ensure that deep changes (msg attachments) are updated
|
1331
|
+
// with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
|
1332
|
+
...structuredClone(message),
|
1333
|
+
// add a revision id to ensure that the message is updated with SWR. SWR uses a
|
1334
|
+
// hashing approach by default to detect changes, but it only works for shallow
|
1335
|
+
// changes. This is why we need to add a revision id to ensure that the message
|
1336
|
+
// is updated with SWR (without it, the changes get stuck in SWR and are not
|
1337
|
+
// forwarded to rendering):
|
1338
|
+
revisionId: generateId3()
|
1339
|
+
};
|
1340
|
+
onUpdate({ message: copiedMessage });
|
1341
|
+
},
|
1342
|
+
lastMessage,
|
1343
|
+
onToolCall,
|
1344
|
+
onFinish,
|
1345
|
+
newMessageId: generateId3(),
|
1346
|
+
messageMetadataSchema
|
1347
|
+
}),
|
1348
|
+
onError: (error) => {
|
1349
|
+
throw error;
|
1350
|
+
}
|
1775
1351
|
});
|
1776
1352
|
return;
|
1777
1353
|
}
|
@@ -1783,6 +1359,7 @@ async function callChatApi({
|
|
1783
1359
|
}
|
1784
1360
|
|
1785
1361
|
// src/ui/call-completion-api.ts
|
1362
|
+
import { parseJsonEventStream as parseJsonEventStream2 } from "@ai-sdk/provider-utils";
|
1786
1363
|
var getOriginalFetch2 = () => fetch;
|
1787
1364
|
async function callCompletionApi({
|
1788
1365
|
api,
|
@@ -1795,10 +1372,8 @@ async function callCompletionApi({
|
|
1795
1372
|
setLoading,
|
1796
1373
|
setError,
|
1797
1374
|
setAbortController,
|
1798
|
-
onResponse,
|
1799
1375
|
onFinish,
|
1800
1376
|
onError,
|
1801
|
-
onData,
|
1802
1377
|
fetch: fetch2 = getOriginalFetch2()
|
1803
1378
|
}) {
|
1804
1379
|
var _a17;
|
@@ -1823,13 +1398,6 @@ async function callCompletionApi({
|
|
1823
1398
|
}).catch((err) => {
|
1824
1399
|
throw err;
|
1825
1400
|
});
|
1826
|
-
if (onResponse) {
|
1827
|
-
try {
|
1828
|
-
await onResponse(response);
|
1829
|
-
} catch (err) {
|
1830
|
-
throw err;
|
1831
|
-
}
|
1832
|
-
}
|
1833
1401
|
if (!response.ok) {
|
1834
1402
|
throw new Error(
|
1835
1403
|
(_a17 = await response.text()) != null ? _a17 : "Failed to fetch the chat response."
|
@@ -1851,17 +1419,28 @@ async function callCompletionApi({
|
|
1851
1419
|
break;
|
1852
1420
|
}
|
1853
1421
|
case "data": {
|
1854
|
-
await
|
1855
|
-
stream:
|
1856
|
-
|
1857
|
-
|
1858
|
-
|
1859
|
-
|
1860
|
-
|
1861
|
-
|
1862
|
-
|
1863
|
-
|
1864
|
-
|
1422
|
+
await consumeStream({
|
1423
|
+
stream: parseJsonEventStream2({
|
1424
|
+
stream: response.body,
|
1425
|
+
schema: uiMessageStreamPartSchema
|
1426
|
+
}).pipeThrough(
|
1427
|
+
new TransformStream({
|
1428
|
+
async transform(part) {
|
1429
|
+
if (!part.success) {
|
1430
|
+
throw part.error;
|
1431
|
+
}
|
1432
|
+
const { type, value } = part.value;
|
1433
|
+
if (type === "text") {
|
1434
|
+
result += value;
|
1435
|
+
setCompletion(result);
|
1436
|
+
} else if (type === "error") {
|
1437
|
+
throw new Error(value);
|
1438
|
+
}
|
1439
|
+
}
|
1440
|
+
})
|
1441
|
+
),
|
1442
|
+
onError: (error) => {
|
1443
|
+
throw error;
|
1865
1444
|
}
|
1866
1445
|
});
|
1867
1446
|
break;
|
@@ -2074,57 +1653,185 @@ function convertToModelMessages(messages, options) {
|
|
2074
1653
|
}
|
2075
1654
|
}
|
2076
1655
|
}
|
2077
|
-
return modelMessages;
|
1656
|
+
return modelMessages;
|
1657
|
+
}
|
1658
|
+
var convertToCoreMessages = convertToModelMessages;
|
1659
|
+
|
1660
|
+
// src/ui/should-resubmit-messages.ts
|
1661
|
+
function shouldResubmitMessages({
|
1662
|
+
originalMaxToolInvocationStep,
|
1663
|
+
originalMessageCount,
|
1664
|
+
maxSteps,
|
1665
|
+
messages
|
1666
|
+
}) {
|
1667
|
+
var _a17;
|
1668
|
+
const lastMessage = messages[messages.length - 1];
|
1669
|
+
return (
|
1670
|
+
// check if the feature is enabled:
|
1671
|
+
maxSteps > 1 && // ensure there is a last message:
|
1672
|
+
lastMessage != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
|
1673
|
+
(messages.length > originalMessageCount || extractMaxToolInvocationStep(getToolInvocations(lastMessage)) !== originalMaxToolInvocationStep) && // check that next step is possible:
|
1674
|
+
isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
|
1675
|
+
((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) < maxSteps
|
1676
|
+
);
|
1677
|
+
}
|
1678
|
+
function isAssistantMessageWithCompletedToolCalls(message) {
|
1679
|
+
if (message.role !== "assistant") {
|
1680
|
+
return false;
|
1681
|
+
}
|
1682
|
+
const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {
|
1683
|
+
return part.type === "step-start" ? index : lastIndex;
|
1684
|
+
}, -1);
|
1685
|
+
const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter((part) => part.type === "tool-invocation");
|
1686
|
+
return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => "result" in part.toolInvocation);
|
1687
|
+
}
|
1688
|
+
|
1689
|
+
// src/ui/update-tool-call-result.ts
|
1690
|
+
function updateToolCallResult({
|
1691
|
+
messages,
|
1692
|
+
toolCallId,
|
1693
|
+
toolResult: result
|
1694
|
+
}) {
|
1695
|
+
const lastMessage = messages[messages.length - 1];
|
1696
|
+
const invocationPart = lastMessage.parts.find(
|
1697
|
+
(part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === toolCallId
|
1698
|
+
);
|
1699
|
+
if (invocationPart == null) {
|
1700
|
+
return;
|
1701
|
+
}
|
1702
|
+
invocationPart.toolInvocation = {
|
1703
|
+
...invocationPart.toolInvocation,
|
1704
|
+
state: "result",
|
1705
|
+
result
|
1706
|
+
};
|
1707
|
+
}
|
1708
|
+
|
1709
|
+
// src/ui-message-stream/create-ui-message-stream.ts
|
1710
|
+
function createUIMessageStream({
|
1711
|
+
execute,
|
1712
|
+
onError = () => "An error occurred."
|
1713
|
+
// mask error messages for safety by default
|
1714
|
+
}) {
|
1715
|
+
let controller;
|
1716
|
+
const ongoingStreamPromises = [];
|
1717
|
+
const stream = new ReadableStream({
|
1718
|
+
start(controllerArg) {
|
1719
|
+
controller = controllerArg;
|
1720
|
+
}
|
1721
|
+
});
|
1722
|
+
function safeEnqueue(data) {
|
1723
|
+
try {
|
1724
|
+
controller.enqueue(data);
|
1725
|
+
} catch (error) {
|
1726
|
+
}
|
1727
|
+
}
|
1728
|
+
try {
|
1729
|
+
const result = execute({
|
1730
|
+
write(part) {
|
1731
|
+
safeEnqueue(part);
|
1732
|
+
},
|
1733
|
+
merge(streamArg) {
|
1734
|
+
ongoingStreamPromises.push(
|
1735
|
+
(async () => {
|
1736
|
+
const reader = streamArg.getReader();
|
1737
|
+
while (true) {
|
1738
|
+
const { done, value } = await reader.read();
|
1739
|
+
if (done)
|
1740
|
+
break;
|
1741
|
+
safeEnqueue(value);
|
1742
|
+
}
|
1743
|
+
})().catch((error) => {
|
1744
|
+
safeEnqueue({ type: "error", value: onError(error) });
|
1745
|
+
})
|
1746
|
+
);
|
1747
|
+
},
|
1748
|
+
onError
|
1749
|
+
});
|
1750
|
+
if (result) {
|
1751
|
+
ongoingStreamPromises.push(
|
1752
|
+
result.catch((error) => {
|
1753
|
+
safeEnqueue({ type: "error", value: onError(error) });
|
1754
|
+
})
|
1755
|
+
);
|
1756
|
+
}
|
1757
|
+
} catch (error) {
|
1758
|
+
safeEnqueue({ type: "error", value: onError(error) });
|
1759
|
+
}
|
1760
|
+
const waitForStreams = new Promise(async (resolve) => {
|
1761
|
+
while (ongoingStreamPromises.length > 0) {
|
1762
|
+
await ongoingStreamPromises.shift();
|
1763
|
+
}
|
1764
|
+
resolve();
|
1765
|
+
});
|
1766
|
+
waitForStreams.finally(() => {
|
1767
|
+
try {
|
1768
|
+
controller.close();
|
1769
|
+
} catch (error) {
|
1770
|
+
}
|
1771
|
+
});
|
1772
|
+
return stream;
|
2078
1773
|
}
|
2079
|
-
var convertToCoreMessages = convertToModelMessages;
|
2080
1774
|
|
2081
|
-
// src/ui/
|
2082
|
-
|
2083
|
-
|
2084
|
-
|
2085
|
-
|
2086
|
-
|
1775
|
+
// src/ui-message-stream/ui-message-stream-headers.ts
|
1776
|
+
var uiMessageStreamHeaders = {
|
1777
|
+
"content-type": "text/event-stream",
|
1778
|
+
"cache-control": "no-cache",
|
1779
|
+
connection: "keep-alive",
|
1780
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
1781
|
+
"x-accel-buffering": "no"
|
1782
|
+
// disable nginx buffering
|
1783
|
+
};
|
1784
|
+
|
1785
|
+
// src/ui-message-stream/json-to-sse-transform-stream.ts
|
1786
|
+
var JsonToSseTransformStream = class extends TransformStream {
|
1787
|
+
constructor() {
|
1788
|
+
super({
|
1789
|
+
transform(part, controller) {
|
1790
|
+
controller.enqueue(`data: ${JSON.stringify(part)}
|
1791
|
+
|
1792
|
+
`);
|
1793
|
+
},
|
1794
|
+
flush(controller) {
|
1795
|
+
controller.enqueue("data: [DONE]\n\n");
|
1796
|
+
}
|
1797
|
+
});
|
1798
|
+
}
|
1799
|
+
};
|
1800
|
+
|
1801
|
+
// src/ui-message-stream/create-ui-message-stream-response.ts
|
1802
|
+
function createUIMessageStreamResponse({
|
1803
|
+
status,
|
1804
|
+
statusText,
|
1805
|
+
headers,
|
1806
|
+
stream
|
2087
1807
|
}) {
|
2088
|
-
|
2089
|
-
|
2090
|
-
|
2091
|
-
|
2092
|
-
|
2093
|
-
|
2094
|
-
|
2095
|
-
isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
|
2096
|
-
((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) < maxSteps
|
1808
|
+
return new Response(
|
1809
|
+
stream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream()),
|
1810
|
+
{
|
1811
|
+
status,
|
1812
|
+
statusText,
|
1813
|
+
headers: prepareHeaders(headers, uiMessageStreamHeaders)
|
1814
|
+
}
|
2097
1815
|
);
|
2098
1816
|
}
|
2099
|
-
function isAssistantMessageWithCompletedToolCalls(message) {
|
2100
|
-
if (message.role !== "assistant") {
|
2101
|
-
return false;
|
2102
|
-
}
|
2103
|
-
const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {
|
2104
|
-
return part.type === "step-start" ? index : lastIndex;
|
2105
|
-
}, -1);
|
2106
|
-
const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter((part) => part.type === "tool-invocation");
|
2107
|
-
return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => "result" in part.toolInvocation);
|
2108
|
-
}
|
2109
1817
|
|
2110
|
-
// src/ui/
|
2111
|
-
function
|
2112
|
-
|
2113
|
-
|
2114
|
-
|
1818
|
+
// src/ui-message-stream/pipe-ui-message-stream-to-response.ts
|
1819
|
+
function pipeUIMessageStreamToResponse({
|
1820
|
+
response,
|
1821
|
+
status,
|
1822
|
+
statusText,
|
1823
|
+
headers,
|
1824
|
+
stream
|
2115
1825
|
}) {
|
2116
|
-
|
2117
|
-
|
2118
|
-
|
2119
|
-
|
2120
|
-
|
2121
|
-
|
2122
|
-
|
2123
|
-
|
2124
|
-
|
2125
|
-
state: "result",
|
2126
|
-
result
|
2127
|
-
};
|
1826
|
+
writeToServerResponse({
|
1827
|
+
response,
|
1828
|
+
status,
|
1829
|
+
statusText,
|
1830
|
+
headers: Object.fromEntries(
|
1831
|
+
prepareHeaders(headers, uiMessageStreamHeaders).entries()
|
1832
|
+
),
|
1833
|
+
stream: stream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
|
1834
|
+
});
|
2128
1835
|
}
|
2129
1836
|
|
2130
1837
|
// src/util/data-url.ts
|
@@ -2821,7 +2528,7 @@ var DefaultEmbedManyResult = class {
|
|
2821
2528
|
};
|
2822
2529
|
|
2823
2530
|
// src/util/detect-media-type.ts
|
2824
|
-
import { convertBase64ToUint8Array
|
2531
|
+
import { convertBase64ToUint8Array } from "@ai-sdk/provider-utils";
|
2825
2532
|
var imageMediaTypeSignatures = [
|
2826
2533
|
{
|
2827
2534
|
mediaType: "image/gif",
|
@@ -2928,7 +2635,7 @@ var audioMediaTypeSignatures = [
|
|
2928
2635
|
}
|
2929
2636
|
];
|
2930
2637
|
var stripID3 = (data) => {
|
2931
|
-
const bytes = typeof data === "string" ?
|
2638
|
+
const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
|
2932
2639
|
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
|
2933
2640
|
return bytes.slice(id3Size + 10);
|
2934
2641
|
};
|
@@ -2955,8 +2662,8 @@ function detectMediaType({
|
|
2955
2662
|
|
2956
2663
|
// core/generate-text/generated-file.ts
|
2957
2664
|
import {
|
2958
|
-
convertBase64ToUint8Array as
|
2959
|
-
convertUint8ArrayToBase64
|
2665
|
+
convertBase64ToUint8Array as convertBase64ToUint8Array2,
|
2666
|
+
convertUint8ArrayToBase64
|
2960
2667
|
} from "@ai-sdk/provider-utils";
|
2961
2668
|
var DefaultGeneratedFile = class {
|
2962
2669
|
constructor({
|
@@ -2971,14 +2678,14 @@ var DefaultGeneratedFile = class {
|
|
2971
2678
|
// lazy conversion with caching to avoid unnecessary conversion overhead:
|
2972
2679
|
get base64() {
|
2973
2680
|
if (this.base64Data == null) {
|
2974
|
-
this.base64Data =
|
2681
|
+
this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
|
2975
2682
|
}
|
2976
2683
|
return this.base64Data;
|
2977
2684
|
}
|
2978
2685
|
// lazy conversion with caching to avoid unnecessary conversion overhead:
|
2979
2686
|
get uint8Array() {
|
2980
2687
|
if (this.uint8ArrayData == null) {
|
2981
|
-
this.uint8ArrayData =
|
2688
|
+
this.uint8ArrayData = convertBase64ToUint8Array2(this.base64Data);
|
2982
2689
|
}
|
2983
2690
|
return this.uint8ArrayData;
|
2984
2691
|
}
|
@@ -2995,6 +2702,7 @@ async function generateImage({
|
|
2995
2702
|
model,
|
2996
2703
|
prompt,
|
2997
2704
|
n = 1,
|
2705
|
+
maxImagesPerCall,
|
2998
2706
|
size,
|
2999
2707
|
aspectRatio,
|
3000
2708
|
seed,
|
@@ -3005,14 +2713,14 @@ async function generateImage({
|
|
3005
2713
|
}) {
|
3006
2714
|
var _a17, _b;
|
3007
2715
|
const { retry } = prepareRetries({ maxRetries: maxRetriesArg });
|
3008
|
-
const
|
3009
|
-
const callCount = Math.ceil(n /
|
2716
|
+
const maxImagesPerCallWithDefault = (_a17 = maxImagesPerCall != null ? maxImagesPerCall : model.maxImagesPerCall) != null ? _a17 : 1;
|
2717
|
+
const callCount = Math.ceil(n / maxImagesPerCallWithDefault);
|
3010
2718
|
const callImageCounts = Array.from({ length: callCount }, (_, i) => {
|
3011
2719
|
if (i < callCount - 1) {
|
3012
|
-
return
|
2720
|
+
return maxImagesPerCallWithDefault;
|
3013
2721
|
}
|
3014
|
-
const remainder = n %
|
3015
|
-
return remainder === 0 ?
|
2722
|
+
const remainder = n % maxImagesPerCallWithDefault;
|
2723
|
+
return remainder === 0 ? maxImagesPerCallWithDefault : remainder;
|
3016
2724
|
});
|
3017
2725
|
const results = await Promise.all(
|
3018
2726
|
callImageCounts.map(
|
@@ -3089,7 +2797,7 @@ import {
|
|
3089
2797
|
} from "@ai-sdk/provider";
|
3090
2798
|
import {
|
3091
2799
|
createIdGenerator,
|
3092
|
-
safeParseJSON as
|
2800
|
+
safeParseJSON as safeParseJSON2
|
3093
2801
|
} from "@ai-sdk/provider-utils";
|
3094
2802
|
|
3095
2803
|
// core/generate-text/extract-content-text.ts
|
@@ -3131,6 +2839,92 @@ async function download({ url }) {
|
|
3131
2839
|
}
|
3132
2840
|
}
|
3133
2841
|
|
2842
|
+
// core/prompt/data-content.ts
|
2843
|
+
import { AISDKError as AISDKError17 } from "@ai-sdk/provider";
|
2844
|
+
import {
|
2845
|
+
convertBase64ToUint8Array as convertBase64ToUint8Array3,
|
2846
|
+
convertUint8ArrayToBase64 as convertUint8ArrayToBase642
|
2847
|
+
} from "@ai-sdk/provider-utils";
|
2848
|
+
import { z as z2 } from "zod";
|
2849
|
+
|
2850
|
+
// core/prompt/split-data-url.ts
|
2851
|
+
function splitDataUrl(dataUrl) {
|
2852
|
+
try {
|
2853
|
+
const [header, base64Content] = dataUrl.split(",");
|
2854
|
+
return {
|
2855
|
+
mediaType: header.split(";")[0].split(":")[1],
|
2856
|
+
base64Content
|
2857
|
+
};
|
2858
|
+
} catch (error) {
|
2859
|
+
return {
|
2860
|
+
mediaType: void 0,
|
2861
|
+
base64Content: void 0
|
2862
|
+
};
|
2863
|
+
}
|
2864
|
+
}
|
2865
|
+
|
2866
|
+
// core/prompt/data-content.ts
|
2867
|
+
var dataContentSchema = z2.union([
|
2868
|
+
z2.string(),
|
2869
|
+
z2.instanceof(Uint8Array),
|
2870
|
+
z2.instanceof(ArrayBuffer),
|
2871
|
+
z2.custom(
|
2872
|
+
// Buffer might not be available in some environments such as CloudFlare:
|
2873
|
+
(value) => {
|
2874
|
+
var _a17, _b;
|
2875
|
+
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
2876
|
+
},
|
2877
|
+
{ message: "Must be a Buffer" }
|
2878
|
+
)
|
2879
|
+
]);
|
2880
|
+
function convertToLanguageModelV2DataContent(content) {
|
2881
|
+
if (content instanceof Uint8Array) {
|
2882
|
+
return { data: content, mediaType: void 0 };
|
2883
|
+
}
|
2884
|
+
if (content instanceof ArrayBuffer) {
|
2885
|
+
return { data: new Uint8Array(content), mediaType: void 0 };
|
2886
|
+
}
|
2887
|
+
if (typeof content === "string") {
|
2888
|
+
try {
|
2889
|
+
content = new URL(content);
|
2890
|
+
} catch (error) {
|
2891
|
+
}
|
2892
|
+
}
|
2893
|
+
if (content instanceof URL && content.protocol === "data:") {
|
2894
|
+
const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
|
2895
|
+
content.toString()
|
2896
|
+
);
|
2897
|
+
if (dataUrlMediaType == null || base64Content == null) {
|
2898
|
+
throw new AISDKError17({
|
2899
|
+
name: "InvalidDataContentError",
|
2900
|
+
message: `Invalid data URL format in content ${content.toString()}`
|
2901
|
+
});
|
2902
|
+
}
|
2903
|
+
return { data: base64Content, mediaType: dataUrlMediaType };
|
2904
|
+
}
|
2905
|
+
return { data: content, mediaType: void 0 };
|
2906
|
+
}
|
2907
|
+
function convertDataContentToUint8Array(content) {
|
2908
|
+
if (content instanceof Uint8Array) {
|
2909
|
+
return content;
|
2910
|
+
}
|
2911
|
+
if (typeof content === "string") {
|
2912
|
+
try {
|
2913
|
+
return convertBase64ToUint8Array3(content);
|
2914
|
+
} catch (error) {
|
2915
|
+
throw new InvalidDataContentError({
|
2916
|
+
message: "Invalid data content. Content string is not a base64-encoded media.",
|
2917
|
+
content,
|
2918
|
+
cause: error
|
2919
|
+
});
|
2920
|
+
}
|
2921
|
+
}
|
2922
|
+
if (content instanceof ArrayBuffer) {
|
2923
|
+
return new Uint8Array(content);
|
2924
|
+
}
|
2925
|
+
throw new InvalidDataContentError({ content });
|
2926
|
+
}
|
2927
|
+
|
3134
2928
|
// core/prompt/convert-to-language-model-prompt.ts
|
3135
2929
|
async function convertToLanguageModelPrompt({
|
3136
2930
|
prompt,
|
@@ -3351,8 +3145,8 @@ function prepareCallSettings({
|
|
3351
3145
|
topK,
|
3352
3146
|
presencePenalty,
|
3353
3147
|
frequencyPenalty,
|
3354
|
-
|
3355
|
-
|
3148
|
+
seed,
|
3149
|
+
stopSequences
|
3356
3150
|
}) {
|
3357
3151
|
if (maxOutputTokens != null) {
|
3358
3152
|
if (!Number.isInteger(maxOutputTokens)) {
|
@@ -3426,12 +3220,12 @@ function prepareCallSettings({
|
|
3426
3220
|
}
|
3427
3221
|
return {
|
3428
3222
|
maxOutputTokens,
|
3429
|
-
temperature
|
3223
|
+
temperature,
|
3430
3224
|
topP,
|
3431
3225
|
topK,
|
3432
3226
|
presencePenalty,
|
3433
3227
|
frequencyPenalty,
|
3434
|
-
stopSequences
|
3228
|
+
stopSequences,
|
3435
3229
|
seed
|
3436
3230
|
};
|
3437
3231
|
}
|
@@ -3638,6 +3432,23 @@ import {
|
|
3638
3432
|
asSchema,
|
3639
3433
|
safeValidateTypes as safeValidateTypes2
|
3640
3434
|
} from "@ai-sdk/provider-utils";
|
3435
|
+
|
3436
|
+
// src/util/async-iterable-stream.ts
|
3437
|
+
function createAsyncIterableStream(source) {
|
3438
|
+
const stream = source.pipeThrough(new TransformStream());
|
3439
|
+
stream[Symbol.asyncIterator] = () => {
|
3440
|
+
const reader = stream.getReader();
|
3441
|
+
return {
|
3442
|
+
async next() {
|
3443
|
+
const { done, value } = await reader.read();
|
3444
|
+
return done ? { done: true, value: void 0 } : { done: false, value };
|
3445
|
+
}
|
3446
|
+
};
|
3447
|
+
};
|
3448
|
+
return stream;
|
3449
|
+
}
|
3450
|
+
|
3451
|
+
// core/generate-object/output-strategy.ts
|
3641
3452
|
var noSchemaOutputStrategy = {
|
3642
3453
|
type: "no-schema",
|
3643
3454
|
jsonSchema: void 0,
|
@@ -4188,7 +3999,7 @@ async function generateObject(options) {
|
|
4188
3999
|
request = (_a17 = generateResult.request) != null ? _a17 : {};
|
4189
4000
|
response = generateResult.responseData;
|
4190
4001
|
async function processResult(result2) {
|
4191
|
-
const parseResult = await
|
4002
|
+
const parseResult = await safeParseJSON2({ text: result2 });
|
4192
4003
|
if (!parseResult.success) {
|
4193
4004
|
throw new NoObjectGeneratedError({
|
4194
4005
|
message: "No object generated: could not parse the response.",
|
@@ -4933,8 +4744,8 @@ var DefaultStreamObjectResult = class {
|
|
4933
4744
|
};
|
4934
4745
|
|
4935
4746
|
// src/error/no-speech-generated-error.ts
|
4936
|
-
import { AISDKError as
|
4937
|
-
var NoSpeechGeneratedError = class extends
|
4747
|
+
import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
|
4748
|
+
var NoSpeechGeneratedError = class extends AISDKError18 {
|
4938
4749
|
constructor(options) {
|
4939
4750
|
super({
|
4940
4751
|
name: "AI_NoSpeechGeneratedError",
|
@@ -5025,19 +4836,6 @@ var DefaultSpeechResult = class {
|
|
5025
4836
|
// core/generate-text/generate-text.ts
|
5026
4837
|
import { createIdGenerator as createIdGenerator3 } from "@ai-sdk/provider-utils";
|
5027
4838
|
|
5028
|
-
// src/util/split-on-last-whitespace.ts
|
5029
|
-
var lastWhitespaceRegexp = /^([\s\S]*?)(\s+)(\S*)$/;
|
5030
|
-
function splitOnLastWhitespace(text2) {
|
5031
|
-
const match = text2.match(lastWhitespaceRegexp);
|
5032
|
-
return match ? { prefix: match[1], whitespace: match[2], suffix: match[3] } : void 0;
|
5033
|
-
}
|
5034
|
-
|
5035
|
-
// src/util/remove-text-after-last-whitespace.ts
|
5036
|
-
function removeTextAfterLastWhitespace(text2) {
|
5037
|
-
const match = splitOnLastWhitespace(text2);
|
5038
|
-
return match ? match.prefix + match.whitespace : text2;
|
5039
|
-
}
|
5040
|
-
|
5041
4839
|
// core/prompt/prepare-tools-and-tool-choice.ts
|
5042
4840
|
import { asSchema as asSchema2 } from "@ai-sdk/provider-utils";
|
5043
4841
|
|
@@ -5139,20 +4937,11 @@ function asContent({
|
|
5139
4937
|
...toolResults
|
5140
4938
|
];
|
5141
4939
|
}
|
5142
|
-
function extractFiles(content) {
|
5143
|
-
return content.filter((part) => part.type === "file").map((part) => part.file);
|
5144
|
-
}
|
5145
|
-
function extractReasoning(content) {
|
5146
|
-
return content.filter((part) => part.type === "reasoning");
|
5147
|
-
}
|
5148
|
-
function extractSources(content) {
|
5149
|
-
return content.filter((part) => part.type === "source");
|
5150
|
-
}
|
5151
4940
|
|
5152
4941
|
// core/generate-text/parse-tool-call.ts
|
5153
4942
|
import {
|
5154
4943
|
asSchema as asSchema3,
|
5155
|
-
safeParseJSON as
|
4944
|
+
safeParseJSON as safeParseJSON3,
|
5156
4945
|
safeValidateTypes as safeValidateTypes3
|
5157
4946
|
} from "@ai-sdk/provider-utils";
|
5158
4947
|
async function parseToolCall({
|
@@ -5208,88 +4997,118 @@ async function doParseToolCall({
|
|
5208
4997
|
availableTools: Object.keys(tools)
|
5209
4998
|
});
|
5210
4999
|
}
|
5211
|
-
const schema = asSchema3(tool2.parameters);
|
5212
|
-
const parseResult = toolCall.args.trim() === "" ? await safeValidateTypes3({ value: {}, schema }) : await
|
5213
|
-
if (parseResult.success === false) {
|
5214
|
-
throw new InvalidToolArgumentsError({
|
5215
|
-
toolName,
|
5216
|
-
toolArgs: toolCall.args,
|
5217
|
-
cause: parseResult.error
|
5218
|
-
});
|
5000
|
+
const schema = asSchema3(tool2.parameters);
|
5001
|
+
const parseResult = toolCall.args.trim() === "" ? await safeValidateTypes3({ value: {}, schema }) : await safeParseJSON3({ text: toolCall.args, schema });
|
5002
|
+
if (parseResult.success === false) {
|
5003
|
+
throw new InvalidToolArgumentsError({
|
5004
|
+
toolName,
|
5005
|
+
toolArgs: toolCall.args,
|
5006
|
+
cause: parseResult.error
|
5007
|
+
});
|
5008
|
+
}
|
5009
|
+
return {
|
5010
|
+
type: "tool-call",
|
5011
|
+
toolCallId: toolCall.toolCallId,
|
5012
|
+
toolName,
|
5013
|
+
args: parseResult == null ? void 0 : parseResult.value
|
5014
|
+
};
|
5015
|
+
}
|
5016
|
+
|
5017
|
+
// core/generate-text/step-result.ts
|
5018
|
+
var DefaultStepResult = class {
|
5019
|
+
constructor({
|
5020
|
+
content,
|
5021
|
+
finishReason,
|
5022
|
+
usage,
|
5023
|
+
warnings,
|
5024
|
+
request,
|
5025
|
+
response,
|
5026
|
+
providerMetadata
|
5027
|
+
}) {
|
5028
|
+
this.content = content;
|
5029
|
+
this.finishReason = finishReason;
|
5030
|
+
this.usage = usage;
|
5031
|
+
this.warnings = warnings;
|
5032
|
+
this.request = request;
|
5033
|
+
this.response = response;
|
5034
|
+
this.providerMetadata = providerMetadata;
|
5035
|
+
}
|
5036
|
+
get text() {
|
5037
|
+
return this.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
5038
|
+
}
|
5039
|
+
get reasoning() {
|
5040
|
+
return this.content.filter((part) => part.type === "reasoning");
|
5041
|
+
}
|
5042
|
+
get reasoningText() {
|
5043
|
+
return this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join("");
|
5044
|
+
}
|
5045
|
+
get files() {
|
5046
|
+
return this.content.filter((part) => part.type === "file").map((part) => part.file);
|
5047
|
+
}
|
5048
|
+
get sources() {
|
5049
|
+
return this.content.filter((part) => part.type === "source");
|
5050
|
+
}
|
5051
|
+
get toolCalls() {
|
5052
|
+
return this.content.filter((part) => part.type === "tool-call");
|
5219
5053
|
}
|
5220
|
-
|
5221
|
-
type
|
5222
|
-
|
5223
|
-
|
5224
|
-
args: parseResult == null ? void 0 : parseResult.value
|
5225
|
-
};
|
5226
|
-
}
|
5227
|
-
|
5228
|
-
// core/generate-text/reasoning.ts
|
5229
|
-
function asReasoningText(reasoningParts) {
|
5230
|
-
const reasoningText = reasoningParts.map((part) => part.text).join("");
|
5231
|
-
return reasoningText.length > 0 ? reasoningText : void 0;
|
5232
|
-
}
|
5054
|
+
get toolResults() {
|
5055
|
+
return this.content.filter((part) => part.type === "tool-result");
|
5056
|
+
}
|
5057
|
+
};
|
5233
5058
|
|
5234
5059
|
// core/generate-text/to-response-messages.ts
|
5235
5060
|
function toResponseMessages({
|
5236
|
-
|
5237
|
-
|
5238
|
-
reasoning,
|
5239
|
-
tools,
|
5240
|
-
toolCalls,
|
5241
|
-
toolResults,
|
5242
|
-
messageId,
|
5243
|
-
generateMessageId
|
5061
|
+
content: inputContent,
|
5062
|
+
tools
|
5244
5063
|
}) {
|
5245
5064
|
const responseMessages = [];
|
5246
|
-
const content =
|
5247
|
-
|
5248
|
-
|
5249
|
-
|
5250
|
-
|
5251
|
-
|
5252
|
-
|
5253
|
-
|
5254
|
-
|
5255
|
-
|
5256
|
-
|
5257
|
-
|
5258
|
-
|
5259
|
-
|
5260
|
-
|
5261
|
-
|
5262
|
-
|
5263
|
-
|
5264
|
-
|
5065
|
+
const content = inputContent.filter((part) => part.type !== "tool-result" && part.type !== "source").filter((part) => part.type !== "text" || part.text.length > 0).map((part) => {
|
5066
|
+
switch (part.type) {
|
5067
|
+
case "text":
|
5068
|
+
return part;
|
5069
|
+
case "reasoning":
|
5070
|
+
return {
|
5071
|
+
type: "reasoning",
|
5072
|
+
text: part.text,
|
5073
|
+
providerOptions: part.providerMetadata
|
5074
|
+
};
|
5075
|
+
case "file":
|
5076
|
+
return {
|
5077
|
+
type: "file",
|
5078
|
+
data: part.file.base64,
|
5079
|
+
mediaType: part.file.mediaType
|
5080
|
+
};
|
5081
|
+
case "tool-call":
|
5082
|
+
return part;
|
5083
|
+
}
|
5084
|
+
});
|
5265
5085
|
if (content.length > 0) {
|
5266
5086
|
responseMessages.push({
|
5267
5087
|
role: "assistant",
|
5268
|
-
content
|
5269
|
-
id: messageId
|
5088
|
+
content
|
5270
5089
|
});
|
5271
5090
|
}
|
5272
|
-
|
5091
|
+
const toolResultContent = inputContent.filter((part) => part.type === "tool-result").map((toolResult) => {
|
5092
|
+
const tool2 = tools[toolResult.toolName];
|
5093
|
+
return (tool2 == null ? void 0 : tool2.experimental_toToolResultContent) != null ? {
|
5094
|
+
type: "tool-result",
|
5095
|
+
toolCallId: toolResult.toolCallId,
|
5096
|
+
toolName: toolResult.toolName,
|
5097
|
+
result: tool2.experimental_toToolResultContent(toolResult.result),
|
5098
|
+
experimental_content: tool2.experimental_toToolResultContent(
|
5099
|
+
toolResult.result
|
5100
|
+
)
|
5101
|
+
} : {
|
5102
|
+
type: "tool-result",
|
5103
|
+
toolCallId: toolResult.toolCallId,
|
5104
|
+
toolName: toolResult.toolName,
|
5105
|
+
result: toolResult.result
|
5106
|
+
};
|
5107
|
+
});
|
5108
|
+
if (toolResultContent.length > 0) {
|
5273
5109
|
responseMessages.push({
|
5274
5110
|
role: "tool",
|
5275
|
-
|
5276
|
-
content: toolResults.map((toolResult) => {
|
5277
|
-
const tool2 = tools[toolResult.toolName];
|
5278
|
-
return (tool2 == null ? void 0 : tool2.experimental_toToolResultContent) != null ? {
|
5279
|
-
type: "tool-result",
|
5280
|
-
toolCallId: toolResult.toolCallId,
|
5281
|
-
toolName: toolResult.toolName,
|
5282
|
-
result: tool2.experimental_toToolResultContent(toolResult.result),
|
5283
|
-
experimental_content: tool2.experimental_toToolResultContent(
|
5284
|
-
toolResult.result
|
5285
|
-
)
|
5286
|
-
} : {
|
5287
|
-
type: "tool-result",
|
5288
|
-
toolCallId: toolResult.toolCallId,
|
5289
|
-
toolName: toolResult.toolName,
|
5290
|
-
result: toolResult.result
|
5291
|
-
};
|
5292
|
-
})
|
5111
|
+
content: toolResultContent
|
5293
5112
|
});
|
5294
5113
|
}
|
5295
5114
|
return responseMessages;
|
@@ -5300,10 +5119,6 @@ var originalGenerateId3 = createIdGenerator3({
|
|
5300
5119
|
prefix: "aitxt",
|
5301
5120
|
size: 24
|
5302
5121
|
});
|
5303
|
-
var originalGenerateMessageId = createIdGenerator3({
|
5304
|
-
prefix: "msg",
|
5305
|
-
size: 24
|
5306
|
-
});
|
5307
5122
|
async function generateText({
|
5308
5123
|
model,
|
5309
5124
|
tools,
|
@@ -5315,9 +5130,7 @@ async function generateText({
|
|
5315
5130
|
abortSignal,
|
5316
5131
|
headers,
|
5317
5132
|
maxSteps = 1,
|
5318
|
-
experimental_generateMessageId: generateMessageId = originalGenerateMessageId,
|
5319
5133
|
experimental_output: output,
|
5320
|
-
experimental_continueSteps: continueSteps = false,
|
5321
5134
|
experimental_telemetry: telemetry,
|
5322
5135
|
providerOptions,
|
5323
5136
|
experimental_activeTools: activeTools,
|
@@ -5373,22 +5186,14 @@ async function generateText({
|
|
5373
5186
|
}),
|
5374
5187
|
tracer,
|
5375
5188
|
fn: async (span) => {
|
5376
|
-
var _a17, _b, _c, _d
|
5189
|
+
var _a17, _b, _c, _d;
|
5377
5190
|
const callSettings2 = prepareCallSettings(settings);
|
5378
5191
|
let currentModelResponse;
|
5379
5192
|
let currentToolCalls = [];
|
5380
5193
|
let currentToolResults = [];
|
5381
5194
|
let stepCount = 0;
|
5382
5195
|
const responseMessages = [];
|
5383
|
-
let text2 = "";
|
5384
|
-
const sources = [];
|
5385
5196
|
const steps = [];
|
5386
|
-
let usage = {
|
5387
|
-
inputTokens: void 0,
|
5388
|
-
outputTokens: void 0,
|
5389
|
-
totalTokens: void 0
|
5390
|
-
};
|
5391
|
-
let stepType = "initial";
|
5392
5197
|
do {
|
5393
5198
|
const stepInputMessages = [
|
5394
5199
|
...initialPrompt.messages,
|
@@ -5454,7 +5259,7 @@ async function generateText({
|
|
5454
5259
|
}),
|
5455
5260
|
tracer,
|
5456
5261
|
fn: async (span2) => {
|
5457
|
-
var _a19, _b2, _c2, _d2,
|
5262
|
+
var _a19, _b2, _c2, _d2, _e, _f, _g, _h;
|
5458
5263
|
const result = await stepModel.doGenerate({
|
5459
5264
|
...callSettings2,
|
5460
5265
|
tools: stepTools,
|
@@ -5468,7 +5273,7 @@ async function generateText({
|
|
5468
5273
|
const responseData = {
|
5469
5274
|
id: (_b2 = (_a19 = result.response) == null ? void 0 : _a19.id) != null ? _b2 : generateId3(),
|
5470
5275
|
timestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : currentDate(),
|
5471
|
-
modelId: (
|
5276
|
+
modelId: (_f = (_e = result.response) == null ? void 0 : _e.modelId) != null ? _f : stepModel.modelId,
|
5472
5277
|
headers: (_g = result.response) == null ? void 0 : _g.headers,
|
5473
5278
|
body: (_h = result.response) == null ? void 0 : _h.body
|
5474
5279
|
};
|
@@ -5527,89 +5332,35 @@ async function generateText({
|
|
5527
5332
|
messages: stepInputMessages,
|
5528
5333
|
abortSignal
|
5529
5334
|
});
|
5530
|
-
usage = addLanguageModelUsage(usage, currentModelResponse.usage);
|
5531
|
-
let nextStepType = "done";
|
5532
|
-
if (++stepCount < maxSteps) {
|
5533
|
-
if (continueSteps && currentModelResponse.finishReason === "length" && // only use continue when there are no tool calls:
|
5534
|
-
currentToolCalls.length === 0) {
|
5535
|
-
nextStepType = "continue";
|
5536
|
-
} else if (
|
5537
|
-
// there are tool calls:
|
5538
|
-
currentToolCalls.length > 0 && // all current tool calls have results:
|
5539
|
-
currentToolResults.length === currentToolCalls.length
|
5540
|
-
) {
|
5541
|
-
nextStepType = "tool-result";
|
5542
|
-
}
|
5543
|
-
}
|
5544
5335
|
const stepContent = asContent({
|
5545
5336
|
content: currentModelResponse.content,
|
5546
5337
|
toolCalls: currentToolCalls,
|
5547
5338
|
toolResults: currentToolResults
|
5548
5339
|
});
|
5549
|
-
|
5550
|
-
|
5551
|
-
|
5552
|
-
|
5553
|
-
|
5554
|
-
sources.push(
|
5555
|
-
...currentModelResponse.content.filter(
|
5556
|
-
(part) => part.type === "source"
|
5557
|
-
)
|
5340
|
+
responseMessages.push(
|
5341
|
+
...toResponseMessages({
|
5342
|
+
content: stepContent,
|
5343
|
+
tools: tools != null ? tools : {}
|
5344
|
+
})
|
5558
5345
|
);
|
5559
|
-
|
5560
|
-
const lastMessage = responseMessages[responseMessages.length - 1];
|
5561
|
-
if (typeof lastMessage.content === "string") {
|
5562
|
-
lastMessage.content += stepText;
|
5563
|
-
} else {
|
5564
|
-
lastMessage.content.push({
|
5565
|
-
text: stepText,
|
5566
|
-
type: "text"
|
5567
|
-
});
|
5568
|
-
}
|
5569
|
-
} else {
|
5570
|
-
responseMessages.push(
|
5571
|
-
...toResponseMessages({
|
5572
|
-
text: text2,
|
5573
|
-
files: extractFiles(stepContent),
|
5574
|
-
reasoning: extractReasoning(stepContent).map((part) => ({
|
5575
|
-
type: "reasoning",
|
5576
|
-
text: part.text,
|
5577
|
-
providerOptions: part.providerMetadata
|
5578
|
-
})),
|
5579
|
-
tools: tools != null ? tools : {},
|
5580
|
-
toolCalls: currentToolCalls,
|
5581
|
-
toolResults: currentToolResults,
|
5582
|
-
messageId: generateMessageId(),
|
5583
|
-
generateMessageId
|
5584
|
-
})
|
5585
|
-
);
|
5586
|
-
}
|
5587
|
-
const currentStepResult = {
|
5588
|
-
stepType,
|
5346
|
+
const currentStepResult = new DefaultStepResult({
|
5589
5347
|
content: stepContent,
|
5590
|
-
text: stepText,
|
5591
|
-
reasoningText: asReasoningText(extractReasoning(stepContent)),
|
5592
|
-
reasoning: extractReasoning(stepContent),
|
5593
|
-
files: extractFiles(stepContent),
|
5594
|
-
sources: extractSources(stepContent),
|
5595
|
-
toolCalls: currentToolCalls,
|
5596
|
-
toolResults: currentToolResults,
|
5597
5348
|
finishReason: currentModelResponse.finishReason,
|
5598
5349
|
usage: currentModelResponse.usage,
|
5599
5350
|
warnings: currentModelResponse.warnings,
|
5600
|
-
|
5351
|
+
providerMetadata: currentModelResponse.providerMetadata,
|
5352
|
+
request: (_d = currentModelResponse.request) != null ? _d : {},
|
5601
5353
|
response: {
|
5602
5354
|
...currentModelResponse.response,
|
5603
5355
|
// deep clone msgs to avoid mutating past messages in multi-step:
|
5604
5356
|
messages: structuredClone(responseMessages)
|
5605
|
-
}
|
5606
|
-
|
5607
|
-
isContinued: nextStepType === "continue"
|
5608
|
-
};
|
5357
|
+
}
|
5358
|
+
});
|
5609
5359
|
steps.push(currentStepResult);
|
5610
5360
|
await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
|
5611
|
-
|
5612
|
-
|
5361
|
+
} while (++stepCount < maxSteps && // there are tool calls:
|
5362
|
+
currentToolCalls.length > 0 && // all current tool calls have results:
|
5363
|
+
currentToolResults.length === currentToolCalls.length);
|
5613
5364
|
span.setAttributes(
|
5614
5365
|
selectTelemetryAttributes({
|
5615
5366
|
telemetry,
|
@@ -5630,32 +5381,17 @@ async function generateText({
|
|
5630
5381
|
}
|
5631
5382
|
})
|
5632
5383
|
);
|
5633
|
-
const
|
5634
|
-
{ text: text2 },
|
5635
|
-
{
|
5636
|
-
response: currentModelResponse.response,
|
5637
|
-
usage,
|
5638
|
-
finishReason: currentModelResponse.finishReason
|
5639
|
-
}
|
5640
|
-
));
|
5384
|
+
const lastStep = steps[steps.length - 1];
|
5641
5385
|
return new DefaultGenerateTextResult({
|
5642
|
-
text: text2,
|
5643
|
-
content: asContent({
|
5644
|
-
content: currentModelResponse.content,
|
5645
|
-
toolCalls: currentToolCalls,
|
5646
|
-
toolResults: currentToolResults
|
5647
|
-
}),
|
5648
|
-
resolvedOutput,
|
5649
|
-
finishReason: currentModelResponse.finishReason,
|
5650
|
-
usage,
|
5651
|
-
warnings: currentModelResponse.warnings,
|
5652
|
-
request: (_f = currentModelResponse.request) != null ? _f : {},
|
5653
|
-
response: {
|
5654
|
-
...currentModelResponse.response,
|
5655
|
-
messages: responseMessages
|
5656
|
-
},
|
5657
5386
|
steps,
|
5658
|
-
|
5387
|
+
resolvedOutput: await (output == null ? void 0 : output.parseOutput(
|
5388
|
+
{ text: lastStep.text },
|
5389
|
+
{
|
5390
|
+
response: lastStep.response,
|
5391
|
+
usage: lastStep.usage,
|
5392
|
+
finishReason: lastStep.finishReason
|
5393
|
+
}
|
5394
|
+
))
|
5659
5395
|
});
|
5660
5396
|
}
|
5661
5397
|
});
|
@@ -5737,35 +5473,67 @@ async function executeTools({
|
|
5737
5473
|
}
|
5738
5474
|
var DefaultGenerateTextResult = class {
|
5739
5475
|
constructor(options) {
|
5740
|
-
this.text = options.text;
|
5741
|
-
this.content = options.content;
|
5742
|
-
this.finishReason = options.finishReason;
|
5743
|
-
this.usage = options.usage;
|
5744
|
-
this.warnings = options.warnings;
|
5745
|
-
this.request = options.request;
|
5746
|
-
this.response = options.response;
|
5747
5476
|
this.steps = options.steps;
|
5748
|
-
this.providerMetadata = options.providerMetadata;
|
5749
5477
|
this.resolvedOutput = options.resolvedOutput;
|
5750
5478
|
}
|
5479
|
+
get finalStep() {
|
5480
|
+
return this.steps[this.steps.length - 1];
|
5481
|
+
}
|
5482
|
+
get content() {
|
5483
|
+
return this.finalStep.content;
|
5484
|
+
}
|
5485
|
+
get text() {
|
5486
|
+
return this.finalStep.text;
|
5487
|
+
}
|
5751
5488
|
get files() {
|
5752
|
-
return
|
5489
|
+
return this.finalStep.files;
|
5753
5490
|
}
|
5754
5491
|
get reasoningText() {
|
5755
|
-
|
5756
|
-
return texts.length > 0 ? texts.join("") : void 0;
|
5492
|
+
return this.finalStep.reasoningText;
|
5757
5493
|
}
|
5758
5494
|
get reasoning() {
|
5759
|
-
return this.
|
5495
|
+
return this.finalStep.reasoning;
|
5760
5496
|
}
|
5761
5497
|
get toolCalls() {
|
5762
|
-
return this.
|
5498
|
+
return this.finalStep.toolCalls;
|
5763
5499
|
}
|
5764
5500
|
get toolResults() {
|
5765
|
-
return this.
|
5501
|
+
return this.finalStep.toolResults;
|
5766
5502
|
}
|
5767
5503
|
get sources() {
|
5768
|
-
return this.
|
5504
|
+
return this.finalStep.sources;
|
5505
|
+
}
|
5506
|
+
get finishReason() {
|
5507
|
+
return this.finalStep.finishReason;
|
5508
|
+
}
|
5509
|
+
get warnings() {
|
5510
|
+
return this.finalStep.warnings;
|
5511
|
+
}
|
5512
|
+
get providerMetadata() {
|
5513
|
+
return this.finalStep.providerMetadata;
|
5514
|
+
}
|
5515
|
+
get response() {
|
5516
|
+
return this.finalStep.response;
|
5517
|
+
}
|
5518
|
+
get request() {
|
5519
|
+
return this.finalStep.request;
|
5520
|
+
}
|
5521
|
+
get usage() {
|
5522
|
+
return this.finalStep.usage;
|
5523
|
+
}
|
5524
|
+
get totalUsage() {
|
5525
|
+
return this.steps.reduce(
|
5526
|
+
(totalUsage, step) => {
|
5527
|
+
return addLanguageModelUsage(totalUsage, step.usage);
|
5528
|
+
},
|
5529
|
+
{
|
5530
|
+
inputTokens: void 0,
|
5531
|
+
outputTokens: void 0,
|
5532
|
+
totalTokens: void 0,
|
5533
|
+
reasoningTokens: void 0,
|
5534
|
+
cachedInputTokens: void 0
|
5535
|
+
}
|
5536
|
+
);
|
5769
5537
|
}
|
5770
5538
|
get experimental_output() {
|
5771
5539
|
if (this.resolvedOutput == null) {
|
@@ -5797,7 +5565,7 @@ __export(output_exports, {
|
|
5797
5565
|
});
|
5798
5566
|
import {
|
5799
5567
|
asSchema as asSchema4,
|
5800
|
-
safeParseJSON as
|
5568
|
+
safeParseJSON as safeParseJSON4,
|
5801
5569
|
safeValidateTypes as safeValidateTypes4
|
5802
5570
|
} from "@ai-sdk/provider-utils";
|
5803
5571
|
var text = () => ({
|
@@ -5839,7 +5607,7 @@ var object = ({
|
|
5839
5607
|
}
|
5840
5608
|
},
|
5841
5609
|
async parseOutput({ text: text2 }, context) {
|
5842
|
-
const parseResult = await
|
5610
|
+
const parseResult = await safeParseJSON4({ text: text2 });
|
5843
5611
|
if (!parseResult.success) {
|
5844
5612
|
throw new NoObjectGeneratedError({
|
5845
5613
|
message: "No object generated: could not parse the response.",
|
@@ -5946,25 +5714,6 @@ function asArray(value) {
|
|
5946
5714
|
return value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
5947
5715
|
}
|
5948
5716
|
|
5949
|
-
// src/util/consume-stream.ts
|
5950
|
-
async function consumeStream({
|
5951
|
-
stream,
|
5952
|
-
onError
|
5953
|
-
}) {
|
5954
|
-
const reader = stream.getReader();
|
5955
|
-
try {
|
5956
|
-
while (true) {
|
5957
|
-
const { done } = await reader.read();
|
5958
|
-
if (done)
|
5959
|
-
break;
|
5960
|
-
}
|
5961
|
-
} catch (error) {
|
5962
|
-
onError == null ? void 0 : onError(error);
|
5963
|
-
} finally {
|
5964
|
-
reader.releaseLock();
|
5965
|
-
}
|
5966
|
-
}
|
5967
|
-
|
5968
5717
|
// core/generate-text/run-tools-transformation.ts
|
5969
5718
|
import { generateId } from "@ai-sdk/provider-utils";
|
5970
5719
|
function runToolsTransformation({
|
@@ -6165,10 +5914,6 @@ var originalGenerateId4 = createIdGenerator4({
|
|
6165
5914
|
prefix: "aitxt",
|
6166
5915
|
size: 24
|
6167
5916
|
});
|
6168
|
-
var originalGenerateMessageId2 = createIdGenerator4({
|
6169
|
-
prefix: "msg",
|
6170
|
-
size: 24
|
6171
|
-
});
|
6172
5917
|
function streamText({
|
6173
5918
|
model,
|
6174
5919
|
tools,
|
@@ -6180,9 +5925,7 @@ function streamText({
|
|
6180
5925
|
abortSignal,
|
6181
5926
|
headers,
|
6182
5927
|
maxSteps = 1,
|
6183
|
-
experimental_generateMessageId: generateMessageId = originalGenerateMessageId2,
|
6184
5928
|
experimental_output: output,
|
6185
|
-
experimental_continueSteps: continueSteps = false,
|
6186
5929
|
experimental_telemetry: telemetry,
|
6187
5930
|
providerOptions,
|
6188
5931
|
experimental_toolCallStreaming = false,
|
@@ -6219,7 +5962,6 @@ function streamText({
|
|
6219
5962
|
repairToolCall,
|
6220
5963
|
maxSteps,
|
6221
5964
|
output,
|
6222
|
-
continueSteps,
|
6223
5965
|
providerOptions,
|
6224
5966
|
onChunk,
|
6225
5967
|
onError,
|
@@ -6227,8 +5969,7 @@ function streamText({
|
|
6227
5969
|
onStepFinish,
|
6228
5970
|
now: now2,
|
6229
5971
|
currentDate,
|
6230
|
-
generateId: generateId3
|
6231
|
-
generateMessageId
|
5972
|
+
generateId: generateId3
|
6232
5973
|
});
|
6233
5974
|
}
|
6234
5975
|
function createOutputTransformStream(output) {
|
@@ -6254,7 +5995,7 @@ function createOutputTransformStream(output) {
|
|
6254
5995
|
}
|
6255
5996
|
return new TransformStream({
|
6256
5997
|
async transform(chunk, controller) {
|
6257
|
-
if (chunk.type === "step
|
5998
|
+
if (chunk.type === "finish-step") {
|
6258
5999
|
publishTextChunk({ controller });
|
6259
6000
|
}
|
6260
6001
|
if (chunk.type !== "text") {
|
@@ -6298,32 +6039,18 @@ var DefaultStreamTextResult = class {
|
|
6298
6039
|
repairToolCall,
|
6299
6040
|
maxSteps,
|
6300
6041
|
output,
|
6301
|
-
continueSteps,
|
6302
6042
|
providerOptions,
|
6303
6043
|
now: now2,
|
6304
6044
|
currentDate,
|
6305
6045
|
generateId: generateId3,
|
6306
|
-
generateMessageId,
|
6307
6046
|
onChunk,
|
6308
6047
|
onError,
|
6309
6048
|
onFinish,
|
6310
6049
|
onStepFinish
|
6311
6050
|
}) {
|
6312
|
-
this.
|
6313
|
-
this.usagePromise = new DelayedPromise();
|
6051
|
+
this.totalUsagePromise = new DelayedPromise();
|
6314
6052
|
this.finishReasonPromise = new DelayedPromise();
|
6315
|
-
this.providerMetadataPromise = new DelayedPromise();
|
6316
|
-
this.textPromise = new DelayedPromise();
|
6317
|
-
this.reasoningPromise = new DelayedPromise();
|
6318
|
-
this.reasoningDetailsPromise = new DelayedPromise();
|
6319
|
-
this.sourcesPromise = new DelayedPromise();
|
6320
|
-
this.filesPromise = new DelayedPromise();
|
6321
|
-
this.toolCallsPromise = new DelayedPromise();
|
6322
|
-
this.toolResultsPromise = new DelayedPromise();
|
6323
|
-
this.requestPromise = new DelayedPromise();
|
6324
|
-
this.responsePromise = new DelayedPromise();
|
6325
6053
|
this.stepsPromise = new DelayedPromise();
|
6326
|
-
this.contentPromise = new DelayedPromise();
|
6327
6054
|
if (maxSteps < 1) {
|
6328
6055
|
throw new InvalidArgumentError({
|
6329
6056
|
parameter: "maxSteps",
|
@@ -6332,23 +6059,14 @@ var DefaultStreamTextResult = class {
|
|
6332
6059
|
});
|
6333
6060
|
}
|
6334
6061
|
this.output = output;
|
6335
|
-
|
6336
|
-
let recordedContinuationText = "";
|
6337
|
-
let recordedFullText = "";
|
6062
|
+
this.generateId = generateId3;
|
6338
6063
|
let activeReasoningPart = void 0;
|
6339
6064
|
let recordedContent = [];
|
6340
|
-
const
|
6341
|
-
const recordedResponse = {
|
6342
|
-
id: generateId3(),
|
6343
|
-
timestamp: currentDate(),
|
6344
|
-
modelId: model.modelId,
|
6345
|
-
messages: []
|
6346
|
-
};
|
6347
|
-
let recordedToolCalls = [];
|
6348
|
-
let recordedToolResults = [];
|
6065
|
+
const recordedResponseMessages = [];
|
6349
6066
|
let recordedFinishReason = void 0;
|
6350
|
-
let
|
6351
|
-
let
|
6067
|
+
let recordedTotalUsage = void 0;
|
6068
|
+
let recordedRequest = {};
|
6069
|
+
let recordedWarnings = [];
|
6352
6070
|
const recordedSteps = [];
|
6353
6071
|
let rootSpan;
|
6354
6072
|
const eventProcessor = new TransformStream({
|
@@ -6362,9 +6080,6 @@ var DefaultStreamTextResult = class {
|
|
6362
6080
|
await (onError == null ? void 0 : onError({ error: part.error }));
|
6363
6081
|
}
|
6364
6082
|
if (part.type === "text") {
|
6365
|
-
recordedStepText += part.text;
|
6366
|
-
recordedContinuationText += part.text;
|
6367
|
-
recordedFullText += part.text;
|
6368
6083
|
const latestContent = recordedContent[recordedContent.length - 1];
|
6369
6084
|
if ((latestContent == null ? void 0 : latestContent.type) === "text") {
|
6370
6085
|
latestContent.text += part.text;
|
@@ -6377,12 +6092,12 @@ var DefaultStreamTextResult = class {
|
|
6377
6092
|
activeReasoningPart = {
|
6378
6093
|
type: "reasoning",
|
6379
6094
|
text: part.text,
|
6380
|
-
|
6095
|
+
providerMetadata: part.providerMetadata
|
6381
6096
|
};
|
6382
6097
|
recordedContent.push(activeReasoningPart);
|
6383
6098
|
} else {
|
6384
6099
|
activeReasoningPart.text += part.text;
|
6385
|
-
activeReasoningPart.
|
6100
|
+
activeReasoningPart.providerMetadata = part.providerMetadata;
|
6386
6101
|
}
|
6387
6102
|
}
|
6388
6103
|
if (part.type === "reasoning-part-finish" && activeReasoningPart != null) {
|
@@ -6393,129 +6108,76 @@ var DefaultStreamTextResult = class {
|
|
6393
6108
|
}
|
6394
6109
|
if (part.type === "source") {
|
6395
6110
|
recordedContent.push(part);
|
6396
|
-
recordedSources.push(part);
|
6397
6111
|
}
|
6398
6112
|
if (part.type === "tool-call") {
|
6399
6113
|
recordedContent.push(part);
|
6400
|
-
recordedToolCalls.push(part);
|
6401
6114
|
}
|
6402
6115
|
if (part.type === "tool-result") {
|
6403
6116
|
recordedContent.push(part);
|
6404
|
-
recordedToolResults.push(part);
|
6405
6117
|
}
|
6406
|
-
if (part.type === "step
|
6118
|
+
if (part.type === "start-step") {
|
6119
|
+
recordedRequest = part.request;
|
6120
|
+
recordedWarnings = part.warnings;
|
6121
|
+
}
|
6122
|
+
if (part.type === "finish-step") {
|
6407
6123
|
const stepMessages = toResponseMessages({
|
6408
|
-
|
6409
|
-
|
6410
|
-
reasoning: extractReasoning(recordedContent),
|
6411
|
-
tools: tools != null ? tools : {},
|
6412
|
-
toolCalls: recordedToolCalls,
|
6413
|
-
toolResults: recordedToolResults,
|
6414
|
-
messageId: part.messageId,
|
6415
|
-
generateMessageId
|
6124
|
+
content: recordedContent,
|
6125
|
+
tools: tools != null ? tools : {}
|
6416
6126
|
});
|
6417
|
-
const
|
6418
|
-
let nextStepType = "done";
|
6419
|
-
if (currentStep + 1 < maxSteps) {
|
6420
|
-
if (continueSteps && part.finishReason === "length" && // only use continue when there are no tool calls:
|
6421
|
-
recordedToolCalls.length === 0) {
|
6422
|
-
nextStepType = "continue";
|
6423
|
-
} else if (
|
6424
|
-
// there are tool calls:
|
6425
|
-
recordedToolCalls.length > 0 && // all current tool calls have results:
|
6426
|
-
recordedToolResults.length === recordedToolCalls.length
|
6427
|
-
) {
|
6428
|
-
nextStepType = "tool-result";
|
6429
|
-
}
|
6430
|
-
}
|
6431
|
-
const currentStepResult = {
|
6432
|
-
stepType,
|
6127
|
+
const currentStepResult = new DefaultStepResult({
|
6433
6128
|
content: recordedContent,
|
6434
|
-
text: recordedStepText,
|
6435
|
-
reasoningText: asReasoningText(extractReasoning(recordedContent)),
|
6436
|
-
reasoning: extractReasoning(recordedContent),
|
6437
|
-
files: extractFiles(recordedContent),
|
6438
|
-
sources: extractSources(recordedContent),
|
6439
|
-
toolCalls: recordedToolCalls,
|
6440
|
-
toolResults: recordedToolResults,
|
6441
6129
|
finishReason: part.finishReason,
|
6442
6130
|
usage: part.usage,
|
6443
|
-
warnings:
|
6444
|
-
request:
|
6131
|
+
warnings: recordedWarnings,
|
6132
|
+
request: recordedRequest,
|
6445
6133
|
response: {
|
6446
6134
|
...part.response,
|
6447
|
-
messages: [...
|
6135
|
+
messages: [...recordedResponseMessages, ...stepMessages]
|
6448
6136
|
},
|
6449
|
-
providerMetadata: part.providerMetadata
|
6450
|
-
|
6451
|
-
};
|
6137
|
+
providerMetadata: part.providerMetadata
|
6138
|
+
});
|
6452
6139
|
await (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));
|
6453
6140
|
recordedSteps.push(currentStepResult);
|
6454
6141
|
recordedContent = [];
|
6455
|
-
recordedToolCalls = [];
|
6456
|
-
recordedToolResults = [];
|
6457
|
-
recordedStepText = "";
|
6458
6142
|
activeReasoningPart = void 0;
|
6459
|
-
|
6460
|
-
stepType = nextStepType;
|
6461
|
-
}
|
6462
|
-
if (nextStepType !== "continue") {
|
6463
|
-
recordedResponse.messages.push(...stepMessages);
|
6464
|
-
recordedContinuationText = "";
|
6465
|
-
}
|
6143
|
+
recordedResponseMessages.push(...stepMessages);
|
6466
6144
|
}
|
6467
6145
|
if (part.type === "finish") {
|
6468
|
-
|
6469
|
-
recordedResponse.timestamp = part.response.timestamp;
|
6470
|
-
recordedResponse.modelId = part.response.modelId;
|
6471
|
-
recordedResponse.headers = part.response.headers;
|
6472
|
-
recordedUsage = part.usage;
|
6146
|
+
recordedTotalUsage = part.totalUsage;
|
6473
6147
|
recordedFinishReason = part.finishReason;
|
6474
6148
|
}
|
6475
6149
|
},
|
6476
6150
|
async flush(controller) {
|
6477
|
-
var _a17;
|
6478
6151
|
try {
|
6479
6152
|
if (recordedSteps.length === 0) {
|
6480
6153
|
return;
|
6481
6154
|
}
|
6482
|
-
const lastStep = recordedSteps[recordedSteps.length - 1];
|
6483
|
-
self.contentPromise.resolve(lastStep.content);
|
6484
|
-
self.warningsPromise.resolve(lastStep.warnings);
|
6485
|
-
self.requestPromise.resolve(lastStep.request);
|
6486
|
-
self.responsePromise.resolve(lastStep.response);
|
6487
|
-
self.toolCallsPromise.resolve(lastStep.toolCalls);
|
6488
|
-
self.toolResultsPromise.resolve(lastStep.toolResults);
|
6489
|
-
self.providerMetadataPromise.resolve(lastStep.providerMetadata);
|
6490
|
-
self.reasoningPromise.resolve(lastStep.reasoningText);
|
6491
|
-
self.reasoningDetailsPromise.resolve(lastStep.reasoning);
|
6492
6155
|
const finishReason = recordedFinishReason != null ? recordedFinishReason : "unknown";
|
6493
|
-
const
|
6156
|
+
const totalUsage = recordedTotalUsage != null ? recordedTotalUsage : {
|
6494
6157
|
inputTokens: void 0,
|
6495
6158
|
outputTokens: void 0,
|
6496
6159
|
totalTokens: void 0
|
6497
6160
|
};
|
6498
6161
|
self.finishReasonPromise.resolve(finishReason);
|
6499
|
-
self.
|
6500
|
-
self.textPromise.resolve(recordedFullText);
|
6501
|
-
self.sourcesPromise.resolve(recordedSources);
|
6502
|
-
self.filesPromise.resolve(lastStep.files);
|
6162
|
+
self.totalUsagePromise.resolve(totalUsage);
|
6503
6163
|
self.stepsPromise.resolve(recordedSteps);
|
6164
|
+
const finalStep = recordedSteps[recordedSteps.length - 1];
|
6504
6165
|
await (onFinish == null ? void 0 : onFinish({
|
6505
6166
|
finishReason,
|
6506
|
-
|
6507
|
-
|
6508
|
-
|
6509
|
-
|
6510
|
-
|
6511
|
-
|
6512
|
-
|
6513
|
-
|
6514
|
-
|
6515
|
-
|
6516
|
-
|
6517
|
-
|
6518
|
-
|
6167
|
+
totalUsage,
|
6168
|
+
usage: finalStep.usage,
|
6169
|
+
content: finalStep.content,
|
6170
|
+
text: finalStep.text,
|
6171
|
+
reasoningText: finalStep.reasoningText,
|
6172
|
+
reasoning: finalStep.reasoning,
|
6173
|
+
files: finalStep.files,
|
6174
|
+
sources: finalStep.sources,
|
6175
|
+
toolCalls: finalStep.toolCalls,
|
6176
|
+
toolResults: finalStep.toolResults,
|
6177
|
+
request: finalStep.request,
|
6178
|
+
response: finalStep.response,
|
6179
|
+
warnings: finalStep.warnings,
|
6180
|
+
providerMetadata: finalStep.providerMetadata,
|
6519
6181
|
steps: recordedSteps
|
6520
6182
|
}));
|
6521
6183
|
rootSpan.setAttributes(
|
@@ -6523,18 +6185,18 @@ var DefaultStreamTextResult = class {
|
|
6523
6185
|
telemetry,
|
6524
6186
|
attributes: {
|
6525
6187
|
"ai.response.finishReason": finishReason,
|
6526
|
-
"ai.response.text": { output: () =>
|
6188
|
+
"ai.response.text": { output: () => finalStep.text },
|
6527
6189
|
"ai.response.toolCalls": {
|
6528
6190
|
output: () => {
|
6529
|
-
var
|
6530
|
-
return ((
|
6191
|
+
var _a17;
|
6192
|
+
return ((_a17 = finalStep.toolCalls) == null ? void 0 : _a17.length) ? JSON.stringify(finalStep.toolCalls) : void 0;
|
6531
6193
|
}
|
6532
6194
|
},
|
6533
|
-
"ai.usage.inputTokens":
|
6534
|
-
"ai.usage.outputTokens":
|
6535
|
-
"ai.usage.totalTokens":
|
6536
|
-
"ai.usage.reasoningTokens":
|
6537
|
-
"ai.usage.cachedInputTokens":
|
6195
|
+
"ai.usage.inputTokens": totalUsage.inputTokens,
|
6196
|
+
"ai.usage.outputTokens": totalUsage.outputTokens,
|
6197
|
+
"ai.usage.totalTokens": totalUsage.totalTokens,
|
6198
|
+
"ai.usage.reasoningTokens": totalUsage.reasoningTokens,
|
6199
|
+
"ai.usage.cachedInputTokens": totalUsage.cachedInputTokens
|
6538
6200
|
}
|
6539
6201
|
})
|
6540
6202
|
);
|
@@ -6593,11 +6255,7 @@ var DefaultStreamTextResult = class {
|
|
6593
6255
|
async function streamStep({
|
6594
6256
|
currentStep,
|
6595
6257
|
responseMessages,
|
6596
|
-
usage
|
6597
|
-
stepType: stepType2,
|
6598
|
-
previousStepText,
|
6599
|
-
hasLeadingWhitespace,
|
6600
|
-
messageId
|
6258
|
+
usage
|
6601
6259
|
}) {
|
6602
6260
|
const initialPrompt = await standardizePrompt({
|
6603
6261
|
system,
|
@@ -6695,8 +6353,7 @@ var DefaultStreamTextResult = class {
|
|
6695
6353
|
const stepToolCalls = [];
|
6696
6354
|
const stepToolResults = [];
|
6697
6355
|
let warnings;
|
6698
|
-
const
|
6699
|
-
const stepFiles = [];
|
6356
|
+
const stepContent = [];
|
6700
6357
|
let activeReasoningPart2 = void 0;
|
6701
6358
|
let stepFinishReason = "unknown";
|
6702
6359
|
let stepUsage = {
|
@@ -6707,25 +6364,17 @@ var DefaultStreamTextResult = class {
|
|
6707
6364
|
let stepProviderMetadata;
|
6708
6365
|
let stepFirstChunk = true;
|
6709
6366
|
let stepText = "";
|
6710
|
-
let fullStepText = stepType2 === "continue" ? previousStepText : "";
|
6711
6367
|
let stepResponse = {
|
6712
6368
|
id: generateId3(),
|
6713
6369
|
timestamp: currentDate(),
|
6714
6370
|
modelId: model.modelId
|
6715
6371
|
};
|
6716
|
-
let chunkBuffer = "";
|
6717
|
-
let chunkTextPublished = false;
|
6718
|
-
let inWhitespacePrefix = true;
|
6719
|
-
let hasWhitespaceSuffix = false;
|
6720
6372
|
async function publishTextChunk({
|
6721
6373
|
controller,
|
6722
6374
|
chunk
|
6723
6375
|
}) {
|
6724
6376
|
controller.enqueue(chunk);
|
6725
6377
|
stepText += chunk.text;
|
6726
|
-
fullStepText += chunk.text;
|
6727
|
-
chunkTextPublished = true;
|
6728
|
-
hasWhitespaceSuffix = chunk.text.trimEnd() !== chunk.text;
|
6729
6378
|
}
|
6730
6379
|
self.addStream(
|
6731
6380
|
transformedStream.pipeThrough(
|
@@ -6734,6 +6383,7 @@ var DefaultStreamTextResult = class {
|
|
6734
6383
|
var _a17, _b, _c, _d;
|
6735
6384
|
if (chunk.type === "stream-start") {
|
6736
6385
|
warnings = chunk.warnings;
|
6386
|
+
controller.enqueue({ type: "start" });
|
6737
6387
|
return;
|
6738
6388
|
}
|
6739
6389
|
if (stepFirstChunk) {
|
@@ -6746,8 +6396,7 @@ var DefaultStreamTextResult = class {
|
|
6746
6396
|
"ai.response.msToFirstChunk": msToFirstChunk
|
6747
6397
|
});
|
6748
6398
|
controller.enqueue({
|
6749
|
-
type: "step
|
6750
|
-
messageId,
|
6399
|
+
type: "start-step",
|
6751
6400
|
request: stepRequest,
|
6752
6401
|
warnings: warnings != null ? warnings : []
|
6753
6402
|
});
|
@@ -6758,27 +6407,7 @@ var DefaultStreamTextResult = class {
|
|
6758
6407
|
const chunkType = chunk.type;
|
6759
6408
|
switch (chunkType) {
|
6760
6409
|
case "text": {
|
6761
|
-
|
6762
|
-
const trimmedChunkText = inWhitespacePrefix && hasLeadingWhitespace ? chunk.text.trimStart() : chunk.text;
|
6763
|
-
if (trimmedChunkText.length === 0) {
|
6764
|
-
break;
|
6765
|
-
}
|
6766
|
-
inWhitespacePrefix = false;
|
6767
|
-
chunkBuffer += trimmedChunkText;
|
6768
|
-
const split = splitOnLastWhitespace(chunkBuffer);
|
6769
|
-
if (split != null) {
|
6770
|
-
chunkBuffer = split.suffix;
|
6771
|
-
await publishTextChunk({
|
6772
|
-
controller,
|
6773
|
-
chunk: {
|
6774
|
-
type: "text",
|
6775
|
-
text: split.prefix + split.whitespace
|
6776
|
-
}
|
6777
|
-
});
|
6778
|
-
}
|
6779
|
-
} else {
|
6780
|
-
await publishTextChunk({ controller, chunk });
|
6781
|
-
}
|
6410
|
+
await publishTextChunk({ controller, chunk });
|
6782
6411
|
break;
|
6783
6412
|
}
|
6784
6413
|
case "reasoning": {
|
@@ -6787,12 +6416,12 @@ var DefaultStreamTextResult = class {
|
|
6787
6416
|
activeReasoningPart2 = {
|
6788
6417
|
type: "reasoning",
|
6789
6418
|
text: chunk.text,
|
6790
|
-
|
6419
|
+
providerMetadata: chunk.providerMetadata
|
6791
6420
|
};
|
6792
|
-
|
6421
|
+
stepContent.push(activeReasoningPart2);
|
6793
6422
|
} else {
|
6794
6423
|
activeReasoningPart2.text += chunk.text;
|
6795
|
-
activeReasoningPart2.
|
6424
|
+
activeReasoningPart2.providerMetadata = chunk.providerMetadata;
|
6796
6425
|
}
|
6797
6426
|
break;
|
6798
6427
|
}
|
@@ -6804,11 +6433,13 @@ var DefaultStreamTextResult = class {
|
|
6804
6433
|
case "tool-call": {
|
6805
6434
|
controller.enqueue(chunk);
|
6806
6435
|
stepToolCalls.push(chunk);
|
6436
|
+
stepContent.push(chunk);
|
6807
6437
|
break;
|
6808
6438
|
}
|
6809
6439
|
case "tool-result": {
|
6810
6440
|
controller.enqueue(chunk);
|
6811
6441
|
stepToolResults.push(chunk);
|
6442
|
+
stepContent.push(chunk);
|
6812
6443
|
break;
|
6813
6444
|
}
|
6814
6445
|
case "response-metadata": {
|
@@ -6832,11 +6463,15 @@ var DefaultStreamTextResult = class {
|
|
6832
6463
|
break;
|
6833
6464
|
}
|
6834
6465
|
case "file": {
|
6835
|
-
|
6466
|
+
stepContent.push(chunk);
|
6467
|
+
controller.enqueue(chunk);
|
6468
|
+
break;
|
6469
|
+
}
|
6470
|
+
case "source": {
|
6471
|
+
stepContent.push(chunk);
|
6836
6472
|
controller.enqueue(chunk);
|
6837
6473
|
break;
|
6838
6474
|
}
|
6839
|
-
case "source":
|
6840
6475
|
case "tool-call-streaming-start":
|
6841
6476
|
case "tool-call-delta": {
|
6842
6477
|
controller.enqueue(chunk);
|
@@ -6856,27 +6491,6 @@ var DefaultStreamTextResult = class {
|
|
6856
6491
|
// invoke onFinish callback and resolve toolResults promise when the stream is about to close:
|
6857
6492
|
async flush(controller) {
|
6858
6493
|
const stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;
|
6859
|
-
let nextStepType = "done";
|
6860
|
-
if (currentStep + 1 < maxSteps) {
|
6861
|
-
if (continueSteps && stepFinishReason === "length" && // only use continue when there are no tool calls:
|
6862
|
-
stepToolCalls.length === 0) {
|
6863
|
-
nextStepType = "continue";
|
6864
|
-
} else if (
|
6865
|
-
// there are tool calls:
|
6866
|
-
stepToolCalls.length > 0 && // all current tool calls have results:
|
6867
|
-
stepToolResults.length === stepToolCalls.length
|
6868
|
-
) {
|
6869
|
-
nextStepType = "tool-result";
|
6870
|
-
}
|
6871
|
-
}
|
6872
|
-
if (continueSteps && chunkBuffer.length > 0 && (nextStepType !== "continue" || // when the next step is a regular step, publish the buffer
|
6873
|
-
stepType2 === "continue" && !chunkTextPublished)) {
|
6874
|
-
await publishTextChunk({
|
6875
|
-
controller,
|
6876
|
-
chunk: { type: "text", text: chunkBuffer }
|
6877
|
-
});
|
6878
|
-
chunkBuffer = "";
|
6879
|
-
}
|
6880
6494
|
try {
|
6881
6495
|
doStreamSpan.setAttributes(
|
6882
6496
|
selectTelemetryAttributes({
|
@@ -6909,69 +6523,37 @@ var DefaultStreamTextResult = class {
|
|
6909
6523
|
doStreamSpan.end();
|
6910
6524
|
}
|
6911
6525
|
controller.enqueue({
|
6912
|
-
type: "step
|
6526
|
+
type: "finish-step",
|
6913
6527
|
finishReason: stepFinishReason,
|
6914
6528
|
usage: stepUsage,
|
6915
6529
|
providerMetadata: stepProviderMetadata,
|
6916
|
-
request: stepRequest,
|
6917
6530
|
response: {
|
6918
6531
|
...stepResponse,
|
6919
6532
|
headers: response == null ? void 0 : response.headers
|
6920
|
-
}
|
6921
|
-
warnings,
|
6922
|
-
isContinued: nextStepType === "continue",
|
6923
|
-
messageId
|
6533
|
+
}
|
6924
6534
|
});
|
6925
6535
|
const combinedUsage = addLanguageModelUsage(usage, stepUsage);
|
6926
|
-
if (
|
6536
|
+
if (currentStep + 1 < maxSteps && // there are tool calls:
|
6537
|
+
stepToolCalls.length > 0 && // all current tool calls have results:
|
6538
|
+
stepToolResults.length === stepToolCalls.length) {
|
6539
|
+
responseMessages.push(
|
6540
|
+
...toResponseMessages({
|
6541
|
+
content: stepContent,
|
6542
|
+
tools: tools != null ? tools : {}
|
6543
|
+
})
|
6544
|
+
);
|
6545
|
+
await streamStep({
|
6546
|
+
currentStep: currentStep + 1,
|
6547
|
+
responseMessages,
|
6548
|
+
usage: combinedUsage
|
6549
|
+
});
|
6550
|
+
} else {
|
6927
6551
|
controller.enqueue({
|
6928
6552
|
type: "finish",
|
6929
6553
|
finishReason: stepFinishReason,
|
6930
|
-
|
6931
|
-
providerMetadata: stepProviderMetadata,
|
6932
|
-
response: {
|
6933
|
-
...stepResponse,
|
6934
|
-
headers: response == null ? void 0 : response.headers
|
6935
|
-
}
|
6554
|
+
totalUsage: combinedUsage
|
6936
6555
|
});
|
6937
6556
|
self.closeStream();
|
6938
|
-
} else {
|
6939
|
-
if (stepType2 === "continue") {
|
6940
|
-
const lastMessage = responseMessages[responseMessages.length - 1];
|
6941
|
-
if (typeof lastMessage.content === "string") {
|
6942
|
-
lastMessage.content += stepText;
|
6943
|
-
} else {
|
6944
|
-
lastMessage.content.push({
|
6945
|
-
text: stepText,
|
6946
|
-
type: "text"
|
6947
|
-
});
|
6948
|
-
}
|
6949
|
-
} else {
|
6950
|
-
responseMessages.push(
|
6951
|
-
...toResponseMessages({
|
6952
|
-
text: stepText,
|
6953
|
-
files: stepFiles,
|
6954
|
-
reasoning: stepReasoning,
|
6955
|
-
tools: tools != null ? tools : {},
|
6956
|
-
toolCalls: stepToolCalls,
|
6957
|
-
toolResults: stepToolResults,
|
6958
|
-
messageId,
|
6959
|
-
generateMessageId
|
6960
|
-
})
|
6961
|
-
);
|
6962
|
-
}
|
6963
|
-
await streamStep({
|
6964
|
-
currentStep: currentStep + 1,
|
6965
|
-
responseMessages,
|
6966
|
-
usage: combinedUsage,
|
6967
|
-
stepType: nextStepType,
|
6968
|
-
previousStepText: fullStepText,
|
6969
|
-
hasLeadingWhitespace: hasWhitespaceSuffix,
|
6970
|
-
messageId: (
|
6971
|
-
// keep the same id when continuing a step:
|
6972
|
-
nextStepType === "continue" ? messageId : generateMessageId()
|
6973
|
-
)
|
6974
|
-
});
|
6975
6557
|
}
|
6976
6558
|
}
|
6977
6559
|
})
|
@@ -6985,11 +6567,7 @@ var DefaultStreamTextResult = class {
|
|
6985
6567
|
inputTokens: void 0,
|
6986
6568
|
outputTokens: void 0,
|
6987
6569
|
totalTokens: void 0
|
6988
|
-
}
|
6989
|
-
previousStepText: "",
|
6990
|
-
stepType: "initial",
|
6991
|
-
hasLeadingWhitespace: false,
|
6992
|
-
messageId: generateMessageId()
|
6570
|
+
}
|
6993
6571
|
});
|
6994
6572
|
}
|
6995
6573
|
}).catch((error) => {
|
@@ -7004,50 +6582,56 @@ var DefaultStreamTextResult = class {
|
|
7004
6582
|
self.closeStream();
|
7005
6583
|
});
|
7006
6584
|
}
|
7007
|
-
get
|
7008
|
-
return this.
|
6585
|
+
get steps() {
|
6586
|
+
return this.stepsPromise.value;
|
7009
6587
|
}
|
7010
|
-
get
|
7011
|
-
return this.
|
6588
|
+
get finalStep() {
|
6589
|
+
return this.steps.then((steps) => steps[steps.length - 1]);
|
7012
6590
|
}
|
7013
|
-
get
|
7014
|
-
return this.
|
6591
|
+
get content() {
|
6592
|
+
return this.finalStep.then((step) => step.content);
|
7015
6593
|
}
|
7016
|
-
get
|
7017
|
-
return this.
|
6594
|
+
get warnings() {
|
6595
|
+
return this.finalStep.then((step) => step.warnings);
|
7018
6596
|
}
|
7019
6597
|
get providerMetadata() {
|
7020
|
-
return this.
|
6598
|
+
return this.finalStep.then((step) => step.providerMetadata);
|
7021
6599
|
}
|
7022
6600
|
get text() {
|
7023
|
-
return this.
|
6601
|
+
return this.finalStep.then((step) => step.text);
|
7024
6602
|
}
|
7025
6603
|
get reasoningText() {
|
7026
|
-
return this.
|
6604
|
+
return this.finalStep.then((step) => step.reasoningText);
|
7027
6605
|
}
|
7028
6606
|
get reasoning() {
|
7029
|
-
return this.
|
6607
|
+
return this.finalStep.then((step) => step.reasoning);
|
7030
6608
|
}
|
7031
6609
|
get sources() {
|
7032
|
-
return this.
|
6610
|
+
return this.finalStep.then((step) => step.sources);
|
7033
6611
|
}
|
7034
6612
|
get files() {
|
7035
|
-
return this.
|
6613
|
+
return this.finalStep.then((step) => step.files);
|
7036
6614
|
}
|
7037
6615
|
get toolCalls() {
|
7038
|
-
return this.
|
6616
|
+
return this.finalStep.then((step) => step.toolCalls);
|
7039
6617
|
}
|
7040
6618
|
get toolResults() {
|
7041
|
-
return this.
|
6619
|
+
return this.finalStep.then((step) => step.toolResults);
|
6620
|
+
}
|
6621
|
+
get usage() {
|
6622
|
+
return this.finalStep.then((step) => step.usage);
|
7042
6623
|
}
|
7043
6624
|
get request() {
|
7044
|
-
return this.
|
6625
|
+
return this.finalStep.then((step) => step.request);
|
7045
6626
|
}
|
7046
6627
|
get response() {
|
7047
|
-
return this.
|
6628
|
+
return this.finalStep.then((step) => step.response);
|
7048
6629
|
}
|
7049
|
-
get
|
7050
|
-
return this.
|
6630
|
+
get totalUsage() {
|
6631
|
+
return this.totalUsagePromise.value;
|
6632
|
+
}
|
6633
|
+
get finishReason() {
|
6634
|
+
return this.finishReasonPromise.value;
|
7051
6635
|
}
|
7052
6636
|
/**
|
7053
6637
|
Split out a new stream from the original stream.
|
@@ -7113,26 +6697,33 @@ var DefaultStreamTextResult = class {
|
|
7113
6697
|
)
|
7114
6698
|
);
|
7115
6699
|
}
|
7116
|
-
|
7117
|
-
|
7118
|
-
|
7119
|
-
|
6700
|
+
toUIMessageStream({
|
6701
|
+
newMessageId,
|
6702
|
+
originalMessages = [],
|
6703
|
+
onFinish,
|
6704
|
+
messageMetadata,
|
7120
6705
|
sendReasoning = false,
|
7121
6706
|
sendSources = false,
|
7122
|
-
|
6707
|
+
experimental_sendStart = true,
|
6708
|
+
experimental_sendFinish = true,
|
6709
|
+
onError = () => "An error occurred."
|
6710
|
+
// mask error messages for safety by default
|
7123
6711
|
} = {}) {
|
7124
|
-
|
6712
|
+
const lastMessage = originalMessages[originalMessages.length - 1];
|
6713
|
+
const isContinuation = (lastMessage == null ? void 0 : lastMessage.role) === "assistant";
|
6714
|
+
const messageId = isContinuation ? lastMessage.id : newMessageId;
|
6715
|
+
const baseStream = this.fullStream.pipeThrough(
|
7125
6716
|
new TransformStream({
|
7126
|
-
transform: async (
|
7127
|
-
const
|
7128
|
-
switch (
|
6717
|
+
transform: async (part, controller) => {
|
6718
|
+
const partType = part.type;
|
6719
|
+
switch (partType) {
|
7129
6720
|
case "text": {
|
7130
|
-
controller.enqueue({ type: "text", value:
|
6721
|
+
controller.enqueue({ type: "text", value: part.text });
|
7131
6722
|
break;
|
7132
6723
|
}
|
7133
6724
|
case "reasoning": {
|
7134
6725
|
if (sendReasoning) {
|
7135
|
-
controller.enqueue({ type: "reasoning", value:
|
6726
|
+
controller.enqueue({ type: "reasoning", value: part });
|
7136
6727
|
}
|
7137
6728
|
break;
|
7138
6729
|
}
|
@@ -7149,15 +6740,15 @@ var DefaultStreamTextResult = class {
|
|
7149
6740
|
controller.enqueue({
|
7150
6741
|
type: "file",
|
7151
6742
|
value: {
|
7152
|
-
mediaType:
|
7153
|
-
url: `data:${
|
6743
|
+
mediaType: part.file.mediaType,
|
6744
|
+
url: `data:${part.file.mediaType};base64,${part.file.base64}`
|
7154
6745
|
}
|
7155
6746
|
});
|
7156
6747
|
break;
|
7157
6748
|
}
|
7158
6749
|
case "source": {
|
7159
6750
|
if (sendSources) {
|
7160
|
-
controller.enqueue({ type: "source", value:
|
6751
|
+
controller.enqueue({ type: "source", value: part });
|
7161
6752
|
}
|
7162
6753
|
break;
|
7163
6754
|
}
|
@@ -7165,8 +6756,8 @@ var DefaultStreamTextResult = class {
|
|
7165
6756
|
controller.enqueue({
|
7166
6757
|
type: "tool-call-streaming-start",
|
7167
6758
|
value: {
|
7168
|
-
toolCallId:
|
7169
|
-
toolName:
|
6759
|
+
toolCallId: part.toolCallId,
|
6760
|
+
toolName: part.toolName
|
7170
6761
|
}
|
7171
6762
|
});
|
7172
6763
|
break;
|
@@ -7175,8 +6766,8 @@ var DefaultStreamTextResult = class {
|
|
7175
6766
|
controller.enqueue({
|
7176
6767
|
type: "tool-call-delta",
|
7177
6768
|
value: {
|
7178
|
-
toolCallId:
|
7179
|
-
argsTextDelta:
|
6769
|
+
toolCallId: part.toolCallId,
|
6770
|
+
argsTextDelta: part.argsTextDelta
|
7180
6771
|
}
|
7181
6772
|
});
|
7182
6773
|
break;
|
@@ -7185,9 +6776,9 @@ var DefaultStreamTextResult = class {
|
|
7185
6776
|
controller.enqueue({
|
7186
6777
|
type: "tool-call",
|
7187
6778
|
value: {
|
7188
|
-
toolCallId:
|
7189
|
-
toolName:
|
7190
|
-
args:
|
6779
|
+
toolCallId: part.toolCallId,
|
6780
|
+
toolName: part.toolName,
|
6781
|
+
args: part.args
|
7191
6782
|
}
|
7192
6783
|
});
|
7193
6784
|
break;
|
@@ -7196,8 +6787,8 @@ var DefaultStreamTextResult = class {
|
|
7196
6787
|
controller.enqueue({
|
7197
6788
|
type: "tool-result",
|
7198
6789
|
value: {
|
7199
|
-
toolCallId:
|
7200
|
-
result:
|
6790
|
+
toolCallId: part.toolCallId,
|
6791
|
+
result: part.result
|
7201
6792
|
}
|
7202
6793
|
});
|
7203
6794
|
break;
|
@@ -7205,69 +6796,100 @@ var DefaultStreamTextResult = class {
|
|
7205
6796
|
case "error": {
|
7206
6797
|
controller.enqueue({
|
7207
6798
|
type: "error",
|
7208
|
-
value: onError(
|
6799
|
+
value: onError(part.error)
|
7209
6800
|
});
|
7210
6801
|
break;
|
7211
6802
|
}
|
7212
|
-
case "step
|
6803
|
+
case "start-step": {
|
7213
6804
|
controller.enqueue({
|
7214
6805
|
type: "start-step",
|
7215
6806
|
value: {
|
7216
|
-
|
6807
|
+
metadata: messageMetadata == null ? void 0 : messageMetadata({ part })
|
7217
6808
|
}
|
7218
6809
|
});
|
7219
6810
|
break;
|
7220
6811
|
}
|
7221
|
-
case "step
|
6812
|
+
case "finish-step": {
|
7222
6813
|
controller.enqueue({
|
7223
6814
|
type: "finish-step",
|
7224
6815
|
value: {
|
7225
|
-
|
7226
|
-
usage: sendUsage ? chunk.usage : void 0,
|
7227
|
-
isContinued: chunk.isContinued
|
6816
|
+
metadata: messageMetadata == null ? void 0 : messageMetadata({ part })
|
7228
6817
|
}
|
7229
6818
|
});
|
7230
6819
|
break;
|
7231
6820
|
}
|
6821
|
+
case "start": {
|
6822
|
+
if (experimental_sendStart) {
|
6823
|
+
controller.enqueue({
|
6824
|
+
type: "start",
|
6825
|
+
value: {
|
6826
|
+
messageId,
|
6827
|
+
metadata: messageMetadata == null ? void 0 : messageMetadata({ part })
|
6828
|
+
}
|
6829
|
+
});
|
6830
|
+
}
|
6831
|
+
break;
|
6832
|
+
}
|
7232
6833
|
case "finish": {
|
7233
6834
|
if (experimental_sendFinish) {
|
7234
6835
|
controller.enqueue({
|
7235
|
-
type: "finish
|
6836
|
+
type: "finish",
|
7236
6837
|
value: {
|
7237
|
-
|
7238
|
-
usage: sendUsage ? chunk.usage : void 0
|
6838
|
+
metadata: messageMetadata == null ? void 0 : messageMetadata({ part })
|
7239
6839
|
}
|
7240
6840
|
});
|
7241
6841
|
}
|
7242
6842
|
break;
|
7243
6843
|
}
|
7244
6844
|
default: {
|
7245
|
-
const exhaustiveCheck =
|
6845
|
+
const exhaustiveCheck = partType;
|
7246
6846
|
throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
|
7247
6847
|
}
|
7248
6848
|
}
|
7249
6849
|
}
|
7250
6850
|
})
|
7251
6851
|
);
|
6852
|
+
return onFinish == null ? baseStream : processUIMessageStream({
|
6853
|
+
stream: baseStream,
|
6854
|
+
lastMessage,
|
6855
|
+
newMessageId: messageId != null ? messageId : this.generateId(),
|
6856
|
+
onFinish: ({ message }) => {
|
6857
|
+
const isContinuation2 = message.id === (lastMessage == null ? void 0 : lastMessage.id);
|
6858
|
+
onFinish({
|
6859
|
+
isContinuation: isContinuation2,
|
6860
|
+
responseMessage: message,
|
6861
|
+
messages: [
|
6862
|
+
...isContinuation2 ? originalMessages.slice(0, -1) : originalMessages,
|
6863
|
+
message
|
6864
|
+
]
|
6865
|
+
});
|
6866
|
+
}
|
6867
|
+
});
|
7252
6868
|
}
|
7253
|
-
|
7254
|
-
|
7255
|
-
|
6869
|
+
pipeUIMessageStreamToResponse(response, {
|
6870
|
+
newMessageId,
|
6871
|
+
originalMessages,
|
6872
|
+
onFinish,
|
6873
|
+
messageMetadata,
|
7256
6874
|
sendReasoning,
|
7257
6875
|
sendSources,
|
7258
6876
|
experimental_sendFinish,
|
7259
6877
|
experimental_sendStart,
|
6878
|
+
onError,
|
7260
6879
|
...init
|
7261
6880
|
} = {}) {
|
7262
|
-
|
6881
|
+
pipeUIMessageStreamToResponse({
|
7263
6882
|
response,
|
7264
|
-
|
7265
|
-
|
7266
|
-
|
6883
|
+
stream: this.toUIMessageStream({
|
6884
|
+
newMessageId,
|
6885
|
+
originalMessages,
|
6886
|
+
onFinish,
|
6887
|
+
messageMetadata,
|
7267
6888
|
sendReasoning,
|
7268
6889
|
sendSources,
|
7269
6890
|
experimental_sendFinish,
|
7270
|
-
experimental_sendStart
|
6891
|
+
experimental_sendStart,
|
6892
|
+
onError
|
7271
6893
|
}),
|
7272
6894
|
...init
|
7273
6895
|
});
|
@@ -7279,23 +6901,29 @@ var DefaultStreamTextResult = class {
|
|
7279
6901
|
...init
|
7280
6902
|
});
|
7281
6903
|
}
|
7282
|
-
|
7283
|
-
|
7284
|
-
|
6904
|
+
toUIMessageStreamResponse({
|
6905
|
+
newMessageId,
|
6906
|
+
originalMessages,
|
6907
|
+
onFinish,
|
6908
|
+
messageMetadata,
|
7285
6909
|
sendReasoning,
|
7286
6910
|
sendSources,
|
7287
6911
|
experimental_sendFinish,
|
7288
6912
|
experimental_sendStart,
|
6913
|
+
onError,
|
7289
6914
|
...init
|
7290
6915
|
} = {}) {
|
7291
|
-
return
|
7292
|
-
|
7293
|
-
|
7294
|
-
|
6916
|
+
return createUIMessageStreamResponse({
|
6917
|
+
stream: this.toUIMessageStream({
|
6918
|
+
newMessageId,
|
6919
|
+
originalMessages,
|
6920
|
+
onFinish,
|
6921
|
+
messageMetadata,
|
7295
6922
|
sendReasoning,
|
7296
6923
|
sendSources,
|
7297
6924
|
experimental_sendFinish,
|
7298
|
-
experimental_sendStart
|
6925
|
+
experimental_sendStart,
|
6926
|
+
onError
|
7299
6927
|
}),
|
7300
6928
|
...init
|
7301
6929
|
});
|
@@ -7308,39 +6936,6 @@ var DefaultStreamTextResult = class {
|
|
7308
6936
|
}
|
7309
6937
|
};
|
7310
6938
|
|
7311
|
-
// src/util/merge-objects.ts
|
7312
|
-
function mergeObjects(target, source) {
|
7313
|
-
if (target === void 0 && source === void 0) {
|
7314
|
-
return void 0;
|
7315
|
-
}
|
7316
|
-
if (target === void 0) {
|
7317
|
-
return source;
|
7318
|
-
}
|
7319
|
-
if (source === void 0) {
|
7320
|
-
return target;
|
7321
|
-
}
|
7322
|
-
const result = { ...target };
|
7323
|
-
for (const key in source) {
|
7324
|
-
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
7325
|
-
const sourceValue = source[key];
|
7326
|
-
if (sourceValue === void 0)
|
7327
|
-
continue;
|
7328
|
-
const targetValue = key in target ? target[key] : void 0;
|
7329
|
-
const isSourceObject = sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && !(sourceValue instanceof Date) && !(sourceValue instanceof RegExp);
|
7330
|
-
const isTargetObject = targetValue !== null && targetValue !== void 0 && typeof targetValue === "object" && !Array.isArray(targetValue) && !(targetValue instanceof Date) && !(targetValue instanceof RegExp);
|
7331
|
-
if (isSourceObject && isTargetObject) {
|
7332
|
-
result[key] = mergeObjects(
|
7333
|
-
targetValue,
|
7334
|
-
sourceValue
|
7335
|
-
);
|
7336
|
-
} else {
|
7337
|
-
result[key] = sourceValue;
|
7338
|
-
}
|
7339
|
-
}
|
7340
|
-
}
|
7341
|
-
return result;
|
7342
|
-
}
|
7343
|
-
|
7344
6939
|
// core/middleware/default-settings-middleware.ts
|
7345
6940
|
function defaultSettingsMiddleware({
|
7346
6941
|
settings
|
@@ -7348,33 +6943,7 @@ function defaultSettingsMiddleware({
|
|
7348
6943
|
return {
|
7349
6944
|
middlewareVersion: "v2",
|
7350
6945
|
transformParams: async ({ params }) => {
|
7351
|
-
|
7352
|
-
return {
|
7353
|
-
...settings,
|
7354
|
-
...params,
|
7355
|
-
// map all values that are null to undefined
|
7356
|
-
maxOutputTokens: settings.maxOutputTokens !== null ? (_a17 = params.maxOutputTokens) != null ? _a17 : settings.maxOutputTokens : void 0,
|
7357
|
-
temperature: settings.temperature !== null ? (
|
7358
|
-
// temperature: special case 0 or null
|
7359
|
-
params.temperature === 0 || params.temperature == null ? (_b = settings.temperature) != null ? _b : params.temperature : params.temperature
|
7360
|
-
) : void 0,
|
7361
|
-
stopSequences: settings.stopSequences !== null ? (_c = params.stopSequences) != null ? _c : settings.stopSequences : void 0,
|
7362
|
-
topP: settings.topP !== null ? (_d = params.topP) != null ? _d : settings.topP : void 0,
|
7363
|
-
topK: settings.topK !== null ? (_e = params.topK) != null ? _e : settings.topK : void 0,
|
7364
|
-
presencePenalty: settings.presencePenalty !== null ? (_f = params.presencePenalty) != null ? _f : settings.presencePenalty : void 0,
|
7365
|
-
frequencyPenalty: settings.frequencyPenalty !== null ? (_g = params.frequencyPenalty) != null ? _g : settings.frequencyPenalty : void 0,
|
7366
|
-
responseFormat: settings.responseFormat !== null ? (_h = params.responseFormat) != null ? _h : settings.responseFormat : void 0,
|
7367
|
-
seed: settings.seed !== null ? (_i = params.seed) != null ? _i : settings.seed : void 0,
|
7368
|
-
tools: settings.tools !== null ? (_j = params.tools) != null ? _j : settings.tools : void 0,
|
7369
|
-
toolChoice: settings.toolChoice !== null ? (_k = params.toolChoice) != null ? _k : settings.toolChoice : void 0,
|
7370
|
-
// headers: deep merge
|
7371
|
-
headers: mergeObjects(settings.headers, params.headers),
|
7372
|
-
// provider options: deep merge
|
7373
|
-
providerOptions: mergeObjects(
|
7374
|
-
settings.providerOptions,
|
7375
|
-
params.providerOptions
|
7376
|
-
)
|
7377
|
-
};
|
6946
|
+
return mergeObjects(settings, params);
|
7378
6947
|
}
|
7379
6948
|
};
|
7380
6949
|
}
|
@@ -7636,7 +7205,7 @@ function customProvider({
|
|
7636
7205
|
var experimental_customProvider = customProvider;
|
7637
7206
|
|
7638
7207
|
// core/registry/no-such-provider-error.ts
|
7639
|
-
import { AISDKError as
|
7208
|
+
import { AISDKError as AISDKError19, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
|
7640
7209
|
var name16 = "AI_NoSuchProviderError";
|
7641
7210
|
var marker16 = `vercel.ai.error.${name16}`;
|
7642
7211
|
var symbol16 = Symbol.for(marker16);
|
@@ -7655,7 +7224,7 @@ var NoSuchProviderError = class extends NoSuchModelError3 {
|
|
7655
7224
|
this.availableProviders = availableProviders;
|
7656
7225
|
}
|
7657
7226
|
static isInstance(error) {
|
7658
|
-
return
|
7227
|
+
return AISDKError19.hasMarker(error, marker16);
|
7659
7228
|
}
|
7660
7229
|
};
|
7661
7230
|
_a16 = symbol16;
|
@@ -7751,7 +7320,7 @@ function tool(tool2) {
|
|
7751
7320
|
}
|
7752
7321
|
|
7753
7322
|
// core/tool/mcp/mcp-sse-transport.ts
|
7754
|
-
import { createEventSourceParserStream
|
7323
|
+
import { createEventSourceParserStream } from "@ai-sdk/provider-utils";
|
7755
7324
|
|
7756
7325
|
// core/tool/mcp/json-rpc-message.ts
|
7757
7326
|
import { z as z10 } from "zod";
|
@@ -7922,7 +7491,7 @@ var SseMCPTransport = class {
|
|
7922
7491
|
(_b = this.onerror) == null ? void 0 : _b.call(this, error);
|
7923
7492
|
return reject(error);
|
7924
7493
|
}
|
7925
|
-
const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
|
7494
|
+
const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream());
|
7926
7495
|
const reader = stream.getReader();
|
7927
7496
|
const processEvents = async () => {
|
7928
7497
|
var _a18, _b2, _c2;
|
@@ -8310,8 +7879,8 @@ var MCPClient = class {
|
|
8310
7879
|
};
|
8311
7880
|
|
8312
7881
|
// src/error/no-transcript-generated-error.ts
|
8313
|
-
import { AISDKError as
|
8314
|
-
var NoTranscriptGeneratedError = class extends
|
7882
|
+
import { AISDKError as AISDKError20 } from "@ai-sdk/provider";
|
7883
|
+
var NoTranscriptGeneratedError = class extends AISDKError20 {
|
8315
7884
|
constructor(options) {
|
8316
7885
|
super({
|
8317
7886
|
name: "AI_NoTranscriptGeneratedError",
|
@@ -8403,7 +7972,6 @@ export {
|
|
8403
7972
|
TypeValidationError,
|
8404
7973
|
UnsupportedFunctionalityError,
|
8405
7974
|
appendClientMessage,
|
8406
|
-
appendResponseMessages,
|
8407
7975
|
asSchema5 as asSchema,
|
8408
7976
|
assistantModelMessageSchema,
|
8409
7977
|
callChatApi,
|
@@ -8417,11 +7985,11 @@ export {
|
|
8417
7985
|
coreToolMessageSchema,
|
8418
7986
|
coreUserMessageSchema,
|
8419
7987
|
cosineSimilarity,
|
8420
|
-
createDataStream,
|
8421
|
-
createDataStreamResponse,
|
8422
7988
|
createIdGenerator5 as createIdGenerator,
|
8423
7989
|
createProviderRegistry,
|
8424
7990
|
createTextStreamResponse,
|
7991
|
+
createUIMessageStream,
|
7992
|
+
createUIMessageStreamResponse,
|
8425
7993
|
customProvider,
|
8426
7994
|
defaultSettingsMiddleware,
|
8427
7995
|
embed,
|
@@ -8444,9 +8012,8 @@ export {
|
|
8444
8012
|
jsonSchema2 as jsonSchema,
|
8445
8013
|
modelMessageSchema,
|
8446
8014
|
parsePartialJson,
|
8447
|
-
pipeDataStreamToResponse,
|
8448
8015
|
pipeTextStreamToResponse,
|
8449
|
-
|
8016
|
+
pipeUIMessageStreamToResponse,
|
8450
8017
|
processTextStream,
|
8451
8018
|
shouldResubmitMessages,
|
8452
8019
|
simulateReadableStream,
|