ai 0.0.0-85f9a635-20240518005312 → 0.0.0-9477ebb9-20250403064906
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 +3521 -0
- package/README.md +112 -22
- package/dist/index.d.mts +3697 -1642
- package/dist/index.d.ts +3697 -1642
- package/dist/index.js +7201 -2942
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7249 -2963
- package/dist/index.mjs.map +1 -1
- package/mcp-stdio/create-child-process.test.ts +92 -0
- package/mcp-stdio/create-child-process.ts +21 -0
- package/mcp-stdio/dist/index.d.mts +169 -0
- package/mcp-stdio/dist/index.d.ts +169 -0
- package/mcp-stdio/dist/index.js +352 -0
- package/mcp-stdio/dist/index.js.map +1 -0
- package/mcp-stdio/dist/index.mjs +337 -0
- package/mcp-stdio/dist/index.mjs.map +1 -0
- package/mcp-stdio/get-environment.ts +43 -0
- package/mcp-stdio/index.ts +4 -0
- package/mcp-stdio/mcp-stdio-transport.test.ts +262 -0
- package/mcp-stdio/mcp-stdio-transport.ts +157 -0
- package/package.json +46 -103
- package/react/dist/index.d.mts +10 -557
- package/react/dist/index.d.ts +10 -574
- package/react/dist/index.js +6 -1397
- package/react/dist/index.js.map +1 -1
- package/react/dist/index.mjs +10 -1384
- package/react/dist/index.mjs.map +1 -1
- package/rsc/dist/index.d.ts +432 -199
- package/rsc/dist/rsc-server.d.mts +431 -199
- package/rsc/dist/rsc-server.mjs +1599 -1357
- package/rsc/dist/rsc-server.mjs.map +1 -1
- package/rsc/dist/rsc-shared.d.mts +30 -23
- package/rsc/dist/rsc-shared.mjs +70 -108
- package/rsc/dist/rsc-shared.mjs.map +1 -1
- package/test/dist/index.d.mts +65 -0
- package/test/dist/index.d.ts +65 -0
- package/test/dist/index.js +121 -0
- package/test/dist/index.js.map +1 -0
- package/test/dist/index.mjs +94 -0
- package/test/dist/index.mjs.map +1 -0
- package/prompts/dist/index.d.mts +0 -324
- package/prompts/dist/index.d.ts +0 -324
- package/prompts/dist/index.js +0 -178
- package/prompts/dist/index.js.map +0 -1
- package/prompts/dist/index.mjs +0 -146
- package/prompts/dist/index.mjs.map +0 -1
- package/react/dist/index.server.d.mts +0 -17
- package/react/dist/index.server.d.ts +0 -17
- package/react/dist/index.server.js +0 -50
- package/react/dist/index.server.js.map +0 -1
- package/react/dist/index.server.mjs +0 -23
- package/react/dist/index.server.mjs.map +0 -1
- package/solid/dist/index.d.mts +0 -408
- package/solid/dist/index.d.ts +0 -408
- package/solid/dist/index.js +0 -1072
- package/solid/dist/index.js.map +0 -1
- package/solid/dist/index.mjs +0 -1044
- package/solid/dist/index.mjs.map +0 -1
- package/svelte/dist/index.d.mts +0 -484
- package/svelte/dist/index.d.ts +0 -484
- package/svelte/dist/index.js +0 -1778
- package/svelte/dist/index.js.map +0 -1
- package/svelte/dist/index.mjs +0 -1749
- package/svelte/dist/index.mjs.map +0 -1
- package/vue/dist/index.d.mts +0 -402
- package/vue/dist/index.d.ts +0 -402
- package/vue/dist/index.js +0 -1072
- package/vue/dist/index.js.map +0 -1
- package/vue/dist/index.mjs +0 -1034
- package/vue/dist/index.mjs.map +0 -1
package/rsc/dist/rsc-server.mjs
CHANGED
@@ -1,12 +1,11 @@
|
|
1
1
|
// rsc/ai-state.tsx
|
2
|
-
import { AsyncLocalStorage } from "async_hooks";
|
3
2
|
import * as jsondiffpatch from "jsondiffpatch";
|
3
|
+
import { AsyncLocalStorage } from "async_hooks";
|
4
4
|
|
5
|
-
//
|
6
|
-
import { Suspense } from "react";
|
7
|
-
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
5
|
+
// util/create-resolvable-promise.ts
|
8
6
|
function createResolvablePromise() {
|
9
|
-
let resolve
|
7
|
+
let resolve;
|
8
|
+
let reject;
|
10
9
|
const promise = new Promise((res, rej) => {
|
11
10
|
resolve = res;
|
12
11
|
reject = rej;
|
@@ -17,43 +16,9 @@ function createResolvablePromise() {
|
|
17
16
|
reject
|
18
17
|
};
|
19
18
|
}
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
// current
|
24
|
-
n
|
25
|
-
// next
|
26
|
-
}) => {
|
27
|
-
const chunk = await n;
|
28
|
-
if (chunk.done) {
|
29
|
-
return chunk.value;
|
30
|
-
}
|
31
|
-
if (chunk.append) {
|
32
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
33
|
-
c,
|
34
|
-
/* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) })
|
35
|
-
] });
|
36
|
-
}
|
37
|
-
return /* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) });
|
38
|
-
}
|
39
|
-
][0];
|
40
|
-
function createSuspensedChunk(initialValue) {
|
41
|
-
const { promise, resolve, reject } = createResolvablePromise();
|
42
|
-
return {
|
43
|
-
row: /* @__PURE__ */ jsx(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx(R, { c: initialValue, n: promise }) }),
|
44
|
-
resolve,
|
45
|
-
reject
|
46
|
-
};
|
47
|
-
}
|
48
|
-
var isFunction = (x) => typeof x === "function";
|
49
|
-
var consumeStream = async (stream) => {
|
50
|
-
const reader = stream.getReader();
|
51
|
-
while (true) {
|
52
|
-
const { done } = await reader.read();
|
53
|
-
if (done)
|
54
|
-
break;
|
55
|
-
}
|
56
|
-
};
|
19
|
+
|
20
|
+
// util/is-function.ts
|
21
|
+
var isFunction = (value) => typeof value === "function";
|
57
22
|
|
58
23
|
// rsc/ai-state.tsx
|
59
24
|
var asyncAIStateStorage = new AsyncLocalStorage();
|
@@ -67,7 +32,8 @@ function getAIStateStoreOrThrow(message) {
|
|
67
32
|
function withAIState({ state, options }, fn) {
|
68
33
|
return asyncAIStateStorage.run(
|
69
34
|
{
|
70
|
-
currentState: state,
|
35
|
+
currentState: JSON.parse(JSON.stringify(state)),
|
36
|
+
// deep clone object
|
71
37
|
originalState: state,
|
72
38
|
sealed: false,
|
73
39
|
options
|
@@ -115,7 +81,7 @@ function getMutableAIState(...args) {
|
|
115
81
|
store.mutationDeltaResolve = resolve;
|
116
82
|
}
|
117
83
|
function doUpdate(newState, done) {
|
118
|
-
var
|
84
|
+
var _a9, _b;
|
119
85
|
if (args.length > 0) {
|
120
86
|
if (typeof store.currentState !== "object") {
|
121
87
|
const key = args[0];
|
@@ -139,7 +105,7 @@ function getMutableAIState(...args) {
|
|
139
105
|
store.currentState = newState;
|
140
106
|
}
|
141
107
|
}
|
142
|
-
(_b = (
|
108
|
+
(_b = (_a9 = store.options).onSetAIState) == null ? void 0 : _b.call(_a9, {
|
143
109
|
key: args.length > 0 ? args[0] : void 0,
|
144
110
|
state: store.currentState,
|
145
111
|
done
|
@@ -174,93 +140,265 @@ function getMutableAIState(...args) {
|
|
174
140
|
return mutableState;
|
175
141
|
}
|
176
142
|
|
177
|
-
// rsc/
|
178
|
-
import
|
143
|
+
// rsc/provider.tsx
|
144
|
+
import * as React from "react";
|
145
|
+
import { InternalAIProvider } from "./rsc-shared.mjs";
|
146
|
+
import { jsx } from "react/jsx-runtime";
|
147
|
+
async function innerAction({
|
148
|
+
action,
|
149
|
+
options
|
150
|
+
}, state, ...args) {
|
151
|
+
"use server";
|
152
|
+
return await withAIState(
|
153
|
+
{
|
154
|
+
state,
|
155
|
+
options
|
156
|
+
},
|
157
|
+
async () => {
|
158
|
+
const result = await action(...args);
|
159
|
+
sealMutableAIState();
|
160
|
+
return [getAIStateDeltaPromise(), result];
|
161
|
+
}
|
162
|
+
);
|
163
|
+
}
|
164
|
+
function wrapAction(action, options) {
|
165
|
+
return innerAction.bind(null, { action, options });
|
166
|
+
}
|
167
|
+
function createAI({
|
168
|
+
actions,
|
169
|
+
initialAIState,
|
170
|
+
initialUIState,
|
171
|
+
onSetAIState,
|
172
|
+
onGetUIState
|
173
|
+
}) {
|
174
|
+
const wrappedActions = {};
|
175
|
+
for (const name9 in actions) {
|
176
|
+
wrappedActions[name9] = wrapAction(actions[name9], {
|
177
|
+
onSetAIState
|
178
|
+
});
|
179
|
+
}
|
180
|
+
const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
|
181
|
+
const AI = async (props) => {
|
182
|
+
var _a9, _b;
|
183
|
+
if ("useState" in React) {
|
184
|
+
throw new Error(
|
185
|
+
"This component can only be used inside Server Components."
|
186
|
+
);
|
187
|
+
}
|
188
|
+
let uiState = (_a9 = props.initialUIState) != null ? _a9 : initialUIState;
|
189
|
+
let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
|
190
|
+
let aiStateDelta = void 0;
|
191
|
+
if (wrappedSyncUIState) {
|
192
|
+
const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
|
193
|
+
if (newUIState !== void 0) {
|
194
|
+
aiStateDelta = newAIStateDelta;
|
195
|
+
uiState = newUIState;
|
196
|
+
}
|
197
|
+
}
|
198
|
+
return /* @__PURE__ */ jsx(
|
199
|
+
InternalAIProvider,
|
200
|
+
{
|
201
|
+
wrappedActions,
|
202
|
+
wrappedSyncUIState,
|
203
|
+
initialUIState: uiState,
|
204
|
+
initialAIState: aiState,
|
205
|
+
initialAIStatePatch: aiStateDelta,
|
206
|
+
children: props.children
|
207
|
+
}
|
208
|
+
);
|
209
|
+
};
|
210
|
+
return AI;
|
211
|
+
}
|
179
212
|
|
180
|
-
//
|
181
|
-
import {
|
182
|
-
import { getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
|
213
|
+
// rsc/stream-ui/stream-ui.tsx
|
214
|
+
import { safeParseJSON } from "@ai-sdk/provider-utils";
|
183
215
|
|
184
|
-
//
|
185
|
-
|
186
|
-
|
187
|
-
}
|
216
|
+
// util/download-error.ts
|
217
|
+
import { AISDKError } from "@ai-sdk/provider";
|
218
|
+
var name = "AI_DownloadError";
|
219
|
+
var marker = `vercel.ai.error.${name}`;
|
220
|
+
var symbol = Symbol.for(marker);
|
221
|
+
var _a;
|
222
|
+
var DownloadError = class extends AISDKError {
|
223
|
+
constructor({
|
224
|
+
url,
|
225
|
+
statusCode,
|
226
|
+
statusText,
|
227
|
+
cause,
|
228
|
+
message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
|
229
|
+
}) {
|
230
|
+
super({ name, message, cause });
|
231
|
+
this[_a] = true;
|
232
|
+
this.url = url;
|
233
|
+
this.statusCode = statusCode;
|
234
|
+
this.statusText = statusText;
|
235
|
+
}
|
236
|
+
static isInstance(error) {
|
237
|
+
return AISDKError.hasMarker(error, marker);
|
238
|
+
}
|
239
|
+
};
|
240
|
+
_a = symbol;
|
188
241
|
|
189
|
-
//
|
190
|
-
|
191
|
-
|
192
|
-
|
193
|
-
backoffFactor = 2
|
194
|
-
} = {}) => async (f) => _retryWithExponentialBackoff(f, {
|
195
|
-
maxRetries,
|
196
|
-
delayInMs: initialDelayInMs,
|
197
|
-
backoffFactor
|
198
|
-
});
|
199
|
-
async function _retryWithExponentialBackoff(f, {
|
200
|
-
maxRetries,
|
201
|
-
delayInMs,
|
202
|
-
backoffFactor
|
203
|
-
}, errors = []) {
|
242
|
+
// util/download.ts
|
243
|
+
async function download({ url }) {
|
244
|
+
var _a9;
|
245
|
+
const urlText = url.toString();
|
204
246
|
try {
|
205
|
-
|
206
|
-
|
207
|
-
|
208
|
-
|
209
|
-
|
210
|
-
|
211
|
-
throw error;
|
212
|
-
}
|
213
|
-
const errorMessage = getErrorMessage(error);
|
214
|
-
const newErrors = [...errors, error];
|
215
|
-
const tryNumber = newErrors.length;
|
216
|
-
if (tryNumber > maxRetries) {
|
217
|
-
throw new RetryError({
|
218
|
-
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
|
219
|
-
reason: "maxRetriesExceeded",
|
220
|
-
errors: newErrors
|
247
|
+
const response = await fetch(urlText);
|
248
|
+
if (!response.ok) {
|
249
|
+
throw new DownloadError({
|
250
|
+
url: urlText,
|
251
|
+
statusCode: response.status,
|
252
|
+
statusText: response.statusText
|
221
253
|
});
|
222
254
|
}
|
223
|
-
|
224
|
-
await
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
|
229
|
-
);
|
230
|
-
}
|
231
|
-
if (tryNumber === 1) {
|
255
|
+
return {
|
256
|
+
data: new Uint8Array(await response.arrayBuffer()),
|
257
|
+
mimeType: (_a9 = response.headers.get("content-type")) != null ? _a9 : void 0
|
258
|
+
};
|
259
|
+
} catch (error) {
|
260
|
+
if (DownloadError.isInstance(error)) {
|
232
261
|
throw error;
|
233
262
|
}
|
234
|
-
throw new
|
235
|
-
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
|
236
|
-
reason: "errorNotRetryable",
|
237
|
-
errors: newErrors
|
238
|
-
});
|
263
|
+
throw new DownloadError({ url: urlText, cause: error });
|
239
264
|
}
|
240
265
|
}
|
241
266
|
|
242
267
|
// core/util/detect-image-mimetype.ts
|
243
268
|
var mimeTypeSignatures = [
|
244
|
-
{
|
245
|
-
|
246
|
-
|
247
|
-
|
269
|
+
{
|
270
|
+
mimeType: "image/gif",
|
271
|
+
bytesPrefix: [71, 73, 70],
|
272
|
+
base64Prefix: "R0lG"
|
273
|
+
},
|
274
|
+
{
|
275
|
+
mimeType: "image/png",
|
276
|
+
bytesPrefix: [137, 80, 78, 71],
|
277
|
+
base64Prefix: "iVBORw"
|
278
|
+
},
|
279
|
+
{
|
280
|
+
mimeType: "image/jpeg",
|
281
|
+
bytesPrefix: [255, 216],
|
282
|
+
base64Prefix: "/9j/"
|
283
|
+
},
|
284
|
+
{
|
285
|
+
mimeType: "image/webp",
|
286
|
+
bytesPrefix: [82, 73, 70, 70],
|
287
|
+
base64Prefix: "UklGRg"
|
288
|
+
},
|
289
|
+
{
|
290
|
+
mimeType: "image/bmp",
|
291
|
+
bytesPrefix: [66, 77],
|
292
|
+
base64Prefix: "Qk"
|
293
|
+
},
|
294
|
+
{
|
295
|
+
mimeType: "image/tiff",
|
296
|
+
bytesPrefix: [73, 73, 42, 0],
|
297
|
+
base64Prefix: "SUkqAA"
|
298
|
+
},
|
299
|
+
{
|
300
|
+
mimeType: "image/tiff",
|
301
|
+
bytesPrefix: [77, 77, 0, 42],
|
302
|
+
base64Prefix: "TU0AKg"
|
303
|
+
},
|
304
|
+
{
|
305
|
+
mimeType: "image/avif",
|
306
|
+
bytesPrefix: [
|
307
|
+
0,
|
308
|
+
0,
|
309
|
+
0,
|
310
|
+
32,
|
311
|
+
102,
|
312
|
+
116,
|
313
|
+
121,
|
314
|
+
112,
|
315
|
+
97,
|
316
|
+
118,
|
317
|
+
105,
|
318
|
+
102
|
319
|
+
],
|
320
|
+
base64Prefix: "AAAAIGZ0eXBhdmlm"
|
321
|
+
},
|
322
|
+
{
|
323
|
+
mimeType: "image/heic",
|
324
|
+
bytesPrefix: [
|
325
|
+
0,
|
326
|
+
0,
|
327
|
+
0,
|
328
|
+
32,
|
329
|
+
102,
|
330
|
+
116,
|
331
|
+
121,
|
332
|
+
112,
|
333
|
+
104,
|
334
|
+
101,
|
335
|
+
105,
|
336
|
+
99
|
337
|
+
],
|
338
|
+
base64Prefix: "AAAAIGZ0eXBoZWlj"
|
339
|
+
}
|
248
340
|
];
|
249
341
|
function detectImageMimeType(image) {
|
250
|
-
for (const
|
251
|
-
if (image.length >=
|
252
|
-
return mimeType;
|
342
|
+
for (const signature of mimeTypeSignatures) {
|
343
|
+
if (typeof image === "string" ? image.startsWith(signature.base64Prefix) : image.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => image[index] === byte)) {
|
344
|
+
return signature.mimeType;
|
253
345
|
}
|
254
346
|
}
|
255
347
|
return void 0;
|
256
348
|
}
|
257
349
|
|
258
350
|
// core/prompt/data-content.ts
|
259
|
-
import { InvalidDataContentError } from "@ai-sdk/provider";
|
260
351
|
import {
|
261
352
|
convertBase64ToUint8Array,
|
262
353
|
convertUint8ArrayToBase64
|
263
354
|
} from "@ai-sdk/provider-utils";
|
355
|
+
|
356
|
+
// core/prompt/invalid-data-content-error.ts
|
357
|
+
import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
|
358
|
+
var name2 = "AI_InvalidDataContentError";
|
359
|
+
var marker2 = `vercel.ai.error.${name2}`;
|
360
|
+
var symbol2 = Symbol.for(marker2);
|
361
|
+
var _a2;
|
362
|
+
var InvalidDataContentError = class extends AISDKError2 {
|
363
|
+
constructor({
|
364
|
+
content,
|
365
|
+
cause,
|
366
|
+
message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
|
367
|
+
}) {
|
368
|
+
super({ name: name2, message, cause });
|
369
|
+
this[_a2] = true;
|
370
|
+
this.content = content;
|
371
|
+
}
|
372
|
+
static isInstance(error) {
|
373
|
+
return AISDKError2.hasMarker(error, marker2);
|
374
|
+
}
|
375
|
+
};
|
376
|
+
_a2 = symbol2;
|
377
|
+
|
378
|
+
// core/prompt/data-content.ts
|
379
|
+
import { z } from "zod";
|
380
|
+
var dataContentSchema = z.union([
|
381
|
+
z.string(),
|
382
|
+
z.instanceof(Uint8Array),
|
383
|
+
z.instanceof(ArrayBuffer),
|
384
|
+
z.custom(
|
385
|
+
// Buffer might not be available in some environments such as CloudFlare:
|
386
|
+
(value) => {
|
387
|
+
var _a9, _b;
|
388
|
+
return (_b = (_a9 = globalThis.Buffer) == null ? void 0 : _a9.isBuffer(value)) != null ? _b : false;
|
389
|
+
},
|
390
|
+
{ message: "Must be a Buffer" }
|
391
|
+
)
|
392
|
+
]);
|
393
|
+
function convertDataContentToBase64String(content) {
|
394
|
+
if (typeof content === "string") {
|
395
|
+
return content;
|
396
|
+
}
|
397
|
+
if (content instanceof ArrayBuffer) {
|
398
|
+
return convertUint8ArrayToBase64(new Uint8Array(content));
|
399
|
+
}
|
400
|
+
return convertUint8ArrayToBase64(content);
|
401
|
+
}
|
264
402
|
function convertDataContentToUint8Array(content) {
|
265
403
|
if (content instanceof Uint8Array) {
|
266
404
|
return content;
|
@@ -270,7 +408,7 @@ function convertDataContentToUint8Array(content) {
|
|
270
408
|
return convertBase64ToUint8Array(content);
|
271
409
|
} catch (error) {
|
272
410
|
throw new InvalidDataContentError({
|
273
|
-
message: "Invalid data content. Content string is not a base64-encoded
|
411
|
+
message: "Invalid data content. Content string is not a base64-encoded media.",
|
274
412
|
content,
|
275
413
|
cause: error
|
276
414
|
});
|
@@ -281,130 +419,319 @@ function convertDataContentToUint8Array(content) {
|
|
281
419
|
}
|
282
420
|
throw new InvalidDataContentError({ content });
|
283
421
|
}
|
422
|
+
function convertUint8ArrayToText(uint8Array) {
|
423
|
+
try {
|
424
|
+
return new TextDecoder().decode(uint8Array);
|
425
|
+
} catch (error) {
|
426
|
+
throw new Error("Error decoding Uint8Array to text");
|
427
|
+
}
|
428
|
+
}
|
429
|
+
|
430
|
+
// core/prompt/invalid-message-role-error.ts
|
431
|
+
import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
|
432
|
+
var name3 = "AI_InvalidMessageRoleError";
|
433
|
+
var marker3 = `vercel.ai.error.${name3}`;
|
434
|
+
var symbol3 = Symbol.for(marker3);
|
435
|
+
var _a3;
|
436
|
+
var InvalidMessageRoleError = class extends AISDKError3 {
|
437
|
+
constructor({
|
438
|
+
role,
|
439
|
+
message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
|
440
|
+
}) {
|
441
|
+
super({ name: name3, message });
|
442
|
+
this[_a3] = true;
|
443
|
+
this.role = role;
|
444
|
+
}
|
445
|
+
static isInstance(error) {
|
446
|
+
return AISDKError3.hasMarker(error, marker3);
|
447
|
+
}
|
448
|
+
};
|
449
|
+
_a3 = symbol3;
|
450
|
+
|
451
|
+
// core/prompt/split-data-url.ts
|
452
|
+
function splitDataUrl(dataUrl) {
|
453
|
+
try {
|
454
|
+
const [header, base64Content] = dataUrl.split(",");
|
455
|
+
return {
|
456
|
+
mimeType: header.split(";")[0].split(":")[1],
|
457
|
+
base64Content
|
458
|
+
};
|
459
|
+
} catch (error) {
|
460
|
+
return {
|
461
|
+
mimeType: void 0,
|
462
|
+
base64Content: void 0
|
463
|
+
};
|
464
|
+
}
|
465
|
+
}
|
284
466
|
|
285
467
|
// core/prompt/convert-to-language-model-prompt.ts
|
286
|
-
function convertToLanguageModelPrompt(
|
287
|
-
|
288
|
-
|
289
|
-
|
290
|
-
|
291
|
-
|
292
|
-
|
293
|
-
|
468
|
+
async function convertToLanguageModelPrompt({
|
469
|
+
prompt,
|
470
|
+
modelSupportsImageUrls = true,
|
471
|
+
modelSupportsUrl = () => false,
|
472
|
+
downloadImplementation = download
|
473
|
+
}) {
|
474
|
+
const downloadedAssets = await downloadAssets(
|
475
|
+
prompt.messages,
|
476
|
+
downloadImplementation,
|
477
|
+
modelSupportsImageUrls,
|
478
|
+
modelSupportsUrl
|
479
|
+
);
|
480
|
+
return [
|
481
|
+
...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
|
482
|
+
...prompt.messages.map(
|
483
|
+
(message) => convertToLanguageModelMessage(message, downloadedAssets)
|
484
|
+
)
|
485
|
+
];
|
486
|
+
}
|
487
|
+
function convertToLanguageModelMessage(message, downloadedAssets) {
|
488
|
+
var _a9, _b, _c, _d, _e, _f;
|
489
|
+
const role = message.role;
|
490
|
+
switch (role) {
|
491
|
+
case "system": {
|
492
|
+
return {
|
493
|
+
role: "system",
|
494
|
+
content: message.content,
|
495
|
+
providerMetadata: (_a9 = message.providerOptions) != null ? _a9 : message.experimental_providerMetadata
|
496
|
+
};
|
497
|
+
}
|
498
|
+
case "user": {
|
499
|
+
if (typeof message.content === "string") {
|
500
|
+
return {
|
501
|
+
role: "user",
|
502
|
+
content: [{ type: "text", text: message.content }],
|
503
|
+
providerMetadata: (_b = message.providerOptions) != null ? _b : message.experimental_providerMetadata
|
504
|
+
};
|
505
|
+
}
|
506
|
+
return {
|
294
507
|
role: "user",
|
295
|
-
content:
|
296
|
-
|
297
|
-
|
508
|
+
content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
|
509
|
+
providerMetadata: (_c = message.providerOptions) != null ? _c : message.experimental_providerMetadata
|
510
|
+
};
|
298
511
|
}
|
299
|
-
case "
|
300
|
-
|
301
|
-
|
302
|
-
|
303
|
-
|
304
|
-
|
512
|
+
case "assistant": {
|
513
|
+
if (typeof message.content === "string") {
|
514
|
+
return {
|
515
|
+
role: "assistant",
|
516
|
+
content: [{ type: "text", text: message.content }],
|
517
|
+
providerMetadata: (_d = message.providerOptions) != null ? _d : message.experimental_providerMetadata
|
518
|
+
};
|
519
|
+
}
|
520
|
+
return {
|
521
|
+
role: "assistant",
|
522
|
+
content: message.content.filter(
|
523
|
+
// remove empty text parts:
|
524
|
+
(part) => part.type !== "text" || part.text !== ""
|
525
|
+
).map((part) => {
|
526
|
+
var _a10;
|
527
|
+
const providerOptions = (_a10 = part.providerOptions) != null ? _a10 : part.experimental_providerMetadata;
|
528
|
+
switch (part.type) {
|
529
|
+
case "file": {
|
530
|
+
return {
|
531
|
+
type: "file",
|
532
|
+
data: part.data instanceof URL ? part.data : convertDataContentToBase64String(part.data),
|
533
|
+
filename: part.filename,
|
534
|
+
mimeType: part.mimeType,
|
535
|
+
providerMetadata: providerOptions
|
536
|
+
};
|
305
537
|
}
|
306
|
-
case "
|
307
|
-
if (typeof message.content === "string") {
|
308
|
-
return {
|
309
|
-
role: "user",
|
310
|
-
content: [{ type: "text", text: message.content }]
|
311
|
-
};
|
312
|
-
}
|
538
|
+
case "reasoning": {
|
313
539
|
return {
|
314
|
-
|
315
|
-
|
316
|
-
|
317
|
-
|
318
|
-
switch (part.type) {
|
319
|
-
case "text": {
|
320
|
-
return part;
|
321
|
-
}
|
322
|
-
case "image": {
|
323
|
-
if (part.image instanceof URL) {
|
324
|
-
return {
|
325
|
-
type: "image",
|
326
|
-
image: part.image,
|
327
|
-
mimeType: part.mimeType
|
328
|
-
};
|
329
|
-
}
|
330
|
-
const imageUint8 = convertDataContentToUint8Array(
|
331
|
-
part.image
|
332
|
-
);
|
333
|
-
return {
|
334
|
-
type: "image",
|
335
|
-
image: imageUint8,
|
336
|
-
mimeType: (_a = part.mimeType) != null ? _a : detectImageMimeType(imageUint8)
|
337
|
-
};
|
338
|
-
}
|
339
|
-
}
|
340
|
-
}
|
341
|
-
)
|
540
|
+
type: "reasoning",
|
541
|
+
text: part.text,
|
542
|
+
signature: part.signature,
|
543
|
+
providerMetadata: providerOptions
|
342
544
|
};
|
343
545
|
}
|
344
|
-
case "
|
345
|
-
|
346
|
-
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
}
|
351
|
-
return { role: "assistant", content: message.content };
|
546
|
+
case "redacted-reasoning": {
|
547
|
+
return {
|
548
|
+
type: "redacted-reasoning",
|
549
|
+
data: part.data,
|
550
|
+
providerMetadata: providerOptions
|
551
|
+
};
|
352
552
|
}
|
353
|
-
case "
|
354
|
-
return
|
553
|
+
case "text": {
|
554
|
+
return {
|
555
|
+
type: "text",
|
556
|
+
text: part.text,
|
557
|
+
providerMetadata: providerOptions
|
558
|
+
};
|
559
|
+
}
|
560
|
+
case "tool-call": {
|
561
|
+
return {
|
562
|
+
type: "tool-call",
|
563
|
+
toolCallId: part.toolCallId,
|
564
|
+
toolName: part.toolName,
|
565
|
+
args: part.args,
|
566
|
+
providerMetadata: providerOptions
|
567
|
+
};
|
355
568
|
}
|
356
569
|
}
|
357
|
-
})
|
358
|
-
|
359
|
-
|
570
|
+
}),
|
571
|
+
providerMetadata: (_e = message.providerOptions) != null ? _e : message.experimental_providerMetadata
|
572
|
+
};
|
573
|
+
}
|
574
|
+
case "tool": {
|
575
|
+
return {
|
576
|
+
role: "tool",
|
577
|
+
content: message.content.map((part) => {
|
578
|
+
var _a10;
|
579
|
+
return {
|
580
|
+
type: "tool-result",
|
581
|
+
toolCallId: part.toolCallId,
|
582
|
+
toolName: part.toolName,
|
583
|
+
result: part.result,
|
584
|
+
content: part.experimental_content,
|
585
|
+
isError: part.isError,
|
586
|
+
providerMetadata: (_a10 = part.providerOptions) != null ? _a10 : part.experimental_providerMetadata
|
587
|
+
};
|
588
|
+
}),
|
589
|
+
providerMetadata: (_f = message.providerOptions) != null ? _f : message.experimental_providerMetadata
|
590
|
+
};
|
360
591
|
}
|
361
592
|
default: {
|
362
|
-
const _exhaustiveCheck =
|
363
|
-
throw new
|
593
|
+
const _exhaustiveCheck = role;
|
594
|
+
throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
|
595
|
+
}
|
596
|
+
}
|
597
|
+
}
|
598
|
+
async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
|
599
|
+
const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
|
600
|
+
(content) => Array.isArray(content)
|
601
|
+
).flat().filter(
|
602
|
+
(part) => part.type === "image" || part.type === "file"
|
603
|
+
).filter(
|
604
|
+
(part) => !(part.type === "image" && modelSupportsImageUrls === true)
|
605
|
+
).map((part) => part.type === "image" ? part.image : part.data).map(
|
606
|
+
(part) => (
|
607
|
+
// support string urls:
|
608
|
+
typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
|
609
|
+
)
|
610
|
+
).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
|
611
|
+
const downloadedImages = await Promise.all(
|
612
|
+
urls.map(async (url) => ({
|
613
|
+
url,
|
614
|
+
data: await downloadImplementation({ url })
|
615
|
+
}))
|
616
|
+
);
|
617
|
+
return Object.fromEntries(
|
618
|
+
downloadedImages.map(({ url, data }) => [url.toString(), data])
|
619
|
+
);
|
620
|
+
}
|
621
|
+
function convertPartToLanguageModelPart(part, downloadedAssets) {
|
622
|
+
var _a9, _b, _c, _d;
|
623
|
+
if (part.type === "text") {
|
624
|
+
return {
|
625
|
+
type: "text",
|
626
|
+
text: part.text,
|
627
|
+
providerMetadata: (_a9 = part.providerOptions) != null ? _a9 : part.experimental_providerMetadata
|
628
|
+
};
|
629
|
+
}
|
630
|
+
let mimeType = part.mimeType;
|
631
|
+
let data;
|
632
|
+
let content;
|
633
|
+
let normalizedData;
|
634
|
+
const type = part.type;
|
635
|
+
switch (type) {
|
636
|
+
case "image":
|
637
|
+
data = part.image;
|
638
|
+
break;
|
639
|
+
case "file":
|
640
|
+
data = part.data;
|
641
|
+
break;
|
642
|
+
default:
|
643
|
+
throw new Error(`Unsupported part type: ${type}`);
|
644
|
+
}
|
645
|
+
try {
|
646
|
+
content = typeof data === "string" ? new URL(data) : data;
|
647
|
+
} catch (error) {
|
648
|
+
content = data;
|
649
|
+
}
|
650
|
+
if (content instanceof URL) {
|
651
|
+
if (content.protocol === "data:") {
|
652
|
+
const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(
|
653
|
+
content.toString()
|
654
|
+
);
|
655
|
+
if (dataUrlMimeType == null || base64Content == null) {
|
656
|
+
throw new Error(`Invalid data URL format in part ${type}`);
|
657
|
+
}
|
658
|
+
mimeType = dataUrlMimeType;
|
659
|
+
normalizedData = convertDataContentToUint8Array(base64Content);
|
660
|
+
} else {
|
661
|
+
const downloadedFile = downloadedAssets[content.toString()];
|
662
|
+
if (downloadedFile) {
|
663
|
+
normalizedData = downloadedFile.data;
|
664
|
+
mimeType != null ? mimeType : mimeType = downloadedFile.mimeType;
|
665
|
+
} else {
|
666
|
+
normalizedData = content;
|
667
|
+
}
|
668
|
+
}
|
669
|
+
} else {
|
670
|
+
normalizedData = convertDataContentToUint8Array(content);
|
671
|
+
}
|
672
|
+
switch (type) {
|
673
|
+
case "image": {
|
674
|
+
if (normalizedData instanceof Uint8Array) {
|
675
|
+
mimeType = (_b = detectImageMimeType(normalizedData)) != null ? _b : mimeType;
|
676
|
+
}
|
677
|
+
return {
|
678
|
+
type: "image",
|
679
|
+
image: normalizedData,
|
680
|
+
mimeType,
|
681
|
+
providerMetadata: (_c = part.providerOptions) != null ? _c : part.experimental_providerMetadata
|
682
|
+
};
|
683
|
+
}
|
684
|
+
case "file": {
|
685
|
+
if (mimeType == null) {
|
686
|
+
throw new Error(`Mime type is missing for file part`);
|
687
|
+
}
|
688
|
+
return {
|
689
|
+
type: "file",
|
690
|
+
data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
|
691
|
+
filename: part.filename,
|
692
|
+
mimeType,
|
693
|
+
providerMetadata: (_d = part.providerOptions) != null ? _d : part.experimental_providerMetadata
|
694
|
+
};
|
364
695
|
}
|
365
696
|
}
|
366
|
-
return languageModelMessages;
|
367
697
|
}
|
368
698
|
|
369
|
-
//
|
370
|
-
import {
|
371
|
-
|
372
|
-
|
373
|
-
|
374
|
-
|
375
|
-
|
699
|
+
// errors/invalid-argument-error.ts
|
700
|
+
import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
|
701
|
+
var name4 = "AI_InvalidArgumentError";
|
702
|
+
var marker4 = `vercel.ai.error.${name4}`;
|
703
|
+
var symbol4 = Symbol.for(marker4);
|
704
|
+
var _a4;
|
705
|
+
var InvalidArgumentError = class extends AISDKError4 {
|
706
|
+
constructor({
|
707
|
+
parameter,
|
708
|
+
value,
|
709
|
+
message
|
710
|
+
}) {
|
711
|
+
super({
|
712
|
+
name: name4,
|
713
|
+
message: `Invalid argument for parameter ${parameter}: ${message}`
|
376
714
|
});
|
715
|
+
this[_a4] = true;
|
716
|
+
this.parameter = parameter;
|
717
|
+
this.value = value;
|
377
718
|
}
|
378
|
-
|
379
|
-
|
380
|
-
prompt,
|
381
|
-
message: "prompt and messages cannot be defined at the same time"
|
382
|
-
});
|
719
|
+
static isInstance(error) {
|
720
|
+
return AISDKError4.hasMarker(error, marker4);
|
383
721
|
}
|
384
|
-
|
385
|
-
|
386
|
-
prompt: prompt.prompt,
|
387
|
-
messages: void 0,
|
388
|
-
system: prompt.system
|
389
|
-
} : {
|
390
|
-
type: "messages",
|
391
|
-
prompt: void 0,
|
392
|
-
messages: prompt.messages,
|
393
|
-
// only possible case bc of checks above
|
394
|
-
system: prompt.system
|
395
|
-
};
|
396
|
-
}
|
722
|
+
};
|
723
|
+
_a4 = symbol4;
|
397
724
|
|
398
725
|
// core/prompt/prepare-call-settings.ts
|
399
|
-
import { InvalidArgumentError } from "@ai-sdk/provider";
|
400
726
|
function prepareCallSettings({
|
401
727
|
maxTokens,
|
402
728
|
temperature,
|
403
729
|
topP,
|
730
|
+
topK,
|
404
731
|
presencePenalty,
|
405
732
|
frequencyPenalty,
|
406
|
-
|
407
|
-
|
733
|
+
stopSequences,
|
734
|
+
seed
|
408
735
|
}) {
|
409
736
|
if (maxTokens != null) {
|
410
737
|
if (!Number.isInteger(maxTokens)) {
|
@@ -440,7 +767,16 @@ function prepareCallSettings({
|
|
440
767
|
});
|
441
768
|
}
|
442
769
|
}
|
443
|
-
if (
|
770
|
+
if (topK != null) {
|
771
|
+
if (typeof topK !== "number") {
|
772
|
+
throw new InvalidArgumentError({
|
773
|
+
parameter: "topK",
|
774
|
+
value: topK,
|
775
|
+
message: "topK must be a number"
|
776
|
+
});
|
777
|
+
}
|
778
|
+
}
|
779
|
+
if (presencePenalty != null) {
|
444
780
|
if (typeof presencePenalty !== "number") {
|
445
781
|
throw new InvalidArgumentError({
|
446
782
|
parameter: "presencePenalty",
|
@@ -467,734 +803,878 @@ function prepareCallSettings({
|
|
467
803
|
});
|
468
804
|
}
|
469
805
|
}
|
470
|
-
if (maxRetries != null) {
|
471
|
-
if (!Number.isInteger(maxRetries)) {
|
472
|
-
throw new InvalidArgumentError({
|
473
|
-
parameter: "maxRetries",
|
474
|
-
value: maxRetries,
|
475
|
-
message: "maxRetries must be an integer"
|
476
|
-
});
|
477
|
-
}
|
478
|
-
if (maxRetries < 0) {
|
479
|
-
throw new InvalidArgumentError({
|
480
|
-
parameter: "maxRetries",
|
481
|
-
value: maxRetries,
|
482
|
-
message: "maxRetries must be >= 0"
|
483
|
-
});
|
484
|
-
}
|
485
|
-
}
|
486
806
|
return {
|
487
807
|
maxTokens,
|
808
|
+
// TODO v5 remove default 0 for temperature
|
488
809
|
temperature: temperature != null ? temperature : 0,
|
489
810
|
topP,
|
811
|
+
topK,
|
490
812
|
presencePenalty,
|
491
813
|
frequencyPenalty,
|
492
|
-
|
493
|
-
|
814
|
+
stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
|
815
|
+
seed
|
494
816
|
};
|
495
817
|
}
|
496
818
|
|
497
|
-
//
|
498
|
-
import
|
499
|
-
|
500
|
-
return zodToJsonSchema(zodSchema);
|
501
|
-
}
|
819
|
+
// util/retry-with-exponential-backoff.ts
|
820
|
+
import { APICallError } from "@ai-sdk/provider";
|
821
|
+
import { delay, getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
|
502
822
|
|
503
|
-
//
|
504
|
-
|
505
|
-
|
506
|
-
|
507
|
-
|
508
|
-
|
509
|
-
|
510
|
-
|
511
|
-
|
512
|
-
|
513
|
-
|
514
|
-
|
515
|
-
|
516
|
-
|
517
|
-
|
518
|
-
|
519
|
-
|
520
|
-
'"function_call" parts expect an object with a "function_call" property.'
|
521
|
-
);
|
522
|
-
}
|
523
|
-
return {
|
524
|
-
type: "function_call",
|
525
|
-
value
|
526
|
-
};
|
527
|
-
}
|
528
|
-
};
|
529
|
-
var dataStreamPart = {
|
530
|
-
code: "2",
|
531
|
-
name: "data",
|
532
|
-
parse: (value) => {
|
533
|
-
if (!Array.isArray(value)) {
|
534
|
-
throw new Error('"data" parts expect an array value.');
|
535
|
-
}
|
536
|
-
return { type: "data", value };
|
537
|
-
}
|
538
|
-
};
|
539
|
-
var errorStreamPart = {
|
540
|
-
code: "3",
|
541
|
-
name: "error",
|
542
|
-
parse: (value) => {
|
543
|
-
if (typeof value !== "string") {
|
544
|
-
throw new Error('"error" parts expect a string value.');
|
545
|
-
}
|
546
|
-
return { type: "error", value };
|
547
|
-
}
|
548
|
-
};
|
549
|
-
var assistantMessageStreamPart = {
|
550
|
-
code: "4",
|
551
|
-
name: "assistant_message",
|
552
|
-
parse: (value) => {
|
553
|
-
if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
|
554
|
-
(item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
|
555
|
-
)) {
|
556
|
-
throw new Error(
|
557
|
-
'"assistant_message" parts expect an object with an "id", "role", and "content" property.'
|
558
|
-
);
|
559
|
-
}
|
560
|
-
return {
|
561
|
-
type: "assistant_message",
|
562
|
-
value
|
563
|
-
};
|
823
|
+
// util/retry-error.ts
|
824
|
+
import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
|
825
|
+
var name5 = "AI_RetryError";
|
826
|
+
var marker5 = `vercel.ai.error.${name5}`;
|
827
|
+
var symbol5 = Symbol.for(marker5);
|
828
|
+
var _a5;
|
829
|
+
var RetryError = class extends AISDKError5 {
|
830
|
+
constructor({
|
831
|
+
message,
|
832
|
+
reason,
|
833
|
+
errors
|
834
|
+
}) {
|
835
|
+
super({ name: name5, message });
|
836
|
+
this[_a5] = true;
|
837
|
+
this.reason = reason;
|
838
|
+
this.errors = errors;
|
839
|
+
this.lastError = errors[errors.length - 1];
|
564
840
|
}
|
565
|
-
|
566
|
-
|
567
|
-
code: "5",
|
568
|
-
name: "assistant_control_data",
|
569
|
-
parse: (value) => {
|
570
|
-
if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
|
571
|
-
throw new Error(
|
572
|
-
'"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
|
573
|
-
);
|
574
|
-
}
|
575
|
-
return {
|
576
|
-
type: "assistant_control_data",
|
577
|
-
value: {
|
578
|
-
threadId: value.threadId,
|
579
|
-
messageId: value.messageId
|
580
|
-
}
|
581
|
-
};
|
841
|
+
static isInstance(error) {
|
842
|
+
return AISDKError5.hasMarker(error, marker5);
|
582
843
|
}
|
583
844
|
};
|
584
|
-
|
585
|
-
|
586
|
-
|
587
|
-
|
588
|
-
|
589
|
-
|
590
|
-
|
591
|
-
|
845
|
+
_a5 = symbol5;
|
846
|
+
|
847
|
+
// util/retry-with-exponential-backoff.ts
|
848
|
+
var retryWithExponentialBackoff = ({
|
849
|
+
maxRetries = 2,
|
850
|
+
initialDelayInMs = 2e3,
|
851
|
+
backoffFactor = 2
|
852
|
+
} = {}) => async (f) => _retryWithExponentialBackoff(f, {
|
853
|
+
maxRetries,
|
854
|
+
delayInMs: initialDelayInMs,
|
855
|
+
backoffFactor
|
856
|
+
});
|
857
|
+
async function _retryWithExponentialBackoff(f, {
|
858
|
+
maxRetries,
|
859
|
+
delayInMs,
|
860
|
+
backoffFactor
|
861
|
+
}, errors = []) {
|
862
|
+
try {
|
863
|
+
return await f();
|
864
|
+
} catch (error) {
|
865
|
+
if (isAbortError(error)) {
|
866
|
+
throw error;
|
592
867
|
}
|
593
|
-
|
594
|
-
|
595
|
-
value
|
596
|
-
};
|
597
|
-
}
|
598
|
-
};
|
599
|
-
var toolCallsStreamPart = {
|
600
|
-
code: "7",
|
601
|
-
name: "tool_calls",
|
602
|
-
parse: (value) => {
|
603
|
-
if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some(
|
604
|
-
(tc) => tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string"
|
605
|
-
)) {
|
606
|
-
throw new Error(
|
607
|
-
'"tool_calls" parts expect an object with a ToolCallPayload.'
|
608
|
-
);
|
868
|
+
if (maxRetries === 0) {
|
869
|
+
throw error;
|
609
870
|
}
|
610
|
-
|
611
|
-
|
612
|
-
|
613
|
-
|
614
|
-
|
615
|
-
}
|
616
|
-
|
617
|
-
|
618
|
-
|
619
|
-
parse: (value) => {
|
620
|
-
if (!Array.isArray(value)) {
|
621
|
-
throw new Error('"message_annotations" parts expect an array value.');
|
871
|
+
const errorMessage = getErrorMessage(error);
|
872
|
+
const newErrors = [...errors, error];
|
873
|
+
const tryNumber = newErrors.length;
|
874
|
+
if (tryNumber > maxRetries) {
|
875
|
+
throw new RetryError({
|
876
|
+
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
|
877
|
+
reason: "maxRetriesExceeded",
|
878
|
+
errors: newErrors
|
879
|
+
});
|
622
880
|
}
|
623
|
-
|
624
|
-
|
625
|
-
|
626
|
-
|
627
|
-
|
628
|
-
|
629
|
-
parse: (value) => {
|
630
|
-
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
|
631
|
-
throw new Error(
|
632
|
-
'"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
|
881
|
+
if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
|
882
|
+
await delay(delayInMs);
|
883
|
+
return _retryWithExponentialBackoff(
|
884
|
+
f,
|
885
|
+
{ maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
|
886
|
+
newErrors
|
633
887
|
);
|
634
888
|
}
|
635
|
-
|
636
|
-
|
637
|
-
value
|
638
|
-
};
|
639
|
-
}
|
640
|
-
};
|
641
|
-
var toolResultStreamPart = {
|
642
|
-
code: "a",
|
643
|
-
name: "tool_result",
|
644
|
-
parse: (value) => {
|
645
|
-
if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object" || !("result" in value)) {
|
646
|
-
throw new Error(
|
647
|
-
'"tool_result" parts expect an object with a "toolCallId", "toolName", "args", and "result" property.'
|
648
|
-
);
|
889
|
+
if (tryNumber === 1) {
|
890
|
+
throw error;
|
649
891
|
}
|
650
|
-
|
651
|
-
|
652
|
-
|
653
|
-
|
654
|
-
|
655
|
-
};
|
656
|
-
var streamParts = [
|
657
|
-
textStreamPart,
|
658
|
-
functionCallStreamPart,
|
659
|
-
dataStreamPart,
|
660
|
-
errorStreamPart,
|
661
|
-
assistantMessageStreamPart,
|
662
|
-
assistantControlDataStreamPart,
|
663
|
-
dataMessageStreamPart,
|
664
|
-
toolCallsStreamPart,
|
665
|
-
messageAnnotationsStreamPart,
|
666
|
-
toolCallStreamPart,
|
667
|
-
toolResultStreamPart
|
668
|
-
];
|
669
|
-
var streamPartsByCode = {
|
670
|
-
[textStreamPart.code]: textStreamPart,
|
671
|
-
[functionCallStreamPart.code]: functionCallStreamPart,
|
672
|
-
[dataStreamPart.code]: dataStreamPart,
|
673
|
-
[errorStreamPart.code]: errorStreamPart,
|
674
|
-
[assistantMessageStreamPart.code]: assistantMessageStreamPart,
|
675
|
-
[assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
|
676
|
-
[dataMessageStreamPart.code]: dataMessageStreamPart,
|
677
|
-
[toolCallsStreamPart.code]: toolCallsStreamPart,
|
678
|
-
[messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart,
|
679
|
-
[toolCallStreamPart.code]: toolCallStreamPart,
|
680
|
-
[toolResultStreamPart.code]: toolResultStreamPart
|
681
|
-
};
|
682
|
-
var StreamStringPrefixes = {
|
683
|
-
[textStreamPart.name]: textStreamPart.code,
|
684
|
-
[functionCallStreamPart.name]: functionCallStreamPart.code,
|
685
|
-
[dataStreamPart.name]: dataStreamPart.code,
|
686
|
-
[errorStreamPart.name]: errorStreamPart.code,
|
687
|
-
[assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
|
688
|
-
[assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
|
689
|
-
[dataMessageStreamPart.name]: dataMessageStreamPart.code,
|
690
|
-
[toolCallsStreamPart.name]: toolCallsStreamPart.code,
|
691
|
-
[messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code,
|
692
|
-
[toolCallStreamPart.name]: toolCallStreamPart.code,
|
693
|
-
[toolResultStreamPart.name]: toolResultStreamPart.code
|
694
|
-
};
|
695
|
-
var validCodes = streamParts.map((part) => part.code);
|
696
|
-
var parseStreamPart = (line) => {
|
697
|
-
const firstSeparatorIndex = line.indexOf(":");
|
698
|
-
if (firstSeparatorIndex === -1) {
|
699
|
-
throw new Error("Failed to parse stream string. No separator found.");
|
700
|
-
}
|
701
|
-
const prefix = line.slice(0, firstSeparatorIndex);
|
702
|
-
if (!validCodes.includes(prefix)) {
|
703
|
-
throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
|
704
|
-
}
|
705
|
-
const code = prefix;
|
706
|
-
const textValue = line.slice(firstSeparatorIndex + 1);
|
707
|
-
const jsonValue = JSON.parse(textValue);
|
708
|
-
return streamPartsByCode[code].parse(jsonValue);
|
709
|
-
};
|
710
|
-
function formatStreamPart(type, value) {
|
711
|
-
const streamPart = streamParts.find((part) => part.name === type);
|
712
|
-
if (!streamPart) {
|
713
|
-
throw new Error(`Invalid stream part type: ${type}`);
|
714
|
-
}
|
715
|
-
return `${streamPart.code}:${JSON.stringify(value)}
|
716
|
-
`;
|
717
|
-
}
|
718
|
-
|
719
|
-
// shared/utils.ts
|
720
|
-
function createChunkDecoder(complex) {
|
721
|
-
const decoder = new TextDecoder();
|
722
|
-
if (!complex) {
|
723
|
-
return function(chunk) {
|
724
|
-
if (!chunk)
|
725
|
-
return "";
|
726
|
-
return decoder.decode(chunk, { stream: true });
|
727
|
-
};
|
892
|
+
throw new RetryError({
|
893
|
+
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
|
894
|
+
reason: "errorNotRetryable",
|
895
|
+
errors: newErrors
|
896
|
+
});
|
728
897
|
}
|
729
|
-
return function(chunk) {
|
730
|
-
const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
|
731
|
-
return decoded.map(parseStreamPart).filter(Boolean);
|
732
|
-
};
|
733
898
|
}
|
734
899
|
|
735
|
-
//
|
736
|
-
|
737
|
-
|
738
|
-
}
|
739
|
-
|
740
|
-
|
741
|
-
|
742
|
-
|
743
|
-
|
744
|
-
|
745
|
-
(event) => {
|
746
|
-
if ("data" in event && event.type === "event" && event.data === "[DONE]" || // Replicate doesn't send [DONE] but does send a 'done' event
|
747
|
-
// @see https://replicate.com/docs/streaming
|
748
|
-
event.event === "done") {
|
749
|
-
controller.terminate();
|
750
|
-
return;
|
751
|
-
}
|
752
|
-
if ("data" in event) {
|
753
|
-
const parsedMessage = customParser ? customParser(event.data, {
|
754
|
-
event: event.event
|
755
|
-
}) : event.data;
|
756
|
-
if (parsedMessage)
|
757
|
-
controller.enqueue(parsedMessage);
|
758
|
-
}
|
759
|
-
}
|
760
|
-
);
|
761
|
-
},
|
762
|
-
transform(chunk) {
|
763
|
-
eventSourceParser.feed(textDecoder.decode(chunk));
|
764
|
-
}
|
765
|
-
});
|
766
|
-
}
|
767
|
-
function createCallbacksTransformer(cb) {
|
768
|
-
const textEncoder = new TextEncoder();
|
769
|
-
let aggregatedResponse = "";
|
770
|
-
const callbacks = cb || {};
|
771
|
-
return new TransformStream({
|
772
|
-
async start() {
|
773
|
-
if (callbacks.onStart)
|
774
|
-
await callbacks.onStart();
|
775
|
-
},
|
776
|
-
async transform(message, controller) {
|
777
|
-
const content = typeof message === "string" ? message : message.content;
|
778
|
-
controller.enqueue(textEncoder.encode(content));
|
779
|
-
aggregatedResponse += content;
|
780
|
-
if (callbacks.onToken)
|
781
|
-
await callbacks.onToken(content);
|
782
|
-
if (callbacks.onText && typeof message === "string") {
|
783
|
-
await callbacks.onText(message);
|
784
|
-
}
|
785
|
-
},
|
786
|
-
async flush() {
|
787
|
-
const isOpenAICallbacks = isOfTypeOpenAIStreamCallbacks(callbacks);
|
788
|
-
if (callbacks.onCompletion) {
|
789
|
-
await callbacks.onCompletion(aggregatedResponse);
|
790
|
-
}
|
791
|
-
if (callbacks.onFinal && !isOpenAICallbacks) {
|
792
|
-
await callbacks.onFinal(aggregatedResponse);
|
793
|
-
}
|
794
|
-
}
|
795
|
-
});
|
796
|
-
}
|
797
|
-
function isOfTypeOpenAIStreamCallbacks(callbacks) {
|
798
|
-
return "experimental_onFunctionCall" in callbacks;
|
799
|
-
}
|
800
|
-
function trimStartOfStreamHelper() {
|
801
|
-
let isStreamStart = true;
|
802
|
-
return (text) => {
|
803
|
-
if (isStreamStart) {
|
804
|
-
text = text.trimStart();
|
805
|
-
if (text)
|
806
|
-
isStreamStart = false;
|
807
|
-
}
|
808
|
-
return text;
|
809
|
-
};
|
810
|
-
}
|
811
|
-
function AIStream(response, customParser, callbacks) {
|
812
|
-
if (!response.ok) {
|
813
|
-
if (response.body) {
|
814
|
-
const reader = response.body.getReader();
|
815
|
-
return new ReadableStream({
|
816
|
-
async start(controller) {
|
817
|
-
const { done, value } = await reader.read();
|
818
|
-
if (!done) {
|
819
|
-
const errorText = new TextDecoder().decode(value);
|
820
|
-
controller.error(new Error(`Response error: ${errorText}`));
|
821
|
-
}
|
822
|
-
}
|
900
|
+
// core/prompt/prepare-retries.ts
|
901
|
+
function prepareRetries({
|
902
|
+
maxRetries
|
903
|
+
}) {
|
904
|
+
if (maxRetries != null) {
|
905
|
+
if (!Number.isInteger(maxRetries)) {
|
906
|
+
throw new InvalidArgumentError({
|
907
|
+
parameter: "maxRetries",
|
908
|
+
value: maxRetries,
|
909
|
+
message: "maxRetries must be an integer"
|
823
910
|
});
|
824
|
-
}
|
825
|
-
|
826
|
-
|
827
|
-
|
828
|
-
|
911
|
+
}
|
912
|
+
if (maxRetries < 0) {
|
913
|
+
throw new InvalidArgumentError({
|
914
|
+
parameter: "maxRetries",
|
915
|
+
value: maxRetries,
|
916
|
+
message: "maxRetries must be >= 0"
|
829
917
|
});
|
830
918
|
}
|
831
919
|
}
|
832
|
-
const
|
833
|
-
return
|
834
|
-
|
835
|
-
|
836
|
-
|
837
|
-
start(controller) {
|
838
|
-
controller.close();
|
839
|
-
}
|
840
|
-
});
|
841
|
-
}
|
842
|
-
function readableFromAsyncIterable(iterable) {
|
843
|
-
let it = iterable[Symbol.asyncIterator]();
|
844
|
-
return new ReadableStream({
|
845
|
-
async pull(controller) {
|
846
|
-
const { done, value } = await it.next();
|
847
|
-
if (done)
|
848
|
-
controller.close();
|
849
|
-
else
|
850
|
-
controller.enqueue(value);
|
851
|
-
},
|
852
|
-
async cancel(reason) {
|
853
|
-
var _a;
|
854
|
-
await ((_a = it.return) == null ? void 0 : _a.call(it, reason));
|
855
|
-
}
|
856
|
-
});
|
920
|
+
const maxRetriesResult = maxRetries != null ? maxRetries : 2;
|
921
|
+
return {
|
922
|
+
maxRetries: maxRetriesResult,
|
923
|
+
retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
|
924
|
+
};
|
857
925
|
}
|
858
926
|
|
859
|
-
//
|
860
|
-
|
861
|
-
const encoder = new TextEncoder();
|
862
|
-
const decoder = new TextDecoder();
|
863
|
-
return new TransformStream({
|
864
|
-
transform: async (chunk, controller) => {
|
865
|
-
const message = decoder.decode(chunk);
|
866
|
-
controller.enqueue(encoder.encode(formatStreamPart("text", message)));
|
867
|
-
}
|
868
|
-
});
|
869
|
-
}
|
927
|
+
// core/prompt/prepare-tools-and-tool-choice.ts
|
928
|
+
import { asSchema } from "@ai-sdk/ui-utils";
|
870
929
|
|
871
|
-
//
|
872
|
-
function
|
873
|
-
|
874
|
-
return (data) => extract(JSON.parse(data));
|
930
|
+
// core/util/is-non-empty-object.ts
|
931
|
+
function isNonEmptyObject(object) {
|
932
|
+
return object != null && Object.keys(object).length > 0;
|
875
933
|
}
|
876
|
-
|
877
|
-
|
878
|
-
|
879
|
-
|
880
|
-
|
881
|
-
|
882
|
-
|
883
|
-
|
884
|
-
|
885
|
-
|
886
|
-
|
887
|
-
|
888
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
889
|
-
return {
|
890
|
-
delta: {
|
891
|
-
content: (_a = choice.delta) == null ? void 0 : _a.content,
|
892
|
-
function_call: (_b = choice.delta) == null ? void 0 : _b.functionCall,
|
893
|
-
role: (_c = choice.delta) == null ? void 0 : _c.role,
|
894
|
-
tool_calls: ((_e = (_d = choice.delta) == null ? void 0 : _d.toolCalls) == null ? void 0 : _e.length) ? (_g = (_f = choice.delta) == null ? void 0 : _f.toolCalls) == null ? void 0 : _g.map((toolCall, index) => ({
|
895
|
-
index,
|
896
|
-
id: toolCall.id,
|
897
|
-
function: toolCall.function,
|
898
|
-
type: toolCall.type
|
899
|
-
})) : void 0
|
900
|
-
},
|
901
|
-
finish_reason: choice.finishReason,
|
902
|
-
index: choice.index
|
903
|
-
};
|
904
|
-
})
|
905
|
-
};
|
906
|
-
}
|
907
|
-
const text = extract(chunk);
|
908
|
-
if (text)
|
909
|
-
yield text;
|
934
|
+
|
935
|
+
// core/prompt/prepare-tools-and-tool-choice.ts
|
936
|
+
function prepareToolsAndToolChoice({
|
937
|
+
tools,
|
938
|
+
toolChoice,
|
939
|
+
activeTools
|
940
|
+
}) {
|
941
|
+
if (!isNonEmptyObject(tools)) {
|
942
|
+
return {
|
943
|
+
tools: void 0,
|
944
|
+
toolChoice: void 0
|
945
|
+
};
|
910
946
|
}
|
911
|
-
|
912
|
-
|
913
|
-
|
914
|
-
|
915
|
-
|
916
|
-
|
917
|
-
|
918
|
-
|
919
|
-
|
920
|
-
isFunctionStreamingIn = true;
|
921
|
-
return {
|
922
|
-
isText: false,
|
923
|
-
content: `{"function_call": {"name": "${delta.function_call.name}", "arguments": "`
|
924
|
-
};
|
925
|
-
} else if ((_e = (_d = (_c = delta.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.name) {
|
926
|
-
isFunctionStreamingIn = true;
|
927
|
-
const toolCall = delta.tool_calls[0];
|
928
|
-
if (toolCall.index === 0) {
|
947
|
+
const filteredTools = activeTools != null ? Object.entries(tools).filter(
|
948
|
+
([name9]) => activeTools.includes(name9)
|
949
|
+
) : Object.entries(tools);
|
950
|
+
return {
|
951
|
+
tools: filteredTools.map(([name9, tool]) => {
|
952
|
+
const toolType = tool.type;
|
953
|
+
switch (toolType) {
|
954
|
+
case void 0:
|
955
|
+
case "function":
|
929
956
|
return {
|
930
|
-
|
931
|
-
|
957
|
+
type: "function",
|
958
|
+
name: name9,
|
959
|
+
description: tool.description,
|
960
|
+
parameters: asSchema(tool.parameters).jsonSchema
|
932
961
|
};
|
933
|
-
|
962
|
+
case "provider-defined":
|
934
963
|
return {
|
935
|
-
|
936
|
-
|
964
|
+
type: "provider-defined",
|
965
|
+
name: name9,
|
966
|
+
id: tool.id,
|
967
|
+
args: tool.args
|
937
968
|
};
|
969
|
+
default: {
|
970
|
+
const exhaustiveCheck = toolType;
|
971
|
+
throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
|
938
972
|
}
|
939
|
-
} else if ((_h = delta.function_call) == null ? void 0 : _h.arguments) {
|
940
|
-
return {
|
941
|
-
isText: false,
|
942
|
-
content: cleanupArguments((_i = delta.function_call) == null ? void 0 : _i.arguments)
|
943
|
-
};
|
944
|
-
} else if ((_l = (_k = (_j = delta.tool_calls) == null ? void 0 : _j[0]) == null ? void 0 : _k.function) == null ? void 0 : _l.arguments) {
|
945
|
-
return {
|
946
|
-
isText: false,
|
947
|
-
content: cleanupArguments((_o = (_n = (_m = delta.tool_calls) == null ? void 0 : _m[0]) == null ? void 0 : _n.function) == null ? void 0 : _o.arguments)
|
948
|
-
};
|
949
|
-
} else if (isFunctionStreamingIn && (((_p = json.choices[0]) == null ? void 0 : _p.finish_reason) === "function_call" || ((_q = json.choices[0]) == null ? void 0 : _q.finish_reason) === "stop")) {
|
950
|
-
isFunctionStreamingIn = false;
|
951
|
-
return {
|
952
|
-
isText: false,
|
953
|
-
content: '"}}'
|
954
|
-
};
|
955
|
-
} else if (isFunctionStreamingIn && ((_r = json.choices[0]) == null ? void 0 : _r.finish_reason) === "tool_calls") {
|
956
|
-
isFunctionStreamingIn = false;
|
957
|
-
return {
|
958
|
-
isText: false,
|
959
|
-
content: '"}}]}'
|
960
|
-
};
|
961
973
|
}
|
962
|
-
}
|
963
|
-
|
964
|
-
isChatCompletionChunk(json) && json.choices[0].delta.content ? json.choices[0].delta.content : isCompletion(json) ? json.choices[0].text : ""
|
965
|
-
);
|
966
|
-
return text;
|
974
|
+
}),
|
975
|
+
toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
|
967
976
|
};
|
968
|
-
function cleanupArguments(argumentChunk) {
|
969
|
-
let escapedPartialJson = argumentChunk.replace(/\\/g, "\\\\").replace(/\//g, "\\/").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\f/g, "\\f");
|
970
|
-
return `${escapedPartialJson}`;
|
971
|
-
}
|
972
|
-
}
|
973
|
-
var __internal__OpenAIFnMessagesSymbol = Symbol(
|
974
|
-
"internal_openai_fn_messages"
|
975
|
-
);
|
976
|
-
function isChatCompletionChunk(data) {
|
977
|
-
return "choices" in data && data.choices && data.choices[0] && "delta" in data.choices[0];
|
978
|
-
}
|
979
|
-
function isCompletion(data) {
|
980
|
-
return "choices" in data && data.choices && data.choices[0] && "text" in data.choices[0];
|
981
977
|
}
|
982
|
-
|
983
|
-
|
984
|
-
|
985
|
-
|
986
|
-
|
987
|
-
|
988
|
-
|
989
|
-
|
990
|
-
|
991
|
-
|
992
|
-
|
978
|
+
|
979
|
+
// core/prompt/standardize-prompt.ts
|
980
|
+
import { InvalidPromptError } from "@ai-sdk/provider";
|
981
|
+
import { safeValidateTypes } from "@ai-sdk/provider-utils";
|
982
|
+
import { z as z7 } from "zod";
|
983
|
+
|
984
|
+
// core/prompt/attachments-to-parts.ts
|
985
|
+
function attachmentsToParts(attachments) {
|
986
|
+
var _a9, _b, _c;
|
987
|
+
const parts = [];
|
988
|
+
for (const attachment of attachments) {
|
989
|
+
let url;
|
990
|
+
try {
|
991
|
+
url = new URL(attachment.url);
|
992
|
+
} catch (error) {
|
993
|
+
throw new Error(`Invalid URL: ${attachment.url}`);
|
994
|
+
}
|
995
|
+
switch (url.protocol) {
|
996
|
+
case "http:":
|
997
|
+
case "https:": {
|
998
|
+
if ((_a9 = attachment.contentType) == null ? void 0 : _a9.startsWith("image/")) {
|
999
|
+
parts.push({ type: "image", image: url });
|
1000
|
+
} else {
|
1001
|
+
if (!attachment.contentType) {
|
1002
|
+
throw new Error(
|
1003
|
+
"If the attachment is not an image, it must specify a content type"
|
1004
|
+
);
|
1005
|
+
}
|
1006
|
+
parts.push({
|
1007
|
+
type: "file",
|
1008
|
+
data: url,
|
1009
|
+
mimeType: attachment.contentType
|
1010
|
+
});
|
993
1011
|
}
|
994
|
-
|
995
|
-
);
|
996
|
-
} else {
|
997
|
-
stream = AIStream(
|
998
|
-
res,
|
999
|
-
parseOpenAIStream(),
|
1000
|
-
(cb == null ? void 0 : cb.experimental_onFunctionCall) || (cb == null ? void 0 : cb.experimental_onToolCall) ? {
|
1001
|
-
...cb,
|
1002
|
-
onFinal: void 0
|
1003
|
-
} : {
|
1004
|
-
...cb
|
1012
|
+
break;
|
1005
1013
|
}
|
1006
|
-
|
1007
|
-
|
1008
|
-
|
1009
|
-
|
1010
|
-
|
1011
|
-
|
1012
|
-
|
1014
|
+
case "data:": {
|
1015
|
+
let header;
|
1016
|
+
let base64Content;
|
1017
|
+
let mimeType;
|
1018
|
+
try {
|
1019
|
+
[header, base64Content] = attachment.url.split(",");
|
1020
|
+
mimeType = header.split(";")[0].split(":")[1];
|
1021
|
+
} catch (error) {
|
1022
|
+
throw new Error(`Error processing data URL: ${attachment.url}`);
|
1023
|
+
}
|
1024
|
+
if (mimeType == null || base64Content == null) {
|
1025
|
+
throw new Error(`Invalid data URL format: ${attachment.url}`);
|
1026
|
+
}
|
1027
|
+
if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
|
1028
|
+
parts.push({
|
1029
|
+
type: "image",
|
1030
|
+
image: convertDataContentToUint8Array(base64Content)
|
1031
|
+
});
|
1032
|
+
} else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
|
1033
|
+
parts.push({
|
1034
|
+
type: "text",
|
1035
|
+
text: convertUint8ArrayToText(
|
1036
|
+
convertDataContentToUint8Array(base64Content)
|
1037
|
+
)
|
1038
|
+
});
|
1039
|
+
} else {
|
1040
|
+
if (!attachment.contentType) {
|
1041
|
+
throw new Error(
|
1042
|
+
"If the attachment is not an image or text, it must specify a content type"
|
1043
|
+
);
|
1044
|
+
}
|
1045
|
+
parts.push({
|
1046
|
+
type: "file",
|
1047
|
+
data: base64Content,
|
1048
|
+
mimeType: attachment.contentType
|
1049
|
+
});
|
1050
|
+
}
|
1051
|
+
break;
|
1052
|
+
}
|
1053
|
+
default: {
|
1054
|
+
throw new Error(`Unsupported URL protocol: ${url.protocol}`);
|
1055
|
+
}
|
1056
|
+
}
|
1013
1057
|
}
|
1058
|
+
return parts;
|
1014
1059
|
}
|
1015
|
-
|
1016
|
-
|
1017
|
-
|
1018
|
-
|
1019
|
-
|
1020
|
-
|
1021
|
-
|
1022
|
-
|
1023
|
-
|
1024
|
-
|
1025
|
-
|
1026
|
-
|
1027
|
-
|
1028
|
-
|
1029
|
-
|
1030
|
-
|
1031
|
-
|
1032
|
-
|
1060
|
+
|
1061
|
+
// core/prompt/message-conversion-error.ts
|
1062
|
+
import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
|
1063
|
+
var name6 = "AI_MessageConversionError";
|
1064
|
+
var marker6 = `vercel.ai.error.${name6}`;
|
1065
|
+
var symbol6 = Symbol.for(marker6);
|
1066
|
+
var _a6;
|
1067
|
+
var MessageConversionError = class extends AISDKError6 {
|
1068
|
+
constructor({
|
1069
|
+
originalMessage,
|
1070
|
+
message
|
1071
|
+
}) {
|
1072
|
+
super({ name: name6, message });
|
1073
|
+
this[_a6] = true;
|
1074
|
+
this.originalMessage = originalMessage;
|
1075
|
+
}
|
1076
|
+
static isInstance(error) {
|
1077
|
+
return AISDKError6.hasMarker(error, marker6);
|
1078
|
+
}
|
1079
|
+
};
|
1080
|
+
_a6 = symbol6;
|
1081
|
+
|
1082
|
+
// core/prompt/convert-to-core-messages.ts
|
1083
|
+
function convertToCoreMessages(messages, options) {
|
1084
|
+
var _a9, _b;
|
1085
|
+
const tools = (_a9 = options == null ? void 0 : options.tools) != null ? _a9 : {};
|
1086
|
+
const coreMessages = [];
|
1087
|
+
for (let i = 0; i < messages.length; i++) {
|
1088
|
+
const message = messages[i];
|
1089
|
+
const isLastMessage = i === messages.length - 1;
|
1090
|
+
const { role, content, experimental_attachments } = message;
|
1091
|
+
switch (role) {
|
1092
|
+
case "system": {
|
1093
|
+
coreMessages.push({
|
1094
|
+
role: "system",
|
1095
|
+
content
|
1096
|
+
});
|
1097
|
+
break;
|
1033
1098
|
}
|
1034
|
-
|
1035
|
-
|
1036
|
-
|
1037
|
-
|
1038
|
-
|
1039
|
-
|
1040
|
-
|
1099
|
+
case "user": {
|
1100
|
+
if (message.parts == null) {
|
1101
|
+
coreMessages.push({
|
1102
|
+
role: "user",
|
1103
|
+
content: experimental_attachments ? [
|
1104
|
+
{ type: "text", text: content },
|
1105
|
+
...attachmentsToParts(experimental_attachments)
|
1106
|
+
] : content
|
1107
|
+
});
|
1108
|
+
} else {
|
1109
|
+
const textParts = message.parts.filter((part) => part.type === "text").map((part) => ({
|
1110
|
+
type: "text",
|
1111
|
+
text: part.text
|
1112
|
+
}));
|
1113
|
+
coreMessages.push({
|
1114
|
+
role: "user",
|
1115
|
+
content: experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts
|
1116
|
+
});
|
1117
|
+
}
|
1118
|
+
break;
|
1041
1119
|
}
|
1042
|
-
|
1043
|
-
|
1044
|
-
|
1045
|
-
|
1046
|
-
|
1047
|
-
|
1048
|
-
|
1049
|
-
|
1050
|
-
|
1051
|
-
|
1052
|
-
if (callbacks.experimental_onFunctionCall) {
|
1053
|
-
if (payload.function_call === void 0) {
|
1054
|
-
console.warn(
|
1055
|
-
"experimental_onFunctionCall should not be defined when using tools"
|
1056
|
-
);
|
1057
|
-
}
|
1058
|
-
const argumentsPayload = JSON.parse(
|
1059
|
-
payload.function_call.arguments
|
1060
|
-
);
|
1061
|
-
functionResponse = await callbacks.experimental_onFunctionCall(
|
1062
|
-
{
|
1063
|
-
name: payload.function_call.name,
|
1064
|
-
arguments: argumentsPayload
|
1065
|
-
},
|
1066
|
-
(result) => {
|
1067
|
-
newFunctionCallMessages = [
|
1068
|
-
...functionCallMessages,
|
1069
|
-
{
|
1070
|
-
role: "assistant",
|
1071
|
-
content: "",
|
1072
|
-
function_call: payload.function_call
|
1073
|
-
},
|
1074
|
-
{
|
1075
|
-
role: "function",
|
1076
|
-
name: payload.function_call.name,
|
1077
|
-
content: JSON.stringify(result)
|
1078
|
-
}
|
1079
|
-
];
|
1080
|
-
return newFunctionCallMessages;
|
1081
|
-
}
|
1082
|
-
);
|
1083
|
-
}
|
1084
|
-
if (callbacks.experimental_onToolCall) {
|
1085
|
-
const toolCalls = {
|
1086
|
-
tools: []
|
1087
|
-
};
|
1088
|
-
for (const tool of payload.tool_calls) {
|
1089
|
-
toolCalls.tools.push({
|
1090
|
-
id: tool.id,
|
1091
|
-
type: "function",
|
1092
|
-
func: {
|
1093
|
-
name: tool.function.name,
|
1094
|
-
arguments: JSON.parse(tool.function.arguments)
|
1120
|
+
case "assistant": {
|
1121
|
+
if (message.parts != null) {
|
1122
|
+
let processBlock2 = function() {
|
1123
|
+
const content2 = [];
|
1124
|
+
for (const part of block) {
|
1125
|
+
switch (part.type) {
|
1126
|
+
case "file":
|
1127
|
+
case "text": {
|
1128
|
+
content2.push(part);
|
1129
|
+
break;
|
1095
1130
|
}
|
1096
|
-
|
1097
|
-
|
1098
|
-
|
1099
|
-
|
1100
|
-
|
1101
|
-
|
1102
|
-
|
1103
|
-
|
1104
|
-
|
1105
|
-
|
1106
|
-
|
1107
|
-
|
1108
|
-
|
1109
|
-
|
1110
|
-
|
1111
|
-
|
1112
|
-
|
1113
|
-
(tc) => ({
|
1114
|
-
id: tc.id,
|
1115
|
-
type: "function",
|
1116
|
-
function: {
|
1117
|
-
name: tc.function.name,
|
1118
|
-
// we send the arguments an object to the user, but as the API expects a string, we need to stringify it
|
1119
|
-
arguments: JSON.stringify(
|
1120
|
-
tc.function.arguments
|
1121
|
-
)
|
1122
|
-
}
|
1123
|
-
})
|
1124
|
-
)
|
1125
|
-
}
|
1126
|
-
] : [],
|
1127
|
-
// Append the function call result message
|
1128
|
-
{
|
1129
|
-
role: "tool",
|
1130
|
-
tool_call_id,
|
1131
|
-
name: function_name,
|
1132
|
-
content: JSON.stringify(tool_call_result)
|
1133
|
-
}
|
1134
|
-
];
|
1135
|
-
responseIndex++;
|
1131
|
+
case "reasoning": {
|
1132
|
+
for (const detail of part.details) {
|
1133
|
+
switch (detail.type) {
|
1134
|
+
case "text":
|
1135
|
+
content2.push({
|
1136
|
+
type: "reasoning",
|
1137
|
+
text: detail.text,
|
1138
|
+
signature: detail.signature
|
1139
|
+
});
|
1140
|
+
break;
|
1141
|
+
case "redacted":
|
1142
|
+
content2.push({
|
1143
|
+
type: "redacted-reasoning",
|
1144
|
+
data: detail.data
|
1145
|
+
});
|
1146
|
+
break;
|
1147
|
+
}
|
1136
1148
|
}
|
1137
|
-
|
1149
|
+
break;
|
1138
1150
|
}
|
1139
|
-
|
1140
|
-
|
1141
|
-
|
1142
|
-
|
1143
|
-
|
1144
|
-
|
1145
|
-
|
1146
|
-
|
1147
|
-
|
1148
|
-
|
1149
|
-
|
1150
|
-
|
1151
|
+
case "tool-invocation":
|
1152
|
+
content2.push({
|
1153
|
+
type: "tool-call",
|
1154
|
+
toolCallId: part.toolInvocation.toolCallId,
|
1155
|
+
toolName: part.toolInvocation.toolName,
|
1156
|
+
args: part.toolInvocation.args
|
1157
|
+
});
|
1158
|
+
break;
|
1159
|
+
default: {
|
1160
|
+
const _exhaustiveCheck = part;
|
1161
|
+
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
1162
|
+
}
|
1163
|
+
}
|
1164
|
+
}
|
1165
|
+
coreMessages.push({
|
1166
|
+
role: "assistant",
|
1167
|
+
content: content2
|
1168
|
+
});
|
1169
|
+
const stepInvocations = block.filter(
|
1170
|
+
(part) => part.type === "tool-invocation"
|
1171
|
+
).map((part) => part.toolInvocation);
|
1172
|
+
if (stepInvocations.length > 0) {
|
1173
|
+
coreMessages.push({
|
1174
|
+
role: "tool",
|
1175
|
+
content: stepInvocations.map(
|
1176
|
+
(toolInvocation) => {
|
1177
|
+
if (!("result" in toolInvocation)) {
|
1178
|
+
throw new MessageConversionError({
|
1179
|
+
originalMessage: message,
|
1180
|
+
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
|
1181
|
+
});
|
1182
|
+
}
|
1183
|
+
const { toolCallId, toolName, result } = toolInvocation;
|
1184
|
+
const tool = tools[toolName];
|
1185
|
+
return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
|
1186
|
+
type: "tool-result",
|
1187
|
+
toolCallId,
|
1188
|
+
toolName,
|
1189
|
+
result: tool.experimental_toToolResultContent(result),
|
1190
|
+
experimental_content: tool.experimental_toToolResultContent(result)
|
1191
|
+
} : {
|
1192
|
+
type: "tool-result",
|
1193
|
+
toolCallId,
|
1194
|
+
toolName,
|
1195
|
+
result
|
1196
|
+
};
|
1197
|
+
}
|
1151
1198
|
)
|
1152
|
-
)
|
1153
|
-
|
1154
|
-
|
1155
|
-
|
1156
|
-
|
1157
|
-
textEncoder.encode(formatStreamPart("text", functionResponse))
|
1158
|
-
);
|
1159
|
-
aggregatedFinalCompletionResponse = functionResponse;
|
1160
|
-
return;
|
1161
|
-
}
|
1162
|
-
const filteredCallbacks = {
|
1163
|
-
...callbacks,
|
1164
|
-
onStart: void 0
|
1199
|
+
});
|
1200
|
+
}
|
1201
|
+
block = [];
|
1202
|
+
blockHasToolInvocations = false;
|
1203
|
+
currentStep++;
|
1165
1204
|
};
|
1166
|
-
|
1167
|
-
|
1168
|
-
|
1169
|
-
|
1170
|
-
|
1171
|
-
|
1172
|
-
|
1173
|
-
|
1174
|
-
|
1175
|
-
|
1205
|
+
var processBlock = processBlock2;
|
1206
|
+
let currentStep = 0;
|
1207
|
+
let blockHasToolInvocations = false;
|
1208
|
+
let block = [];
|
1209
|
+
for (const part of message.parts) {
|
1210
|
+
switch (part.type) {
|
1211
|
+
case "text": {
|
1212
|
+
if (blockHasToolInvocations) {
|
1213
|
+
processBlock2();
|
1214
|
+
}
|
1215
|
+
block.push(part);
|
1216
|
+
break;
|
1217
|
+
}
|
1218
|
+
case "file":
|
1219
|
+
case "reasoning": {
|
1220
|
+
block.push(part);
|
1221
|
+
break;
|
1222
|
+
}
|
1223
|
+
case "tool-invocation": {
|
1224
|
+
if (((_b = part.toolInvocation.step) != null ? _b : 0) !== currentStep) {
|
1225
|
+
processBlock2();
|
1226
|
+
}
|
1227
|
+
block.push(part);
|
1228
|
+
blockHasToolInvocations = true;
|
1229
|
+
break;
|
1230
|
+
}
|
1176
1231
|
}
|
1177
|
-
controller.enqueue(value);
|
1178
1232
|
}
|
1233
|
+
processBlock2();
|
1234
|
+
break;
|
1179
1235
|
}
|
1180
|
-
|
1181
|
-
if (
|
1182
|
-
|
1236
|
+
const toolInvocations = message.toolInvocations;
|
1237
|
+
if (toolInvocations == null || toolInvocations.length === 0) {
|
1238
|
+
coreMessages.push({ role: "assistant", content });
|
1239
|
+
break;
|
1183
1240
|
}
|
1241
|
+
const maxStep = toolInvocations.reduce((max, toolInvocation) => {
|
1242
|
+
var _a10;
|
1243
|
+
return Math.max(max, (_a10 = toolInvocation.step) != null ? _a10 : 0);
|
1244
|
+
}, 0);
|
1245
|
+
for (let i2 = 0; i2 <= maxStep; i2++) {
|
1246
|
+
const stepInvocations = toolInvocations.filter(
|
1247
|
+
(toolInvocation) => {
|
1248
|
+
var _a10;
|
1249
|
+
return ((_a10 = toolInvocation.step) != null ? _a10 : 0) === i2;
|
1250
|
+
}
|
1251
|
+
);
|
1252
|
+
if (stepInvocations.length === 0) {
|
1253
|
+
continue;
|
1254
|
+
}
|
1255
|
+
coreMessages.push({
|
1256
|
+
role: "assistant",
|
1257
|
+
content: [
|
1258
|
+
...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
|
1259
|
+
...stepInvocations.map(
|
1260
|
+
({ toolCallId, toolName, args }) => ({
|
1261
|
+
type: "tool-call",
|
1262
|
+
toolCallId,
|
1263
|
+
toolName,
|
1264
|
+
args
|
1265
|
+
})
|
1266
|
+
)
|
1267
|
+
]
|
1268
|
+
});
|
1269
|
+
coreMessages.push({
|
1270
|
+
role: "tool",
|
1271
|
+
content: stepInvocations.map((toolInvocation) => {
|
1272
|
+
if (!("result" in toolInvocation)) {
|
1273
|
+
throw new MessageConversionError({
|
1274
|
+
originalMessage: message,
|
1275
|
+
message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
|
1276
|
+
});
|
1277
|
+
}
|
1278
|
+
const { toolCallId, toolName, result } = toolInvocation;
|
1279
|
+
const tool = tools[toolName];
|
1280
|
+
return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
|
1281
|
+
type: "tool-result",
|
1282
|
+
toolCallId,
|
1283
|
+
toolName,
|
1284
|
+
result: tool.experimental_toToolResultContent(result),
|
1285
|
+
experimental_content: tool.experimental_toToolResultContent(result)
|
1286
|
+
} : {
|
1287
|
+
type: "tool-result",
|
1288
|
+
toolCallId,
|
1289
|
+
toolName,
|
1290
|
+
result
|
1291
|
+
};
|
1292
|
+
})
|
1293
|
+
});
|
1294
|
+
}
|
1295
|
+
if (content && !isLastMessage) {
|
1296
|
+
coreMessages.push({ role: "assistant", content });
|
1297
|
+
}
|
1298
|
+
break;
|
1299
|
+
}
|
1300
|
+
case "data": {
|
1301
|
+
break;
|
1302
|
+
}
|
1303
|
+
default: {
|
1304
|
+
const _exhaustiveCheck = role;
|
1305
|
+
throw new MessageConversionError({
|
1306
|
+
originalMessage: message,
|
1307
|
+
message: `Unsupported role: ${_exhaustiveCheck}`
|
1308
|
+
});
|
1184
1309
|
}
|
1185
1310
|
}
|
1186
|
-
}
|
1311
|
+
}
|
1312
|
+
return coreMessages;
|
1187
1313
|
}
|
1188
1314
|
|
1189
|
-
//
|
1190
|
-
|
1191
|
-
|
1315
|
+
// core/prompt/detect-prompt-type.ts
|
1316
|
+
function detectPromptType(prompt) {
|
1317
|
+
if (!Array.isArray(prompt)) {
|
1318
|
+
return "other";
|
1319
|
+
}
|
1320
|
+
if (prompt.length === 0) {
|
1321
|
+
return "messages";
|
1322
|
+
}
|
1323
|
+
const characteristics = prompt.map(detectSingleMessageCharacteristics);
|
1324
|
+
if (characteristics.some((c) => c === "has-ui-specific-parts")) {
|
1325
|
+
return "ui-messages";
|
1326
|
+
} else if (characteristics.every(
|
1327
|
+
(c) => c === "has-core-specific-parts" || c === "message"
|
1328
|
+
)) {
|
1329
|
+
return "messages";
|
1330
|
+
} else {
|
1331
|
+
return "other";
|
1332
|
+
}
|
1333
|
+
}
|
1334
|
+
function detectSingleMessageCharacteristics(message) {
|
1335
|
+
if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
|
1336
|
+
message.role === "data" || // UI-only role
|
1337
|
+
"toolInvocations" in message || // UI-specific field
|
1338
|
+
"parts" in message || // UI-specific field
|
1339
|
+
"experimental_attachments" in message)) {
|
1340
|
+
return "has-ui-specific-parts";
|
1341
|
+
} else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
|
1342
|
+
"experimental_providerMetadata" in message || "providerOptions" in message)) {
|
1343
|
+
return "has-core-specific-parts";
|
1344
|
+
} else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
|
1345
|
+
return "message";
|
1346
|
+
} else {
|
1347
|
+
return "other";
|
1348
|
+
}
|
1349
|
+
}
|
1350
|
+
|
1351
|
+
// core/prompt/message.ts
|
1352
|
+
import { z as z6 } from "zod";
|
1353
|
+
|
1354
|
+
// core/types/provider-metadata.ts
|
1355
|
+
import { z as z3 } from "zod";
|
1356
|
+
|
1357
|
+
// core/types/json-value.ts
|
1358
|
+
import { z as z2 } from "zod";
|
1359
|
+
var jsonValueSchema = z2.lazy(
|
1360
|
+
() => z2.union([
|
1361
|
+
z2.null(),
|
1362
|
+
z2.string(),
|
1363
|
+
z2.number(),
|
1364
|
+
z2.boolean(),
|
1365
|
+
z2.record(z2.string(), jsonValueSchema),
|
1366
|
+
z2.array(jsonValueSchema)
|
1367
|
+
])
|
1368
|
+
);
|
1369
|
+
|
1370
|
+
// core/types/provider-metadata.ts
|
1371
|
+
var providerMetadataSchema = z3.record(
|
1372
|
+
z3.string(),
|
1373
|
+
z3.record(z3.string(), jsonValueSchema)
|
1374
|
+
);
|
1375
|
+
|
1376
|
+
// core/prompt/content-part.ts
|
1377
|
+
import { z as z5 } from "zod";
|
1378
|
+
|
1379
|
+
// core/prompt/tool-result-content.ts
|
1380
|
+
import { z as z4 } from "zod";
|
1381
|
+
var toolResultContentSchema = z4.array(
|
1382
|
+
z4.union([
|
1383
|
+
z4.object({ type: z4.literal("text"), text: z4.string() }),
|
1384
|
+
z4.object({
|
1385
|
+
type: z4.literal("image"),
|
1386
|
+
data: z4.string(),
|
1387
|
+
mimeType: z4.string().optional()
|
1388
|
+
})
|
1389
|
+
])
|
1390
|
+
);
|
1391
|
+
|
1392
|
+
// core/prompt/content-part.ts
|
1393
|
+
var textPartSchema = z5.object({
|
1394
|
+
type: z5.literal("text"),
|
1395
|
+
text: z5.string(),
|
1396
|
+
providerOptions: providerMetadataSchema.optional(),
|
1397
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1398
|
+
});
|
1399
|
+
var imagePartSchema = z5.object({
|
1400
|
+
type: z5.literal("image"),
|
1401
|
+
image: z5.union([dataContentSchema, z5.instanceof(URL)]),
|
1402
|
+
mimeType: z5.string().optional(),
|
1403
|
+
providerOptions: providerMetadataSchema.optional(),
|
1404
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1405
|
+
});
|
1406
|
+
var filePartSchema = z5.object({
|
1407
|
+
type: z5.literal("file"),
|
1408
|
+
data: z5.union([dataContentSchema, z5.instanceof(URL)]),
|
1409
|
+
filename: z5.string().optional(),
|
1410
|
+
mimeType: z5.string(),
|
1411
|
+
providerOptions: providerMetadataSchema.optional(),
|
1412
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1413
|
+
});
|
1414
|
+
var reasoningPartSchema = z5.object({
|
1415
|
+
type: z5.literal("reasoning"),
|
1416
|
+
text: z5.string(),
|
1417
|
+
providerOptions: providerMetadataSchema.optional(),
|
1418
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1419
|
+
});
|
1420
|
+
var redactedReasoningPartSchema = z5.object({
|
1421
|
+
type: z5.literal("redacted-reasoning"),
|
1422
|
+
data: z5.string(),
|
1423
|
+
providerOptions: providerMetadataSchema.optional(),
|
1424
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1425
|
+
});
|
1426
|
+
var toolCallPartSchema = z5.object({
|
1427
|
+
type: z5.literal("tool-call"),
|
1428
|
+
toolCallId: z5.string(),
|
1429
|
+
toolName: z5.string(),
|
1430
|
+
args: z5.unknown(),
|
1431
|
+
providerOptions: providerMetadataSchema.optional(),
|
1432
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1433
|
+
});
|
1434
|
+
var toolResultPartSchema = z5.object({
|
1435
|
+
type: z5.literal("tool-result"),
|
1436
|
+
toolCallId: z5.string(),
|
1437
|
+
toolName: z5.string(),
|
1438
|
+
result: z5.unknown(),
|
1439
|
+
content: toolResultContentSchema.optional(),
|
1440
|
+
isError: z5.boolean().optional(),
|
1441
|
+
providerOptions: providerMetadataSchema.optional(),
|
1442
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1443
|
+
});
|
1444
|
+
|
1445
|
+
// core/prompt/message.ts
|
1446
|
+
var coreSystemMessageSchema = z6.object({
|
1447
|
+
role: z6.literal("system"),
|
1448
|
+
content: z6.string(),
|
1449
|
+
providerOptions: providerMetadataSchema.optional(),
|
1450
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1451
|
+
});
|
1452
|
+
var coreUserMessageSchema = z6.object({
|
1453
|
+
role: z6.literal("user"),
|
1454
|
+
content: z6.union([
|
1455
|
+
z6.string(),
|
1456
|
+
z6.array(z6.union([textPartSchema, imagePartSchema, filePartSchema]))
|
1457
|
+
]),
|
1458
|
+
providerOptions: providerMetadataSchema.optional(),
|
1459
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1460
|
+
});
|
1461
|
+
var coreAssistantMessageSchema = z6.object({
|
1462
|
+
role: z6.literal("assistant"),
|
1463
|
+
content: z6.union([
|
1464
|
+
z6.string(),
|
1465
|
+
z6.array(
|
1466
|
+
z6.union([
|
1467
|
+
textPartSchema,
|
1468
|
+
filePartSchema,
|
1469
|
+
reasoningPartSchema,
|
1470
|
+
redactedReasoningPartSchema,
|
1471
|
+
toolCallPartSchema
|
1472
|
+
])
|
1473
|
+
)
|
1474
|
+
]),
|
1475
|
+
providerOptions: providerMetadataSchema.optional(),
|
1476
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1477
|
+
});
|
1478
|
+
var coreToolMessageSchema = z6.object({
|
1479
|
+
role: z6.literal("tool"),
|
1480
|
+
content: z6.array(toolResultPartSchema),
|
1481
|
+
providerOptions: providerMetadataSchema.optional(),
|
1482
|
+
experimental_providerMetadata: providerMetadataSchema.optional()
|
1483
|
+
});
|
1484
|
+
var coreMessageSchema = z6.union([
|
1485
|
+
coreSystemMessageSchema,
|
1486
|
+
coreUserMessageSchema,
|
1487
|
+
coreAssistantMessageSchema,
|
1488
|
+
coreToolMessageSchema
|
1489
|
+
]);
|
1490
|
+
|
1491
|
+
// core/prompt/standardize-prompt.ts
|
1492
|
+
function standardizePrompt({
|
1493
|
+
prompt,
|
1494
|
+
tools
|
1495
|
+
}) {
|
1496
|
+
if (prompt.prompt == null && prompt.messages == null) {
|
1497
|
+
throw new InvalidPromptError({
|
1498
|
+
prompt,
|
1499
|
+
message: "prompt or messages must be defined"
|
1500
|
+
});
|
1501
|
+
}
|
1502
|
+
if (prompt.prompt != null && prompt.messages != null) {
|
1503
|
+
throw new InvalidPromptError({
|
1504
|
+
prompt,
|
1505
|
+
message: "prompt and messages cannot be defined at the same time"
|
1506
|
+
});
|
1507
|
+
}
|
1508
|
+
if (prompt.system != null && typeof prompt.system !== "string") {
|
1509
|
+
throw new InvalidPromptError({
|
1510
|
+
prompt,
|
1511
|
+
message: "system must be a string"
|
1512
|
+
});
|
1513
|
+
}
|
1514
|
+
if (prompt.prompt != null) {
|
1515
|
+
if (typeof prompt.prompt !== "string") {
|
1516
|
+
throw new InvalidPromptError({
|
1517
|
+
prompt,
|
1518
|
+
message: "prompt must be a string"
|
1519
|
+
});
|
1520
|
+
}
|
1521
|
+
return {
|
1522
|
+
type: "prompt",
|
1523
|
+
system: prompt.system,
|
1524
|
+
messages: [
|
1525
|
+
{
|
1526
|
+
role: "user",
|
1527
|
+
content: prompt.prompt
|
1528
|
+
}
|
1529
|
+
]
|
1530
|
+
};
|
1531
|
+
}
|
1532
|
+
if (prompt.messages != null) {
|
1533
|
+
const promptType = detectPromptType(prompt.messages);
|
1534
|
+
if (promptType === "other") {
|
1535
|
+
throw new InvalidPromptError({
|
1536
|
+
prompt,
|
1537
|
+
message: "messages must be an array of CoreMessage or UIMessage"
|
1538
|
+
});
|
1539
|
+
}
|
1540
|
+
const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
|
1541
|
+
tools
|
1542
|
+
}) : prompt.messages;
|
1543
|
+
if (messages.length === 0) {
|
1544
|
+
throw new InvalidPromptError({
|
1545
|
+
prompt,
|
1546
|
+
message: "messages must not be empty"
|
1547
|
+
});
|
1548
|
+
}
|
1549
|
+
const validationResult = safeValidateTypes({
|
1550
|
+
value: messages,
|
1551
|
+
schema: z7.array(coreMessageSchema)
|
1552
|
+
});
|
1553
|
+
if (!validationResult.success) {
|
1554
|
+
throw new InvalidPromptError({
|
1555
|
+
prompt,
|
1556
|
+
message: "messages must be an array of CoreMessage or UIMessage",
|
1557
|
+
cause: validationResult.error
|
1558
|
+
});
|
1559
|
+
}
|
1560
|
+
return {
|
1561
|
+
type: "messages",
|
1562
|
+
messages,
|
1563
|
+
system: prompt.system
|
1564
|
+
};
|
1565
|
+
}
|
1566
|
+
throw new Error("unreachable");
|
1567
|
+
}
|
1568
|
+
|
1569
|
+
// core/types/usage.ts
|
1570
|
+
function calculateLanguageModelUsage({
|
1571
|
+
promptTokens,
|
1572
|
+
completionTokens
|
1573
|
+
}) {
|
1574
|
+
return {
|
1575
|
+
promptTokens,
|
1576
|
+
completionTokens,
|
1577
|
+
totalTokens: promptTokens + completionTokens
|
1578
|
+
};
|
1579
|
+
}
|
1580
|
+
|
1581
|
+
// errors/invalid-tool-arguments-error.ts
|
1582
|
+
import { AISDKError as AISDKError7, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
|
1583
|
+
var name7 = "AI_InvalidToolArgumentsError";
|
1584
|
+
var marker7 = `vercel.ai.error.${name7}`;
|
1585
|
+
var symbol7 = Symbol.for(marker7);
|
1586
|
+
var _a7;
|
1587
|
+
var InvalidToolArgumentsError = class extends AISDKError7 {
|
1588
|
+
constructor({
|
1589
|
+
toolArgs,
|
1590
|
+
toolName,
|
1591
|
+
cause,
|
1592
|
+
message = `Invalid arguments for tool ${toolName}: ${getErrorMessage2(
|
1593
|
+
cause
|
1594
|
+
)}`
|
1595
|
+
}) {
|
1596
|
+
super({ name: name7, message, cause });
|
1597
|
+
this[_a7] = true;
|
1598
|
+
this.toolArgs = toolArgs;
|
1599
|
+
this.toolName = toolName;
|
1600
|
+
}
|
1601
|
+
static isInstance(error) {
|
1602
|
+
return AISDKError7.hasMarker(error, marker7);
|
1603
|
+
}
|
1604
|
+
};
|
1605
|
+
_a7 = symbol7;
|
1606
|
+
|
1607
|
+
// errors/no-such-tool-error.ts
|
1608
|
+
import { AISDKError as AISDKError8 } from "@ai-sdk/provider";
|
1609
|
+
var name8 = "AI_NoSuchToolError";
|
1610
|
+
var marker8 = `vercel.ai.error.${name8}`;
|
1611
|
+
var symbol8 = Symbol.for(marker8);
|
1612
|
+
var _a8;
|
1613
|
+
var NoSuchToolError = class extends AISDKError8 {
|
1614
|
+
constructor({
|
1615
|
+
toolName,
|
1616
|
+
availableTools = void 0,
|
1617
|
+
message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
|
1618
|
+
}) {
|
1619
|
+
super({ name: name8, message });
|
1620
|
+
this[_a8] = true;
|
1621
|
+
this.toolName = toolName;
|
1622
|
+
this.availableTools = availableTools;
|
1623
|
+
}
|
1624
|
+
static isInstance(error) {
|
1625
|
+
return AISDKError8.hasMarker(error, marker8);
|
1626
|
+
}
|
1627
|
+
};
|
1628
|
+
_a8 = symbol8;
|
1629
|
+
|
1630
|
+
// util/is-async-generator.ts
|
1631
|
+
function isAsyncGenerator(value) {
|
1632
|
+
return value != null && typeof value === "object" && Symbol.asyncIterator in value;
|
1633
|
+
}
|
1634
|
+
|
1635
|
+
// util/is-generator.ts
|
1636
|
+
function isGenerator(value) {
|
1637
|
+
return value != null && typeof value === "object" && Symbol.iterator in value;
|
1638
|
+
}
|
1639
|
+
|
1640
|
+
// util/constants.ts
|
1641
|
+
var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
|
1642
|
+
|
1643
|
+
// rsc/streamable-ui/create-suspended-chunk.tsx
|
1644
|
+
import { Suspense } from "react";
|
1645
|
+
import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
|
1646
|
+
var R = [
|
1647
|
+
async ({
|
1648
|
+
c: current,
|
1649
|
+
n: next
|
1650
|
+
}) => {
|
1651
|
+
const chunk = await next;
|
1652
|
+
if (chunk.done) {
|
1653
|
+
return chunk.value;
|
1654
|
+
}
|
1655
|
+
if (chunk.append) {
|
1656
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
1657
|
+
current,
|
1658
|
+
/* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) })
|
1659
|
+
] });
|
1660
|
+
}
|
1661
|
+
return /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) });
|
1662
|
+
}
|
1663
|
+
][0];
|
1664
|
+
function createSuspendedChunk(initialValue) {
|
1665
|
+
const { promise, resolve, reject } = createResolvablePromise();
|
1666
|
+
return {
|
1667
|
+
row: /* @__PURE__ */ jsx2(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx2(R, { c: initialValue, n: promise }) }),
|
1668
|
+
resolve,
|
1669
|
+
reject
|
1670
|
+
};
|
1671
|
+
}
|
1192
1672
|
|
1193
|
-
// rsc/streamable.tsx
|
1673
|
+
// rsc/streamable-ui/create-streamable-ui.tsx
|
1194
1674
|
function createStreamableUI(initialValue) {
|
1195
1675
|
let currentValue = initialValue;
|
1196
1676
|
let closed = false;
|
1197
|
-
let { row, resolve, reject } =
|
1677
|
+
let { row, resolve, reject } = createSuspendedChunk(initialValue);
|
1198
1678
|
function assertStream(method) {
|
1199
1679
|
if (closed) {
|
1200
1680
|
throw new Error(method + ": UI stream is already closed.");
|
@@ -1210,23 +1690,17 @@ function createStreamableUI(initialValue) {
|
|
1210
1690
|
console.warn(
|
1211
1691
|
"The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
|
1212
1692
|
);
|
1213
|
-
},
|
1693
|
+
}, HANGING_STREAM_WARNING_TIME_MS);
|
1214
1694
|
}
|
1215
1695
|
}
|
1216
1696
|
warnUnclosedStream();
|
1217
|
-
const
|
1218
|
-
/**
|
1219
|
-
* The value of the streamable UI. This can be returned from a Server Action and received by the client.
|
1220
|
-
*/
|
1697
|
+
const streamable = {
|
1221
1698
|
value: row,
|
1222
|
-
/**
|
1223
|
-
* This method updates the current UI node. It takes a new UI node and replaces the old one.
|
1224
|
-
*/
|
1225
1699
|
update(value) {
|
1226
1700
|
assertStream(".update()");
|
1227
1701
|
if (value === currentValue) {
|
1228
1702
|
warnUnclosedStream();
|
1229
|
-
return
|
1703
|
+
return streamable;
|
1230
1704
|
}
|
1231
1705
|
const resolvable = createResolvablePromise();
|
1232
1706
|
currentValue = value;
|
@@ -1234,24 +1708,8 @@ function createStreamableUI(initialValue) {
|
|
1234
1708
|
resolve = resolvable.resolve;
|
1235
1709
|
reject = resolvable.reject;
|
1236
1710
|
warnUnclosedStream();
|
1237
|
-
return
|
1711
|
+
return streamable;
|
1238
1712
|
},
|
1239
|
-
/**
|
1240
|
-
* This method is used to append a new UI node to the end of the old one.
|
1241
|
-
* Once appended a new UI node, the previous UI node cannot be updated anymore.
|
1242
|
-
*
|
1243
|
-
* @example
|
1244
|
-
* ```jsx
|
1245
|
-
* const ui = createStreamableUI(<div>hello</div>)
|
1246
|
-
* ui.append(<div>world</div>)
|
1247
|
-
*
|
1248
|
-
* // The UI node will be:
|
1249
|
-
* // <>
|
1250
|
-
* // <div>hello</div>
|
1251
|
-
* // <div>world</div>
|
1252
|
-
* // </>
|
1253
|
-
* ```
|
1254
|
-
*/
|
1255
1713
|
append(value) {
|
1256
1714
|
assertStream(".append()");
|
1257
1715
|
const resolvable = createResolvablePromise();
|
@@ -1260,43 +1718,252 @@ function createStreamableUI(initialValue) {
|
|
1260
1718
|
resolve = resolvable.resolve;
|
1261
1719
|
reject = resolvable.reject;
|
1262
1720
|
warnUnclosedStream();
|
1263
|
-
return
|
1721
|
+
return streamable;
|
1264
1722
|
},
|
1265
|
-
/**
|
1266
|
-
* This method is used to signal that there is an error in the UI stream.
|
1267
|
-
* It will be thrown on the client side and caught by the nearest error boundary component.
|
1268
|
-
*/
|
1269
1723
|
error(error) {
|
1270
1724
|
assertStream(".error()");
|
1271
1725
|
if (warningTimeout) {
|
1272
1726
|
clearTimeout(warningTimeout);
|
1273
1727
|
}
|
1274
|
-
closed = true;
|
1275
|
-
reject(error);
|
1276
|
-
return
|
1277
|
-
},
|
1278
|
-
|
1279
|
-
|
1280
|
-
|
1281
|
-
|
1282
|
-
|
1283
|
-
|
1284
|
-
|
1285
|
-
|
1286
|
-
|
1287
|
-
|
1728
|
+
closed = true;
|
1729
|
+
reject(error);
|
1730
|
+
return streamable;
|
1731
|
+
},
|
1732
|
+
done(...args) {
|
1733
|
+
assertStream(".done()");
|
1734
|
+
if (warningTimeout) {
|
1735
|
+
clearTimeout(warningTimeout);
|
1736
|
+
}
|
1737
|
+
closed = true;
|
1738
|
+
if (args.length) {
|
1739
|
+
resolve({ value: args[0], done: true });
|
1740
|
+
return streamable;
|
1741
|
+
}
|
1742
|
+
resolve({ value: currentValue, done: true });
|
1743
|
+
return streamable;
|
1744
|
+
}
|
1745
|
+
};
|
1746
|
+
return streamable;
|
1747
|
+
}
|
1748
|
+
|
1749
|
+
// rsc/stream-ui/stream-ui.tsx
|
1750
|
+
var defaultTextRenderer = ({ content }) => content;
|
1751
|
+
async function streamUI({
|
1752
|
+
model,
|
1753
|
+
tools,
|
1754
|
+
toolChoice,
|
1755
|
+
system,
|
1756
|
+
prompt,
|
1757
|
+
messages,
|
1758
|
+
maxRetries,
|
1759
|
+
abortSignal,
|
1760
|
+
headers,
|
1761
|
+
initial,
|
1762
|
+
text,
|
1763
|
+
experimental_providerMetadata,
|
1764
|
+
providerOptions = experimental_providerMetadata,
|
1765
|
+
onFinish,
|
1766
|
+
...settings
|
1767
|
+
}) {
|
1768
|
+
if (typeof model === "string") {
|
1769
|
+
throw new Error(
|
1770
|
+
"`model` cannot be a string in `streamUI`. Use the actual model instance instead."
|
1771
|
+
);
|
1772
|
+
}
|
1773
|
+
if ("functions" in settings) {
|
1774
|
+
throw new Error(
|
1775
|
+
"`functions` is not supported in `streamUI`, use `tools` instead."
|
1776
|
+
);
|
1777
|
+
}
|
1778
|
+
if ("provider" in settings) {
|
1779
|
+
throw new Error(
|
1780
|
+
"`provider` is no longer needed in `streamUI`. Use `model` instead."
|
1781
|
+
);
|
1782
|
+
}
|
1783
|
+
if (tools) {
|
1784
|
+
for (const [name9, tool] of Object.entries(tools)) {
|
1785
|
+
if ("render" in tool) {
|
1786
|
+
throw new Error(
|
1787
|
+
"Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name9
|
1788
|
+
);
|
1789
|
+
}
|
1790
|
+
}
|
1791
|
+
}
|
1792
|
+
const ui = createStreamableUI(initial);
|
1793
|
+
const textRender = text || defaultTextRenderer;
|
1794
|
+
let finished;
|
1795
|
+
let finishEvent = null;
|
1796
|
+
async function render({
|
1797
|
+
args,
|
1798
|
+
renderer,
|
1799
|
+
streamableUI,
|
1800
|
+
isLastCall = false
|
1801
|
+
}) {
|
1802
|
+
if (!renderer)
|
1803
|
+
return;
|
1804
|
+
const renderFinished = createResolvablePromise();
|
1805
|
+
finished = finished ? finished.then(() => renderFinished.promise) : renderFinished.promise;
|
1806
|
+
const rendererResult = renderer(...args);
|
1807
|
+
if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {
|
1808
|
+
while (true) {
|
1809
|
+
const { done, value } = await rendererResult.next();
|
1810
|
+
const node = await value;
|
1811
|
+
if (isLastCall && done) {
|
1812
|
+
streamableUI.done(node);
|
1813
|
+
} else {
|
1814
|
+
streamableUI.update(node);
|
1815
|
+
}
|
1816
|
+
if (done)
|
1817
|
+
break;
|
1818
|
+
}
|
1819
|
+
} else {
|
1820
|
+
const node = await rendererResult;
|
1821
|
+
if (isLastCall) {
|
1822
|
+
streamableUI.done(node);
|
1823
|
+
} else {
|
1824
|
+
streamableUI.update(node);
|
1825
|
+
}
|
1826
|
+
}
|
1827
|
+
renderFinished.resolve(void 0);
|
1828
|
+
}
|
1829
|
+
const { retry } = prepareRetries({ maxRetries });
|
1830
|
+
const validatedPrompt = standardizePrompt({
|
1831
|
+
prompt: { system, prompt, messages },
|
1832
|
+
tools: void 0
|
1833
|
+
// streamUI tools don't support multi-modal tool result conversion
|
1834
|
+
});
|
1835
|
+
const result = await retry(
|
1836
|
+
async () => {
|
1837
|
+
var _a9;
|
1838
|
+
return model.doStream({
|
1839
|
+
mode: {
|
1840
|
+
type: "regular",
|
1841
|
+
...prepareToolsAndToolChoice({
|
1842
|
+
tools,
|
1843
|
+
toolChoice,
|
1844
|
+
activeTools: void 0
|
1845
|
+
})
|
1846
|
+
},
|
1847
|
+
...prepareCallSettings(settings),
|
1848
|
+
inputFormat: validatedPrompt.type,
|
1849
|
+
prompt: await convertToLanguageModelPrompt({
|
1850
|
+
prompt: validatedPrompt,
|
1851
|
+
modelSupportsImageUrls: model.supportsImageUrls,
|
1852
|
+
modelSupportsUrl: (_a9 = model.supportsUrl) == null ? void 0 : _a9.bind(model)
|
1853
|
+
// support 'this' context
|
1854
|
+
}),
|
1855
|
+
providerMetadata: providerOptions,
|
1856
|
+
abortSignal,
|
1857
|
+
headers
|
1858
|
+
});
|
1859
|
+
}
|
1860
|
+
);
|
1861
|
+
const [stream, forkedStream] = result.stream.tee();
|
1862
|
+
(async () => {
|
1863
|
+
try {
|
1864
|
+
let content = "";
|
1865
|
+
let hasToolCall = false;
|
1866
|
+
const reader = forkedStream.getReader();
|
1867
|
+
while (true) {
|
1868
|
+
const { done, value } = await reader.read();
|
1869
|
+
if (done)
|
1870
|
+
break;
|
1871
|
+
switch (value.type) {
|
1872
|
+
case "text-delta": {
|
1873
|
+
content += value.textDelta;
|
1874
|
+
render({
|
1875
|
+
renderer: textRender,
|
1876
|
+
args: [{ content, done: false, delta: value.textDelta }],
|
1877
|
+
streamableUI: ui
|
1878
|
+
});
|
1879
|
+
break;
|
1880
|
+
}
|
1881
|
+
case "tool-call-delta": {
|
1882
|
+
hasToolCall = true;
|
1883
|
+
break;
|
1884
|
+
}
|
1885
|
+
case "tool-call": {
|
1886
|
+
const toolName = value.toolName;
|
1887
|
+
if (!tools) {
|
1888
|
+
throw new NoSuchToolError({ toolName });
|
1889
|
+
}
|
1890
|
+
const tool = tools[toolName];
|
1891
|
+
if (!tool) {
|
1892
|
+
throw new NoSuchToolError({
|
1893
|
+
toolName,
|
1894
|
+
availableTools: Object.keys(tools)
|
1895
|
+
});
|
1896
|
+
}
|
1897
|
+
hasToolCall = true;
|
1898
|
+
const parseResult = safeParseJSON({
|
1899
|
+
text: value.args,
|
1900
|
+
schema: tool.parameters
|
1901
|
+
});
|
1902
|
+
if (parseResult.success === false) {
|
1903
|
+
throw new InvalidToolArgumentsError({
|
1904
|
+
toolName,
|
1905
|
+
toolArgs: value.args,
|
1906
|
+
cause: parseResult.error
|
1907
|
+
});
|
1908
|
+
}
|
1909
|
+
render({
|
1910
|
+
renderer: tool.generate,
|
1911
|
+
args: [
|
1912
|
+
parseResult.value,
|
1913
|
+
{
|
1914
|
+
toolName,
|
1915
|
+
toolCallId: value.toolCallId
|
1916
|
+
}
|
1917
|
+
],
|
1918
|
+
streamableUI: ui,
|
1919
|
+
isLastCall: true
|
1920
|
+
});
|
1921
|
+
break;
|
1922
|
+
}
|
1923
|
+
case "error": {
|
1924
|
+
throw value.error;
|
1925
|
+
}
|
1926
|
+
case "finish": {
|
1927
|
+
finishEvent = {
|
1928
|
+
finishReason: value.finishReason,
|
1929
|
+
usage: calculateLanguageModelUsage(value.usage),
|
1930
|
+
warnings: result.warnings,
|
1931
|
+
rawResponse: result.rawResponse
|
1932
|
+
};
|
1933
|
+
break;
|
1934
|
+
}
|
1935
|
+
}
|
1936
|
+
}
|
1937
|
+
if (!hasToolCall) {
|
1938
|
+
render({
|
1939
|
+
renderer: textRender,
|
1940
|
+
args: [{ content, done: true }],
|
1941
|
+
streamableUI: ui,
|
1942
|
+
isLastCall: true
|
1943
|
+
});
|
1288
1944
|
}
|
1289
|
-
|
1290
|
-
if (
|
1291
|
-
|
1292
|
-
|
1945
|
+
await finished;
|
1946
|
+
if (finishEvent && onFinish) {
|
1947
|
+
await onFinish({
|
1948
|
+
...finishEvent,
|
1949
|
+
value: ui.value
|
1950
|
+
});
|
1293
1951
|
}
|
1294
|
-
|
1295
|
-
|
1952
|
+
} catch (error) {
|
1953
|
+
ui.error(error);
|
1296
1954
|
}
|
1955
|
+
})();
|
1956
|
+
return {
|
1957
|
+
...result,
|
1958
|
+
stream,
|
1959
|
+
value: ui.value
|
1297
1960
|
};
|
1298
|
-
return streamable2;
|
1299
1961
|
}
|
1962
|
+
|
1963
|
+
// rsc/streamable-value/streamable-value.ts
|
1964
|
+
var STREAMABLE_VALUE_TYPE = Symbol.for("ui.streamable.value");
|
1965
|
+
|
1966
|
+
// rsc/streamable-value/create-streamable-value.ts
|
1300
1967
|
var STREAMABLE_VALUE_INTERNAL_LOCK = Symbol("streamable.value.lock");
|
1301
1968
|
function createStreamableValue(initialValue) {
|
1302
1969
|
const isReadableStream = initialValue instanceof ReadableStream || typeof initialValue === "object" && initialValue !== null && "getReader" in initialValue && typeof initialValue.getReader === "function" && "locked" in initialValue && typeof initialValue.locked === "boolean";
|
@@ -1356,9 +2023,9 @@ function createStreamableValueImpl(initialValue) {
|
|
1356
2023
|
}
|
1357
2024
|
warningTimeout = setTimeout(() => {
|
1358
2025
|
console.warn(
|
1359
|
-
"The streamable
|
2026
|
+
"The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
|
1360
2027
|
);
|
1361
|
-
},
|
2028
|
+
}, HANGING_STREAM_WARNING_TIME_MS);
|
1362
2029
|
}
|
1363
2030
|
}
|
1364
2031
|
warnUnclosedStream();
|
@@ -1392,25 +2059,13 @@ function createStreamableValueImpl(initialValue) {
|
|
1392
2059
|
}
|
1393
2060
|
currentValue = value;
|
1394
2061
|
}
|
1395
|
-
const
|
1396
|
-
/**
|
1397
|
-
* @internal This is an internal lock to prevent the value from being
|
1398
|
-
* updated by the user.
|
1399
|
-
*/
|
2062
|
+
const streamable = {
|
1400
2063
|
set [STREAMABLE_VALUE_INTERNAL_LOCK](state) {
|
1401
2064
|
locked = state;
|
1402
2065
|
},
|
1403
|
-
/**
|
1404
|
-
* The value of the streamable. This can be returned from a Server Action and
|
1405
|
-
* received by the client. To read the streamed values, use the
|
1406
|
-
* `readStreamableValue` or `useStreamableValue` APIs.
|
1407
|
-
*/
|
1408
2066
|
get value() {
|
1409
2067
|
return createWrapped(true);
|
1410
2068
|
},
|
1411
|
-
/**
|
1412
|
-
* This method updates the current value with a new one.
|
1413
|
-
*/
|
1414
2069
|
update(value) {
|
1415
2070
|
assertStream(".update()");
|
1416
2071
|
const resolvePrevious = resolvable.resolve;
|
@@ -1419,20 +2074,8 @@ function createStreamableValueImpl(initialValue) {
|
|
1419
2074
|
currentPromise = resolvable.promise;
|
1420
2075
|
resolvePrevious(createWrapped());
|
1421
2076
|
warnUnclosedStream();
|
1422
|
-
return
|
2077
|
+
return streamable;
|
1423
2078
|
},
|
1424
|
-
/**
|
1425
|
-
* This method is used to append a delta string to the current value. It
|
1426
|
-
* requires the current value of the streamable to be a string.
|
1427
|
-
*
|
1428
|
-
* @example
|
1429
|
-
* ```jsx
|
1430
|
-
* const streamable = createStreamableValue('hello');
|
1431
|
-
* streamable.append(' world');
|
1432
|
-
*
|
1433
|
-
* // The value will be 'hello world'
|
1434
|
-
* ```
|
1435
|
-
*/
|
1436
2079
|
append(value) {
|
1437
2080
|
assertStream(".append()");
|
1438
2081
|
if (typeof currentValue !== "string" && typeof currentValue !== "undefined") {
|
@@ -1457,13 +2100,8 @@ function createStreamableValueImpl(initialValue) {
|
|
1457
2100
|
currentPromise = resolvable.promise;
|
1458
2101
|
resolvePrevious(createWrapped());
|
1459
2102
|
warnUnclosedStream();
|
1460
|
-
return
|
2103
|
+
return streamable;
|
1461
2104
|
},
|
1462
|
-
/**
|
1463
|
-
* This method is used to signal that there is an error in the value stream.
|
1464
|
-
* It will be thrown on the client side when consumed via
|
1465
|
-
* `readStreamableValue` or `useStreamableValue`.
|
1466
|
-
*/
|
1467
2105
|
error(error) {
|
1468
2106
|
assertStream(".error()");
|
1469
2107
|
if (warningTimeout) {
|
@@ -1473,16 +2111,8 @@ function createStreamableValueImpl(initialValue) {
|
|
1473
2111
|
currentError = error;
|
1474
2112
|
currentPromise = void 0;
|
1475
2113
|
resolvable.resolve({ error });
|
1476
|
-
return
|
2114
|
+
return streamable;
|
1477
2115
|
},
|
1478
|
-
/**
|
1479
|
-
* This method marks the value as finalized. You can either call it without
|
1480
|
-
* any parameters or with a new value as the final state.
|
1481
|
-
* Once called, the value cannot be updated or appended anymore.
|
1482
|
-
*
|
1483
|
-
* This method is always **required** to be called, otherwise the response
|
1484
|
-
* will be stuck in a loading state.
|
1485
|
-
*/
|
1486
2116
|
done(...args) {
|
1487
2117
|
assertStream(".done()");
|
1488
2118
|
if (warningTimeout) {
|
@@ -1493,400 +2123,13 @@ function createStreamableValueImpl(initialValue) {
|
|
1493
2123
|
if (args.length) {
|
1494
2124
|
updateValueStates(args[0]);
|
1495
2125
|
resolvable.resolve(createWrapped());
|
1496
|
-
return
|
2126
|
+
return streamable;
|
1497
2127
|
}
|
1498
2128
|
resolvable.resolve({});
|
1499
|
-
return
|
1500
|
-
}
|
1501
|
-
};
|
1502
|
-
return streamable2;
|
1503
|
-
}
|
1504
|
-
function render(options) {
|
1505
|
-
const ui = createStreamableUI(options.initial);
|
1506
|
-
const text = options.text ? options.text : ({ content }) => content;
|
1507
|
-
const functions = options.functions ? Object.entries(options.functions).map(
|
1508
|
-
([name, { description, parameters }]) => {
|
1509
|
-
return {
|
1510
|
-
name,
|
1511
|
-
description,
|
1512
|
-
parameters: zodToJsonSchema2(parameters)
|
1513
|
-
};
|
1514
|
-
}
|
1515
|
-
) : void 0;
|
1516
|
-
const tools = options.tools ? Object.entries(options.tools).map(
|
1517
|
-
([name, { description, parameters }]) => {
|
1518
|
-
return {
|
1519
|
-
type: "function",
|
1520
|
-
function: {
|
1521
|
-
name,
|
1522
|
-
description,
|
1523
|
-
parameters: zodToJsonSchema2(parameters)
|
1524
|
-
}
|
1525
|
-
};
|
1526
|
-
}
|
1527
|
-
) : void 0;
|
1528
|
-
if (functions && tools) {
|
1529
|
-
throw new Error(
|
1530
|
-
"You can't have both functions and tools defined. Please choose one or the other."
|
1531
|
-
);
|
1532
|
-
}
|
1533
|
-
let finished;
|
1534
|
-
async function handleRender(args, renderer, res) {
|
1535
|
-
if (!renderer)
|
1536
|
-
return;
|
1537
|
-
const resolvable = createResolvablePromise();
|
1538
|
-
if (finished) {
|
1539
|
-
finished = finished.then(() => resolvable.promise);
|
1540
|
-
} else {
|
1541
|
-
finished = resolvable.promise;
|
1542
|
-
}
|
1543
|
-
const value = renderer(args);
|
1544
|
-
if (value instanceof Promise || value && typeof value === "object" && "then" in value && typeof value.then === "function") {
|
1545
|
-
const node = await value;
|
1546
|
-
res.update(node);
|
1547
|
-
resolvable.resolve(void 0);
|
1548
|
-
} else if (value && typeof value === "object" && Symbol.asyncIterator in value) {
|
1549
|
-
const it = value;
|
1550
|
-
while (true) {
|
1551
|
-
const { done, value: value2 } = await it.next();
|
1552
|
-
res.update(value2);
|
1553
|
-
if (done)
|
1554
|
-
break;
|
1555
|
-
}
|
1556
|
-
resolvable.resolve(void 0);
|
1557
|
-
} else if (value && typeof value === "object" && Symbol.iterator in value) {
|
1558
|
-
const it = value;
|
1559
|
-
while (true) {
|
1560
|
-
const { done, value: value2 } = it.next();
|
1561
|
-
res.update(value2);
|
1562
|
-
if (done)
|
1563
|
-
break;
|
1564
|
-
}
|
1565
|
-
resolvable.resolve(void 0);
|
1566
|
-
} else {
|
1567
|
-
res.update(value);
|
1568
|
-
resolvable.resolve(void 0);
|
1569
|
-
}
|
1570
|
-
}
|
1571
|
-
(async () => {
|
1572
|
-
let hasFunction = false;
|
1573
|
-
let content = "";
|
1574
|
-
consumeStream(
|
1575
|
-
OpenAIStream(
|
1576
|
-
await options.provider.chat.completions.create({
|
1577
|
-
model: options.model,
|
1578
|
-
messages: options.messages,
|
1579
|
-
temperature: options.temperature,
|
1580
|
-
stream: true,
|
1581
|
-
...functions ? {
|
1582
|
-
functions
|
1583
|
-
} : {},
|
1584
|
-
...tools ? {
|
1585
|
-
tools
|
1586
|
-
} : {}
|
1587
|
-
}),
|
1588
|
-
{
|
1589
|
-
...functions ? {
|
1590
|
-
async experimental_onFunctionCall(functionCallPayload) {
|
1591
|
-
var _a, _b;
|
1592
|
-
hasFunction = true;
|
1593
|
-
handleRender(
|
1594
|
-
functionCallPayload.arguments,
|
1595
|
-
(_b = (_a = options.functions) == null ? void 0 : _a[functionCallPayload.name]) == null ? void 0 : _b.render,
|
1596
|
-
ui
|
1597
|
-
);
|
1598
|
-
}
|
1599
|
-
} : {},
|
1600
|
-
...tools ? {
|
1601
|
-
async experimental_onToolCall(toolCallPayload) {
|
1602
|
-
var _a, _b;
|
1603
|
-
hasFunction = true;
|
1604
|
-
for (const tool of toolCallPayload.tools) {
|
1605
|
-
handleRender(
|
1606
|
-
tool.func.arguments,
|
1607
|
-
(_b = (_a = options.tools) == null ? void 0 : _a[tool.func.name]) == null ? void 0 : _b.render,
|
1608
|
-
ui
|
1609
|
-
);
|
1610
|
-
}
|
1611
|
-
}
|
1612
|
-
} : {},
|
1613
|
-
onText(chunk) {
|
1614
|
-
content += chunk;
|
1615
|
-
handleRender({ content, done: false, delta: chunk }, text, ui);
|
1616
|
-
},
|
1617
|
-
async onFinal() {
|
1618
|
-
if (hasFunction) {
|
1619
|
-
await finished;
|
1620
|
-
ui.done();
|
1621
|
-
return;
|
1622
|
-
}
|
1623
|
-
handleRender({ content, done: true }, text, ui);
|
1624
|
-
await finished;
|
1625
|
-
ui.done();
|
1626
|
-
}
|
1627
|
-
}
|
1628
|
-
)
|
1629
|
-
);
|
1630
|
-
})();
|
1631
|
-
return ui.value;
|
1632
|
-
}
|
1633
|
-
|
1634
|
-
// rsc/stream-ui/stream-ui.tsx
|
1635
|
-
import {
|
1636
|
-
InvalidToolArgumentsError,
|
1637
|
-
NoSuchToolError
|
1638
|
-
} from "@ai-sdk/provider";
|
1639
|
-
import { safeParseJSON } from "@ai-sdk/provider-utils";
|
1640
|
-
var defaultTextRenderer = ({ content }) => content;
|
1641
|
-
async function streamUI({
|
1642
|
-
model,
|
1643
|
-
tools,
|
1644
|
-
system,
|
1645
|
-
prompt,
|
1646
|
-
messages,
|
1647
|
-
maxRetries,
|
1648
|
-
abortSignal,
|
1649
|
-
initial,
|
1650
|
-
text,
|
1651
|
-
...settings
|
1652
|
-
}) {
|
1653
|
-
if (typeof model === "string") {
|
1654
|
-
throw new Error(
|
1655
|
-
"`model` cannot be a string in `streamUI`. Use the actual model instance instead."
|
1656
|
-
);
|
1657
|
-
}
|
1658
|
-
if ("functions" in settings) {
|
1659
|
-
throw new Error(
|
1660
|
-
"`functions` is not supported in `streamUI`, use `tools` instead."
|
1661
|
-
);
|
1662
|
-
}
|
1663
|
-
if ("provider" in settings) {
|
1664
|
-
throw new Error(
|
1665
|
-
"`provider` is no longer needed in `streamUI`. Use `model` instead."
|
1666
|
-
);
|
1667
|
-
}
|
1668
|
-
if (tools) {
|
1669
|
-
for (const [name, tool] of Object.entries(tools)) {
|
1670
|
-
if ("render" in tool) {
|
1671
|
-
throw new Error(
|
1672
|
-
"Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name
|
1673
|
-
);
|
1674
|
-
}
|
1675
|
-
}
|
1676
|
-
}
|
1677
|
-
const ui = createStreamableUI(initial);
|
1678
|
-
const textRender = text || defaultTextRenderer;
|
1679
|
-
let finished;
|
1680
|
-
async function handleRender(args, renderer, res) {
|
1681
|
-
if (!renderer)
|
1682
|
-
return;
|
1683
|
-
const resolvable = createResolvablePromise();
|
1684
|
-
if (finished) {
|
1685
|
-
finished = finished.then(() => resolvable.promise);
|
1686
|
-
} else {
|
1687
|
-
finished = resolvable.promise;
|
1688
|
-
}
|
1689
|
-
const value = renderer(...args);
|
1690
|
-
if (value instanceof Promise || value && typeof value === "object" && "then" in value && typeof value.then === "function") {
|
1691
|
-
const node = await value;
|
1692
|
-
res.update(node);
|
1693
|
-
resolvable.resolve(void 0);
|
1694
|
-
} else if (value && typeof value === "object" && Symbol.asyncIterator in value) {
|
1695
|
-
const it = value;
|
1696
|
-
while (true) {
|
1697
|
-
const { done, value: value2 } = await it.next();
|
1698
|
-
res.update(value2);
|
1699
|
-
if (done)
|
1700
|
-
break;
|
1701
|
-
}
|
1702
|
-
resolvable.resolve(void 0);
|
1703
|
-
} else if (value && typeof value === "object" && Symbol.iterator in value) {
|
1704
|
-
const it = value;
|
1705
|
-
while (true) {
|
1706
|
-
const { done, value: value2 } = it.next();
|
1707
|
-
res.update(value2);
|
1708
|
-
if (done)
|
1709
|
-
break;
|
1710
|
-
}
|
1711
|
-
resolvable.resolve(void 0);
|
1712
|
-
} else {
|
1713
|
-
res.update(value);
|
1714
|
-
resolvable.resolve(void 0);
|
1715
|
-
}
|
1716
|
-
}
|
1717
|
-
const retry = retryWithExponentialBackoff({ maxRetries });
|
1718
|
-
const validatedPrompt = getValidatedPrompt({ system, prompt, messages });
|
1719
|
-
const result = await retry(
|
1720
|
-
() => model.doStream({
|
1721
|
-
mode: {
|
1722
|
-
type: "regular",
|
1723
|
-
tools: tools == null ? void 0 : Object.entries(tools).map(([name, tool]) => ({
|
1724
|
-
type: "function",
|
1725
|
-
name,
|
1726
|
-
description: tool.description,
|
1727
|
-
parameters: convertZodToJSONSchema(tool.parameters)
|
1728
|
-
}))
|
1729
|
-
},
|
1730
|
-
...prepareCallSettings(settings),
|
1731
|
-
inputFormat: validatedPrompt.type,
|
1732
|
-
prompt: convertToLanguageModelPrompt(validatedPrompt),
|
1733
|
-
abortSignal
|
1734
|
-
})
|
1735
|
-
);
|
1736
|
-
const [stream, forkedStream] = result.stream.tee();
|
1737
|
-
(async () => {
|
1738
|
-
try {
|
1739
|
-
let content = "";
|
1740
|
-
let hasToolCall = false;
|
1741
|
-
const reader = forkedStream.getReader();
|
1742
|
-
while (true) {
|
1743
|
-
const { done, value } = await reader.read();
|
1744
|
-
if (done)
|
1745
|
-
break;
|
1746
|
-
switch (value.type) {
|
1747
|
-
case "text-delta": {
|
1748
|
-
content += value.textDelta;
|
1749
|
-
handleRender(
|
1750
|
-
[{ content, done: false, delta: value.textDelta }],
|
1751
|
-
textRender,
|
1752
|
-
ui
|
1753
|
-
);
|
1754
|
-
break;
|
1755
|
-
}
|
1756
|
-
case "tool-call-delta": {
|
1757
|
-
hasToolCall = true;
|
1758
|
-
break;
|
1759
|
-
}
|
1760
|
-
case "tool-call": {
|
1761
|
-
const toolName = value.toolName;
|
1762
|
-
if (!tools) {
|
1763
|
-
throw new NoSuchToolError({ toolName });
|
1764
|
-
}
|
1765
|
-
const tool = tools[toolName];
|
1766
|
-
if (!tool) {
|
1767
|
-
throw new NoSuchToolError({
|
1768
|
-
toolName,
|
1769
|
-
availableTools: Object.keys(tools)
|
1770
|
-
});
|
1771
|
-
}
|
1772
|
-
const parseResult = safeParseJSON({
|
1773
|
-
text: value.args,
|
1774
|
-
schema: tool.parameters
|
1775
|
-
});
|
1776
|
-
if (parseResult.success === false) {
|
1777
|
-
throw new InvalidToolArgumentsError({
|
1778
|
-
toolName,
|
1779
|
-
toolArgs: value.args,
|
1780
|
-
cause: parseResult.error
|
1781
|
-
});
|
1782
|
-
}
|
1783
|
-
handleRender(
|
1784
|
-
[
|
1785
|
-
parseResult.value,
|
1786
|
-
{
|
1787
|
-
toolName,
|
1788
|
-
toolCallId: value.toolCallId
|
1789
|
-
}
|
1790
|
-
],
|
1791
|
-
tool.generate,
|
1792
|
-
ui
|
1793
|
-
);
|
1794
|
-
break;
|
1795
|
-
}
|
1796
|
-
case "error": {
|
1797
|
-
throw value.error;
|
1798
|
-
}
|
1799
|
-
case "finish": {
|
1800
|
-
}
|
1801
|
-
}
|
1802
|
-
}
|
1803
|
-
if (hasToolCall) {
|
1804
|
-
await finished;
|
1805
|
-
ui.done();
|
1806
|
-
} else {
|
1807
|
-
handleRender([{ content, done: true }], textRender, ui);
|
1808
|
-
await finished;
|
1809
|
-
ui.done();
|
1810
|
-
}
|
1811
|
-
} catch (error) {
|
1812
|
-
ui.error(error);
|
1813
|
-
}
|
1814
|
-
})();
|
1815
|
-
return {
|
1816
|
-
...result,
|
1817
|
-
stream,
|
1818
|
-
value: ui.value
|
1819
|
-
};
|
1820
|
-
}
|
1821
|
-
|
1822
|
-
// rsc/provider.tsx
|
1823
|
-
import * as React2 from "react";
|
1824
|
-
import { InternalAIProvider } from "./rsc-shared.mjs";
|
1825
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
1826
|
-
async function innerAction({
|
1827
|
-
action,
|
1828
|
-
options
|
1829
|
-
}, state, ...args) {
|
1830
|
-
"use server";
|
1831
|
-
return await withAIState(
|
1832
|
-
{
|
1833
|
-
state,
|
1834
|
-
options
|
1835
|
-
},
|
1836
|
-
async () => {
|
1837
|
-
const result = await action(...args);
|
1838
|
-
sealMutableAIState();
|
1839
|
-
return [getAIStateDeltaPromise(), result];
|
1840
|
-
}
|
1841
|
-
);
|
1842
|
-
}
|
1843
|
-
function wrapAction(action, options) {
|
1844
|
-
return innerAction.bind(null, { action, options });
|
1845
|
-
}
|
1846
|
-
function createAI({
|
1847
|
-
actions,
|
1848
|
-
initialAIState,
|
1849
|
-
initialUIState,
|
1850
|
-
onSetAIState,
|
1851
|
-
onGetUIState
|
1852
|
-
}) {
|
1853
|
-
const wrappedActions = {};
|
1854
|
-
for (const name in actions) {
|
1855
|
-
wrappedActions[name] = wrapAction(actions[name], {
|
1856
|
-
onSetAIState
|
1857
|
-
});
|
1858
|
-
}
|
1859
|
-
const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
|
1860
|
-
const AI = async (props) => {
|
1861
|
-
var _a, _b;
|
1862
|
-
if ("useState" in React2) {
|
1863
|
-
throw new Error(
|
1864
|
-
"This component can only be used inside Server Components."
|
1865
|
-
);
|
1866
|
-
}
|
1867
|
-
let uiState = (_a = props.initialUIState) != null ? _a : initialUIState;
|
1868
|
-
let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
|
1869
|
-
let aiStateDelta = void 0;
|
1870
|
-
if (wrappedSyncUIState) {
|
1871
|
-
const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
|
1872
|
-
if (newUIState !== void 0) {
|
1873
|
-
aiStateDelta = newAIStateDelta;
|
1874
|
-
uiState = newUIState;
|
1875
|
-
}
|
2129
|
+
return streamable;
|
1876
2130
|
}
|
1877
|
-
return /* @__PURE__ */ jsx2(
|
1878
|
-
InternalAIProvider,
|
1879
|
-
{
|
1880
|
-
wrappedActions,
|
1881
|
-
wrappedSyncUIState,
|
1882
|
-
initialUIState: uiState,
|
1883
|
-
initialAIState: aiState,
|
1884
|
-
initialAIStatePatch: aiStateDelta,
|
1885
|
-
children: props.children
|
1886
|
-
}
|
1887
|
-
);
|
1888
2131
|
};
|
1889
|
-
return
|
2132
|
+
return streamable;
|
1890
2133
|
}
|
1891
2134
|
export {
|
1892
2135
|
createAI,
|
@@ -1894,7 +2137,6 @@ export {
|
|
1894
2137
|
createStreamableValue,
|
1895
2138
|
getAIState,
|
1896
2139
|
getMutableAIState,
|
1897
|
-
render,
|
1898
2140
|
streamUI
|
1899
2141
|
};
|
1900
2142
|
//# sourceMappingURL=rsc-server.mjs.map
|