@eko-ai/eko 2.0.3-alpha.2 → 2.0.3-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/base.d.ts +4 -6
- package/dist/agent/base.d.ts.map +1 -1
- package/dist/agent/chat.d.ts +1 -0
- package/dist/agent/chat.d.ts.map +1 -1
- package/dist/agent/computer.d.ts +1 -0
- package/dist/agent/computer.d.ts.map +1 -1
- package/dist/agent/file.d.ts +1 -0
- package/dist/agent/file.d.ts.map +1 -1
- package/dist/agent/shell.d.ts +1 -0
- package/dist/agent/shell.d.ts.map +1 -1
- package/dist/agent/timer.d.ts +1 -0
- package/dist/agent/timer.d.ts.map +1 -1
- package/dist/common/utils.d.ts +1 -1
- package/dist/common/utils.d.ts.map +1 -1
- package/dist/config/index.d.ts +1 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/index.cjs.js +2813 -643
- package/dist/index.esm.js +2813 -643
- package/dist/llm/index.d.ts.map +1 -1
- package/dist/memory/index.d.ts +9 -0
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/snapshot.d.ts +13 -0
- package/dist/memory/snapshot.d.ts.map +1 -0
- package/dist/tools/foreach_task.d.ts +1 -0
- package/dist/tools/foreach_task.d.ts.map +1 -1
- package/dist/tools/human_interact.d.ts +1 -0
- package/dist/tools/human_interact.d.ts.map +1 -1
- package/dist/tools/task_node_status.d.ts +1 -0
- package/dist/tools/task_node_status.d.ts.map +1 -1
- package/dist/tools/variable_storage.d.ts +1 -0
- package/dist/tools/variable_storage.d.ts.map +1 -1
- package/dist/tools/watch_trigger.d.ts +1 -0
- package/dist/tools/watch_trigger.d.ts.map +1 -1
- package/dist/types/llm.types.d.ts +1 -1
- package/dist/types/llm.types.d.ts.map +1 -1
- package/package.json +2 -1
package/dist/index.cjs.js
CHANGED
|
@@ -7,8 +7,9 @@ var buffer = require('buffer');
|
|
|
7
7
|
const config = {
|
|
8
8
|
name: "Fellou",
|
|
9
9
|
platform: "mac",
|
|
10
|
-
maxReactNum:
|
|
11
|
-
maxTokens: 16000
|
|
10
|
+
maxReactNum: 200,
|
|
11
|
+
maxTokens: 16000,
|
|
12
|
+
compressThreshold: 60,
|
|
12
13
|
};
|
|
13
14
|
|
|
14
15
|
var LogLevel;
|
|
@@ -165,10 +166,10 @@ class AgentContext {
|
|
|
165
166
|
}
|
|
166
167
|
|
|
167
168
|
// src/errors/ai-sdk-error.ts
|
|
168
|
-
var marker = "vercel.ai.error";
|
|
169
|
-
var symbol = Symbol.for(marker);
|
|
170
|
-
var _a;
|
|
171
|
-
var _AISDKError = class _AISDKError extends Error {
|
|
169
|
+
var marker$1 = "vercel.ai.error";
|
|
170
|
+
var symbol$1 = Symbol.for(marker$1);
|
|
171
|
+
var _a$1;
|
|
172
|
+
var _AISDKError$1 = class _AISDKError extends Error {
|
|
172
173
|
/**
|
|
173
174
|
* Creates an AI SDK Error.
|
|
174
175
|
*
|
|
@@ -183,7 +184,7 @@ var _AISDKError = class _AISDKError extends Error {
|
|
|
183
184
|
cause
|
|
184
185
|
}) {
|
|
185
186
|
super(message);
|
|
186
|
-
this[_a] = true;
|
|
187
|
+
this[_a$1] = true;
|
|
187
188
|
this.name = name14;
|
|
188
189
|
this.cause = cause;
|
|
189
190
|
}
|
|
@@ -193,22 +194,22 @@ var _AISDKError = class _AISDKError extends Error {
|
|
|
193
194
|
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
194
195
|
*/
|
|
195
196
|
static isInstance(error) {
|
|
196
|
-
return _AISDKError.hasMarker(error, marker);
|
|
197
|
+
return _AISDKError.hasMarker(error, marker$1);
|
|
197
198
|
}
|
|
198
199
|
static hasMarker(error, marker15) {
|
|
199
200
|
const markerSymbol = Symbol.for(marker15);
|
|
200
201
|
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
201
202
|
}
|
|
202
203
|
};
|
|
203
|
-
_a = symbol;
|
|
204
|
-
var AISDKError = _AISDKError;
|
|
204
|
+
_a$1 = symbol$1;
|
|
205
|
+
var AISDKError$1 = _AISDKError$1;
|
|
205
206
|
|
|
206
207
|
// src/errors/api-call-error.ts
|
|
207
|
-
var name = "AI_APICallError";
|
|
208
|
-
var marker2 = `vercel.ai.error.${name}`;
|
|
209
|
-
var symbol2 = Symbol.for(marker2);
|
|
210
|
-
var _a2;
|
|
211
|
-
var APICallError = class extends AISDKError {
|
|
208
|
+
var name$1 = "AI_APICallError";
|
|
209
|
+
var marker2$1 = `vercel.ai.error.${name$1}`;
|
|
210
|
+
var symbol2$1 = Symbol.for(marker2$1);
|
|
211
|
+
var _a2$1;
|
|
212
|
+
var APICallError$1 = class APICallError extends AISDKError$1 {
|
|
212
213
|
constructor({
|
|
213
214
|
message,
|
|
214
215
|
url,
|
|
@@ -224,8 +225,8 @@ var APICallError = class extends AISDKError {
|
|
|
224
225
|
// server error
|
|
225
226
|
data
|
|
226
227
|
}) {
|
|
227
|
-
super({ name, message, cause });
|
|
228
|
-
this[_a2] = true;
|
|
228
|
+
super({ name: name$1, message, cause });
|
|
229
|
+
this[_a2$1] = true;
|
|
229
230
|
this.url = url;
|
|
230
231
|
this.requestBodyValues = requestBodyValues;
|
|
231
232
|
this.statusCode = statusCode;
|
|
@@ -235,30 +236,30 @@ var APICallError = class extends AISDKError {
|
|
|
235
236
|
this.data = data;
|
|
236
237
|
}
|
|
237
238
|
static isInstance(error) {
|
|
238
|
-
return AISDKError.hasMarker(error, marker2);
|
|
239
|
+
return AISDKError$1.hasMarker(error, marker2$1);
|
|
239
240
|
}
|
|
240
241
|
};
|
|
241
|
-
_a2 = symbol2;
|
|
242
|
+
_a2$1 = symbol2$1;
|
|
242
243
|
|
|
243
244
|
// src/errors/empty-response-body-error.ts
|
|
244
|
-
var name2 = "AI_EmptyResponseBodyError";
|
|
245
|
-
var marker3 = `vercel.ai.error.${name2}`;
|
|
246
|
-
var symbol3 = Symbol.for(marker3);
|
|
247
|
-
var _a3;
|
|
248
|
-
var EmptyResponseBodyError = class extends AISDKError {
|
|
245
|
+
var name2$1 = "AI_EmptyResponseBodyError";
|
|
246
|
+
var marker3$1 = `vercel.ai.error.${name2$1}`;
|
|
247
|
+
var symbol3$1 = Symbol.for(marker3$1);
|
|
248
|
+
var _a3$1;
|
|
249
|
+
var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 {
|
|
249
250
|
// used in isInstance
|
|
250
251
|
constructor({ message = "Empty response body" } = {}) {
|
|
251
|
-
super({ name: name2, message });
|
|
252
|
-
this[_a3] = true;
|
|
252
|
+
super({ name: name2$1, message });
|
|
253
|
+
this[_a3$1] = true;
|
|
253
254
|
}
|
|
254
255
|
static isInstance(error) {
|
|
255
|
-
return AISDKError.hasMarker(error, marker3);
|
|
256
|
+
return AISDKError$1.hasMarker(error, marker3$1);
|
|
256
257
|
}
|
|
257
258
|
};
|
|
258
|
-
_a3 = symbol3;
|
|
259
|
+
_a3$1 = symbol3$1;
|
|
259
260
|
|
|
260
261
|
// src/errors/get-error-message.ts
|
|
261
|
-
function getErrorMessage(error) {
|
|
262
|
+
function getErrorMessage$1(error) {
|
|
262
263
|
if (error == null) {
|
|
263
264
|
return "unknown error";
|
|
264
265
|
}
|
|
@@ -272,119 +273,119 @@ function getErrorMessage(error) {
|
|
|
272
273
|
}
|
|
273
274
|
|
|
274
275
|
// src/errors/invalid-argument-error.ts
|
|
275
|
-
var name3 = "AI_InvalidArgumentError";
|
|
276
|
-
var marker4 = `vercel.ai.error.${name3}`;
|
|
277
|
-
var symbol4 = Symbol.for(marker4);
|
|
278
|
-
var _a4;
|
|
279
|
-
var InvalidArgumentError = class extends AISDKError {
|
|
276
|
+
var name3$1 = "AI_InvalidArgumentError";
|
|
277
|
+
var marker4$1 = `vercel.ai.error.${name3$1}`;
|
|
278
|
+
var symbol4$1 = Symbol.for(marker4$1);
|
|
279
|
+
var _a4$1;
|
|
280
|
+
var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
|
|
280
281
|
constructor({
|
|
281
282
|
message,
|
|
282
283
|
cause,
|
|
283
284
|
argument
|
|
284
285
|
}) {
|
|
285
|
-
super({ name: name3, message, cause });
|
|
286
|
-
this[_a4] = true;
|
|
286
|
+
super({ name: name3$1, message, cause });
|
|
287
|
+
this[_a4$1] = true;
|
|
287
288
|
this.argument = argument;
|
|
288
289
|
}
|
|
289
290
|
static isInstance(error) {
|
|
290
|
-
return AISDKError.hasMarker(error, marker4);
|
|
291
|
+
return AISDKError$1.hasMarker(error, marker4$1);
|
|
291
292
|
}
|
|
292
293
|
};
|
|
293
|
-
_a4 = symbol4;
|
|
294
|
+
_a4$1 = symbol4$1;
|
|
294
295
|
|
|
295
296
|
// src/errors/invalid-prompt-error.ts
|
|
296
|
-
var name4 = "AI_InvalidPromptError";
|
|
297
|
-
var marker5 = `vercel.ai.error.${name4}`;
|
|
298
|
-
var symbol5 = Symbol.for(marker5);
|
|
299
|
-
var _a5;
|
|
300
|
-
var InvalidPromptError = class extends AISDKError {
|
|
297
|
+
var name4$1 = "AI_InvalidPromptError";
|
|
298
|
+
var marker5$1 = `vercel.ai.error.${name4$1}`;
|
|
299
|
+
var symbol5$1 = Symbol.for(marker5$1);
|
|
300
|
+
var _a5$1;
|
|
301
|
+
var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 {
|
|
301
302
|
constructor({
|
|
302
303
|
prompt,
|
|
303
304
|
message,
|
|
304
305
|
cause
|
|
305
306
|
}) {
|
|
306
|
-
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
307
|
-
this[_a5] = true;
|
|
307
|
+
super({ name: name4$1, message: `Invalid prompt: ${message}`, cause });
|
|
308
|
+
this[_a5$1] = true;
|
|
308
309
|
this.prompt = prompt;
|
|
309
310
|
}
|
|
310
311
|
static isInstance(error) {
|
|
311
|
-
return AISDKError.hasMarker(error, marker5);
|
|
312
|
+
return AISDKError$1.hasMarker(error, marker5$1);
|
|
312
313
|
}
|
|
313
314
|
};
|
|
314
|
-
_a5 = symbol5;
|
|
315
|
+
_a5$1 = symbol5$1;
|
|
315
316
|
|
|
316
317
|
// src/errors/invalid-response-data-error.ts
|
|
317
|
-
var name5 = "AI_InvalidResponseDataError";
|
|
318
|
-
var marker6 = `vercel.ai.error.${name5}`;
|
|
319
|
-
var symbol6 = Symbol.for(marker6);
|
|
320
|
-
var _a6;
|
|
321
|
-
var InvalidResponseDataError = class extends AISDKError {
|
|
318
|
+
var name5$1 = "AI_InvalidResponseDataError";
|
|
319
|
+
var marker6$1 = `vercel.ai.error.${name5$1}`;
|
|
320
|
+
var symbol6$1 = Symbol.for(marker6$1);
|
|
321
|
+
var _a6$1;
|
|
322
|
+
var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 {
|
|
322
323
|
constructor({
|
|
323
324
|
data,
|
|
324
325
|
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
325
326
|
}) {
|
|
326
|
-
super({ name: name5, message });
|
|
327
|
-
this[_a6] = true;
|
|
327
|
+
super({ name: name5$1, message });
|
|
328
|
+
this[_a6$1] = true;
|
|
328
329
|
this.data = data;
|
|
329
330
|
}
|
|
330
331
|
static isInstance(error) {
|
|
331
|
-
return AISDKError.hasMarker(error, marker6);
|
|
332
|
+
return AISDKError$1.hasMarker(error, marker6$1);
|
|
332
333
|
}
|
|
333
334
|
};
|
|
334
|
-
_a6 = symbol6;
|
|
335
|
+
_a6$1 = symbol6$1;
|
|
335
336
|
|
|
336
337
|
// src/errors/json-parse-error.ts
|
|
337
|
-
var name6 = "AI_JSONParseError";
|
|
338
|
-
var marker7 = `vercel.ai.error.${name6}`;
|
|
339
|
-
var symbol7 = Symbol.for(marker7);
|
|
340
|
-
var _a7;
|
|
341
|
-
var JSONParseError = class extends AISDKError {
|
|
338
|
+
var name6$1 = "AI_JSONParseError";
|
|
339
|
+
var marker7$1 = `vercel.ai.error.${name6$1}`;
|
|
340
|
+
var symbol7$1 = Symbol.for(marker7$1);
|
|
341
|
+
var _a7$1;
|
|
342
|
+
var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
|
|
342
343
|
constructor({ text, cause }) {
|
|
343
344
|
super({
|
|
344
|
-
name: name6,
|
|
345
|
+
name: name6$1,
|
|
345
346
|
message: `JSON parsing failed: Text: ${text}.
|
|
346
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
347
|
+
Error message: ${getErrorMessage$1(cause)}`,
|
|
347
348
|
cause
|
|
348
349
|
});
|
|
349
|
-
this[_a7] = true;
|
|
350
|
+
this[_a7$1] = true;
|
|
350
351
|
this.text = text;
|
|
351
352
|
}
|
|
352
353
|
static isInstance(error) {
|
|
353
|
-
return AISDKError.hasMarker(error, marker7);
|
|
354
|
+
return AISDKError$1.hasMarker(error, marker7$1);
|
|
354
355
|
}
|
|
355
356
|
};
|
|
356
|
-
_a7 = symbol7;
|
|
357
|
+
_a7$1 = symbol7$1;
|
|
357
358
|
|
|
358
359
|
// src/errors/load-api-key-error.ts
|
|
359
|
-
var name7 = "AI_LoadAPIKeyError";
|
|
360
|
-
var marker8 = `vercel.ai.error.${name7}`;
|
|
361
|
-
var symbol8 = Symbol.for(marker8);
|
|
362
|
-
var _a8;
|
|
363
|
-
var LoadAPIKeyError = class extends AISDKError {
|
|
360
|
+
var name7$1 = "AI_LoadAPIKeyError";
|
|
361
|
+
var marker8$1 = `vercel.ai.error.${name7$1}`;
|
|
362
|
+
var symbol8$1 = Symbol.for(marker8$1);
|
|
363
|
+
var _a8$1;
|
|
364
|
+
var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 {
|
|
364
365
|
// used in isInstance
|
|
365
366
|
constructor({ message }) {
|
|
366
|
-
super({ name: name7, message });
|
|
367
|
-
this[_a8] = true;
|
|
367
|
+
super({ name: name7$1, message });
|
|
368
|
+
this[_a8$1] = true;
|
|
368
369
|
}
|
|
369
370
|
static isInstance(error) {
|
|
370
|
-
return AISDKError.hasMarker(error, marker8);
|
|
371
|
+
return AISDKError$1.hasMarker(error, marker8$1);
|
|
371
372
|
}
|
|
372
373
|
};
|
|
373
|
-
_a8 = symbol8;
|
|
374
|
+
_a8$1 = symbol8$1;
|
|
374
375
|
|
|
375
376
|
// src/errors/load-setting-error.ts
|
|
376
377
|
var name8 = "AI_LoadSettingError";
|
|
377
378
|
var marker9 = `vercel.ai.error.${name8}`;
|
|
378
379
|
var symbol9 = Symbol.for(marker9);
|
|
379
380
|
var _a9;
|
|
380
|
-
var LoadSettingError = class extends AISDKError {
|
|
381
|
+
var LoadSettingError = class extends AISDKError$1 {
|
|
381
382
|
// used in isInstance
|
|
382
383
|
constructor({ message }) {
|
|
383
384
|
super({ name: name8, message });
|
|
384
385
|
this[_a9] = true;
|
|
385
386
|
}
|
|
386
387
|
static isInstance(error) {
|
|
387
|
-
return AISDKError.hasMarker(error, marker9);
|
|
388
|
+
return AISDKError$1.hasMarker(error, marker9);
|
|
388
389
|
}
|
|
389
390
|
};
|
|
390
391
|
_a9 = symbol9;
|
|
@@ -394,7 +395,7 @@ var name10 = "AI_NoSuchModelError";
|
|
|
394
395
|
var marker11 = `vercel.ai.error.${name10}`;
|
|
395
396
|
var symbol11 = Symbol.for(marker11);
|
|
396
397
|
var _a11;
|
|
397
|
-
var NoSuchModelError = class extends AISDKError {
|
|
398
|
+
var NoSuchModelError = class extends AISDKError$1 {
|
|
398
399
|
constructor({
|
|
399
400
|
errorName = name10,
|
|
400
401
|
modelId,
|
|
@@ -407,7 +408,7 @@ var NoSuchModelError = class extends AISDKError {
|
|
|
407
408
|
this.modelType = modelType;
|
|
408
409
|
}
|
|
409
410
|
static isInstance(error) {
|
|
410
|
-
return AISDKError.hasMarker(error, marker11);
|
|
411
|
+
return AISDKError$1.hasMarker(error, marker11);
|
|
411
412
|
}
|
|
412
413
|
};
|
|
413
414
|
_a11 = symbol11;
|
|
@@ -417,7 +418,7 @@ var name11 = "AI_TooManyEmbeddingValuesForCallError";
|
|
|
417
418
|
var marker12 = `vercel.ai.error.${name11}`;
|
|
418
419
|
var symbol12 = Symbol.for(marker12);
|
|
419
420
|
var _a12;
|
|
420
|
-
var TooManyEmbeddingValuesForCallError = class extends AISDKError {
|
|
421
|
+
var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
|
|
421
422
|
constructor(options) {
|
|
422
423
|
super({
|
|
423
424
|
name: name11,
|
|
@@ -430,29 +431,29 @@ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
|
|
|
430
431
|
this.values = options.values;
|
|
431
432
|
}
|
|
432
433
|
static isInstance(error) {
|
|
433
|
-
return AISDKError.hasMarker(error, marker12);
|
|
434
|
+
return AISDKError$1.hasMarker(error, marker12);
|
|
434
435
|
}
|
|
435
436
|
};
|
|
436
437
|
_a12 = symbol12;
|
|
437
438
|
|
|
438
439
|
// src/errors/type-validation-error.ts
|
|
439
|
-
var name12 = "AI_TypeValidationError";
|
|
440
|
-
var marker13 = `vercel.ai.error.${name12}`;
|
|
441
|
-
var symbol13 = Symbol.for(marker13);
|
|
442
|
-
var _a13;
|
|
443
|
-
var _TypeValidationError = class _TypeValidationError extends AISDKError {
|
|
440
|
+
var name12$1 = "AI_TypeValidationError";
|
|
441
|
+
var marker13$1 = `vercel.ai.error.${name12$1}`;
|
|
442
|
+
var symbol13$1 = Symbol.for(marker13$1);
|
|
443
|
+
var _a13$1;
|
|
444
|
+
var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 {
|
|
444
445
|
constructor({ value, cause }) {
|
|
445
446
|
super({
|
|
446
|
-
name: name12,
|
|
447
|
+
name: name12$1,
|
|
447
448
|
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
448
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
449
|
+
Error message: ${getErrorMessage$1(cause)}`,
|
|
449
450
|
cause
|
|
450
451
|
});
|
|
451
|
-
this[_a13] = true;
|
|
452
|
+
this[_a13$1] = true;
|
|
452
453
|
this.value = value;
|
|
453
454
|
}
|
|
454
455
|
static isInstance(error) {
|
|
455
|
-
return AISDKError.hasMarker(error, marker13);
|
|
456
|
+
return AISDKError$1.hasMarker(error, marker13$1);
|
|
456
457
|
}
|
|
457
458
|
/**
|
|
458
459
|
* Wraps an error into a TypeValidationError.
|
|
@@ -471,28 +472,28 @@ Error message: ${getErrorMessage(cause)}`,
|
|
|
471
472
|
return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
|
|
472
473
|
}
|
|
473
474
|
};
|
|
474
|
-
_a13 = symbol13;
|
|
475
|
-
var TypeValidationError = _TypeValidationError;
|
|
475
|
+
_a13$1 = symbol13$1;
|
|
476
|
+
var TypeValidationError$1 = _TypeValidationError$1;
|
|
476
477
|
|
|
477
478
|
// src/errors/unsupported-functionality-error.ts
|
|
478
|
-
var name13 = "AI_UnsupportedFunctionalityError";
|
|
479
|
-
var marker14 = `vercel.ai.error.${name13}`;
|
|
480
|
-
var symbol14 = Symbol.for(marker14);
|
|
481
|
-
var _a14;
|
|
482
|
-
var UnsupportedFunctionalityError = class extends AISDKError {
|
|
479
|
+
var name13$1 = "AI_UnsupportedFunctionalityError";
|
|
480
|
+
var marker14$1 = `vercel.ai.error.${name13$1}`;
|
|
481
|
+
var symbol14$1 = Symbol.for(marker14$1);
|
|
482
|
+
var _a14$1;
|
|
483
|
+
var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 {
|
|
483
484
|
constructor({
|
|
484
485
|
functionality,
|
|
485
486
|
message = `'${functionality}' functionality not supported.`
|
|
486
487
|
}) {
|
|
487
|
-
super({ name: name13, message });
|
|
488
|
-
this[_a14] = true;
|
|
488
|
+
super({ name: name13$1, message });
|
|
489
|
+
this[_a14$1] = true;
|
|
489
490
|
this.functionality = functionality;
|
|
490
491
|
}
|
|
491
492
|
static isInstance(error) {
|
|
492
|
-
return AISDKError.hasMarker(error, marker14);
|
|
493
|
+
return AISDKError$1.hasMarker(error, marker14$1);
|
|
493
494
|
}
|
|
494
495
|
};
|
|
495
|
-
_a14 = symbol14;
|
|
496
|
+
_a14$1 = symbol14$1;
|
|
496
497
|
|
|
497
498
|
let customAlphabet = (alphabet, defaultSize = 21) => {
|
|
498
499
|
return (size = defaultSize) => {
|
|
@@ -509,13 +510,13 @@ function getDefaultExportFromCjs (x) {
|
|
|
509
510
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
510
511
|
}
|
|
511
512
|
|
|
512
|
-
var secureJsonParse = {exports: {}};
|
|
513
|
+
var secureJsonParse$1 = {exports: {}};
|
|
513
514
|
|
|
514
|
-
var hasRequiredSecureJsonParse;
|
|
515
|
+
var hasRequiredSecureJsonParse$1;
|
|
515
516
|
|
|
516
|
-
function requireSecureJsonParse () {
|
|
517
|
-
if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
|
|
518
|
-
hasRequiredSecureJsonParse = 1;
|
|
517
|
+
function requireSecureJsonParse$1 () {
|
|
518
|
+
if (hasRequiredSecureJsonParse$1) return secureJsonParse$1.exports;
|
|
519
|
+
hasRequiredSecureJsonParse$1 = 1;
|
|
519
520
|
|
|
520
521
|
const hasBuffer = typeof Buffer !== 'undefined';
|
|
521
522
|
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
@@ -636,19 +637,19 @@ function requireSecureJsonParse () {
|
|
|
636
637
|
}
|
|
637
638
|
}
|
|
638
639
|
|
|
639
|
-
secureJsonParse.exports = parse;
|
|
640
|
-
secureJsonParse.exports.default = parse;
|
|
641
|
-
secureJsonParse.exports.parse = parse;
|
|
642
|
-
secureJsonParse.exports.safeParse = safeParse;
|
|
643
|
-
secureJsonParse.exports.scan = filter;
|
|
644
|
-
return secureJsonParse.exports;
|
|
640
|
+
secureJsonParse$1.exports = parse;
|
|
641
|
+
secureJsonParse$1.exports.default = parse;
|
|
642
|
+
secureJsonParse$1.exports.parse = parse;
|
|
643
|
+
secureJsonParse$1.exports.safeParse = safeParse;
|
|
644
|
+
secureJsonParse$1.exports.scan = filter;
|
|
645
|
+
return secureJsonParse$1.exports;
|
|
645
646
|
}
|
|
646
647
|
|
|
647
|
-
var secureJsonParseExports = requireSecureJsonParse();
|
|
648
|
-
var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
|
|
648
|
+
var secureJsonParseExports$1 = requireSecureJsonParse$1();
|
|
649
|
+
var SecureJSON$1 = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports$1);
|
|
649
650
|
|
|
650
651
|
// src/combine-headers.ts
|
|
651
|
-
function combineHeaders(...headers) {
|
|
652
|
+
function combineHeaders$1(...headers) {
|
|
652
653
|
return headers.reduce(
|
|
653
654
|
(combinedHeaders, currentHeaders) => ({
|
|
654
655
|
...combinedHeaders,
|
|
@@ -717,7 +718,7 @@ function createEventSourceParserStream() {
|
|
|
717
718
|
}
|
|
718
719
|
return new TransformStream({
|
|
719
720
|
transform(chunk, controller) {
|
|
720
|
-
const { lines, incompleteLine } = splitLines(buffer, chunk);
|
|
721
|
+
const { lines, incompleteLine } = splitLines$1(buffer, chunk);
|
|
721
722
|
buffer = incompleteLine;
|
|
722
723
|
for (let i = 0; i < lines.length; i++) {
|
|
723
724
|
parseLine(lines[i], controller);
|
|
@@ -729,7 +730,7 @@ function createEventSourceParserStream() {
|
|
|
729
730
|
}
|
|
730
731
|
});
|
|
731
732
|
}
|
|
732
|
-
function splitLines(buffer, chunk) {
|
|
733
|
+
function splitLines$1(buffer, chunk) {
|
|
733
734
|
const lines = [];
|
|
734
735
|
let currentLine = buffer;
|
|
735
736
|
for (let i = 0; i < chunk.length; ) {
|
|
@@ -751,14 +752,14 @@ function splitLines(buffer, chunk) {
|
|
|
751
752
|
}
|
|
752
753
|
|
|
753
754
|
// src/extract-response-headers.ts
|
|
754
|
-
function extractResponseHeaders(response) {
|
|
755
|
+
function extractResponseHeaders$1(response) {
|
|
755
756
|
const headers = {};
|
|
756
757
|
response.headers.forEach((value, key) => {
|
|
757
758
|
headers[key] = value;
|
|
758
759
|
});
|
|
759
760
|
return headers;
|
|
760
761
|
}
|
|
761
|
-
var createIdGenerator = ({
|
|
762
|
+
var createIdGenerator$1 = ({
|
|
762
763
|
prefix,
|
|
763
764
|
size: defaultSize = 16,
|
|
764
765
|
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
@@ -769,27 +770,27 @@ var createIdGenerator = ({
|
|
|
769
770
|
return generator;
|
|
770
771
|
}
|
|
771
772
|
if (alphabet.includes(separator)) {
|
|
772
|
-
throw new InvalidArgumentError({
|
|
773
|
+
throw new InvalidArgumentError$1({
|
|
773
774
|
argument: "separator",
|
|
774
775
|
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
775
776
|
});
|
|
776
777
|
}
|
|
777
778
|
return (size) => `${prefix}${separator}${generator(size)}`;
|
|
778
779
|
};
|
|
779
|
-
var generateId = createIdGenerator();
|
|
780
|
+
var generateId$1 = createIdGenerator$1();
|
|
780
781
|
|
|
781
782
|
// src/remove-undefined-entries.ts
|
|
782
|
-
function removeUndefinedEntries(record) {
|
|
783
|
+
function removeUndefinedEntries$1(record) {
|
|
783
784
|
return Object.fromEntries(
|
|
784
785
|
Object.entries(record).filter(([_key, value]) => value != null)
|
|
785
786
|
);
|
|
786
787
|
}
|
|
787
788
|
|
|
788
789
|
// src/is-abort-error.ts
|
|
789
|
-
function isAbortError(error) {
|
|
790
|
+
function isAbortError$1(error) {
|
|
790
791
|
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
791
792
|
}
|
|
792
|
-
function loadApiKey({
|
|
793
|
+
function loadApiKey$1({
|
|
793
794
|
apiKey,
|
|
794
795
|
environmentVariableName,
|
|
795
796
|
apiKeyParameterName = "apiKey",
|
|
@@ -799,23 +800,23 @@ function loadApiKey({
|
|
|
799
800
|
return apiKey;
|
|
800
801
|
}
|
|
801
802
|
if (apiKey != null) {
|
|
802
|
-
throw new LoadAPIKeyError({
|
|
803
|
+
throw new LoadAPIKeyError$1({
|
|
803
804
|
message: `${description} API key must be a string.`
|
|
804
805
|
});
|
|
805
806
|
}
|
|
806
807
|
if (typeof process === "undefined") {
|
|
807
|
-
throw new LoadAPIKeyError({
|
|
808
|
+
throw new LoadAPIKeyError$1({
|
|
808
809
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
|
809
810
|
});
|
|
810
811
|
}
|
|
811
812
|
apiKey = process.env[environmentVariableName];
|
|
812
813
|
if (apiKey == null) {
|
|
813
|
-
throw new LoadAPIKeyError({
|
|
814
|
+
throw new LoadAPIKeyError$1({
|
|
814
815
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
|
815
816
|
});
|
|
816
817
|
}
|
|
817
818
|
if (typeof apiKey !== "string") {
|
|
818
|
-
throw new LoadAPIKeyError({
|
|
819
|
+
throw new LoadAPIKeyError$1({
|
|
819
820
|
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
|
820
821
|
});
|
|
821
822
|
}
|
|
@@ -873,39 +874,39 @@ function loadSetting({
|
|
|
873
874
|
}
|
|
874
875
|
|
|
875
876
|
// src/validator.ts
|
|
876
|
-
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
877
|
-
function validator(validate) {
|
|
878
|
-
return { [validatorSymbol]: true, validate };
|
|
877
|
+
var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
|
|
878
|
+
function validator$1(validate) {
|
|
879
|
+
return { [validatorSymbol$1]: true, validate };
|
|
879
880
|
}
|
|
880
|
-
function isValidator(value) {
|
|
881
|
-
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
881
|
+
function isValidator$1(value) {
|
|
882
|
+
return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
|
|
882
883
|
}
|
|
883
|
-
function asValidator(value) {
|
|
884
|
-
return isValidator(value) ? value : zodValidator(value);
|
|
884
|
+
function asValidator$1(value) {
|
|
885
|
+
return isValidator$1(value) ? value : zodValidator$1(value);
|
|
885
886
|
}
|
|
886
|
-
function zodValidator(zodSchema) {
|
|
887
|
-
return validator((value) => {
|
|
887
|
+
function zodValidator$1(zodSchema) {
|
|
888
|
+
return validator$1((value) => {
|
|
888
889
|
const result = zodSchema.safeParse(value);
|
|
889
890
|
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
890
891
|
});
|
|
891
892
|
}
|
|
892
893
|
|
|
893
894
|
// src/validate-types.ts
|
|
894
|
-
function validateTypes({
|
|
895
|
+
function validateTypes$1({
|
|
895
896
|
value,
|
|
896
897
|
schema: inputSchema
|
|
897
898
|
}) {
|
|
898
|
-
const result = safeValidateTypes({ value, schema: inputSchema });
|
|
899
|
+
const result = safeValidateTypes$1({ value, schema: inputSchema });
|
|
899
900
|
if (!result.success) {
|
|
900
|
-
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
901
|
+
throw TypeValidationError$1.wrap({ value, cause: result.error });
|
|
901
902
|
}
|
|
902
903
|
return result.value;
|
|
903
904
|
}
|
|
904
|
-
function safeValidateTypes({
|
|
905
|
+
function safeValidateTypes$1({
|
|
905
906
|
value,
|
|
906
907
|
schema
|
|
907
908
|
}) {
|
|
908
|
-
const validator2 = asValidator(schema);
|
|
909
|
+
const validator2 = asValidator$1(schema);
|
|
909
910
|
try {
|
|
910
911
|
if (validator2.validate == null) {
|
|
911
912
|
return { success: true, value };
|
|
@@ -916,55 +917,55 @@ function safeValidateTypes({
|
|
|
916
917
|
}
|
|
917
918
|
return {
|
|
918
919
|
success: false,
|
|
919
|
-
error: TypeValidationError.wrap({ value, cause: result.error })
|
|
920
|
+
error: TypeValidationError$1.wrap({ value, cause: result.error })
|
|
920
921
|
};
|
|
921
922
|
} catch (error) {
|
|
922
923
|
return {
|
|
923
924
|
success: false,
|
|
924
|
-
error: TypeValidationError.wrap({ value, cause: error })
|
|
925
|
+
error: TypeValidationError$1.wrap({ value, cause: error })
|
|
925
926
|
};
|
|
926
927
|
}
|
|
927
928
|
}
|
|
928
929
|
|
|
929
930
|
// src/parse-json.ts
|
|
930
|
-
function parseJSON({
|
|
931
|
+
function parseJSON$1({
|
|
931
932
|
text,
|
|
932
933
|
schema
|
|
933
934
|
}) {
|
|
934
935
|
try {
|
|
935
|
-
const value = SecureJSON.parse(text);
|
|
936
|
+
const value = SecureJSON$1.parse(text);
|
|
936
937
|
if (schema == null) {
|
|
937
938
|
return value;
|
|
938
939
|
}
|
|
939
|
-
return validateTypes({ value, schema });
|
|
940
|
+
return validateTypes$1({ value, schema });
|
|
940
941
|
} catch (error) {
|
|
941
|
-
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
|
|
942
|
+
if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) {
|
|
942
943
|
throw error;
|
|
943
944
|
}
|
|
944
|
-
throw new JSONParseError({ text, cause: error });
|
|
945
|
+
throw new JSONParseError$1({ text, cause: error });
|
|
945
946
|
}
|
|
946
947
|
}
|
|
947
|
-
function safeParseJSON({
|
|
948
|
+
function safeParseJSON$1({
|
|
948
949
|
text,
|
|
949
950
|
schema
|
|
950
951
|
}) {
|
|
951
952
|
try {
|
|
952
|
-
const value = SecureJSON.parse(text);
|
|
953
|
+
const value = SecureJSON$1.parse(text);
|
|
953
954
|
if (schema == null) {
|
|
954
955
|
return { success: true, value, rawValue: value };
|
|
955
956
|
}
|
|
956
|
-
const validationResult = safeValidateTypes({ value, schema });
|
|
957
|
+
const validationResult = safeValidateTypes$1({ value, schema });
|
|
957
958
|
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
|
|
958
959
|
} catch (error) {
|
|
959
960
|
return {
|
|
960
961
|
success: false,
|
|
961
|
-
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
|
|
962
|
+
error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
|
|
962
963
|
};
|
|
963
964
|
}
|
|
964
965
|
}
|
|
965
|
-
function isParsableJson(input) {
|
|
966
|
+
function isParsableJson$1(input) {
|
|
966
967
|
try {
|
|
967
|
-
SecureJSON.parse(input);
|
|
968
|
+
SecureJSON$1.parse(input);
|
|
968
969
|
return true;
|
|
969
970
|
} catch (e) {
|
|
970
971
|
return false;
|
|
@@ -978,12 +979,12 @@ function parseProviderOptions({
|
|
|
978
979
|
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
|
|
979
980
|
return void 0;
|
|
980
981
|
}
|
|
981
|
-
const parsedProviderOptions = safeValidateTypes({
|
|
982
|
+
const parsedProviderOptions = safeValidateTypes$1({
|
|
982
983
|
value: providerOptions[provider],
|
|
983
984
|
schema
|
|
984
985
|
});
|
|
985
986
|
if (!parsedProviderOptions.success) {
|
|
986
|
-
throw new InvalidArgumentError({
|
|
987
|
+
throw new InvalidArgumentError$1({
|
|
987
988
|
argument: "providerOptions",
|
|
988
989
|
message: `invalid ${provider} provider options`,
|
|
989
990
|
cause: parsedProviderOptions.error
|
|
@@ -991,8 +992,8 @@ function parseProviderOptions({
|
|
|
991
992
|
}
|
|
992
993
|
return parsedProviderOptions.value;
|
|
993
994
|
}
|
|
994
|
-
var getOriginalFetch2 = () => globalThis.fetch;
|
|
995
|
-
var postJsonToApi = async ({
|
|
995
|
+
var getOriginalFetch2$1 = () => globalThis.fetch;
|
|
996
|
+
var postJsonToApi$1 = async ({
|
|
996
997
|
url,
|
|
997
998
|
headers,
|
|
998
999
|
body,
|
|
@@ -1000,7 +1001,7 @@ var postJsonToApi = async ({
|
|
|
1000
1001
|
successfulResponseHandler,
|
|
1001
1002
|
abortSignal,
|
|
1002
1003
|
fetch
|
|
1003
|
-
}) => postToApi({
|
|
1004
|
+
}) => postToApi$1({
|
|
1004
1005
|
url,
|
|
1005
1006
|
headers: {
|
|
1006
1007
|
"Content-Type": "application/json",
|
|
@@ -1023,7 +1024,7 @@ var postFormDataToApi = async ({
|
|
|
1023
1024
|
successfulResponseHandler,
|
|
1024
1025
|
abortSignal,
|
|
1025
1026
|
fetch
|
|
1026
|
-
}) => postToApi({
|
|
1027
|
+
}) => postToApi$1({
|
|
1027
1028
|
url,
|
|
1028
1029
|
headers,
|
|
1029
1030
|
body: {
|
|
@@ -1035,23 +1036,23 @@ var postFormDataToApi = async ({
|
|
|
1035
1036
|
abortSignal,
|
|
1036
1037
|
fetch
|
|
1037
1038
|
});
|
|
1038
|
-
var postToApi = async ({
|
|
1039
|
+
var postToApi$1 = async ({
|
|
1039
1040
|
url,
|
|
1040
1041
|
headers = {},
|
|
1041
1042
|
body,
|
|
1042
1043
|
successfulResponseHandler,
|
|
1043
1044
|
failedResponseHandler,
|
|
1044
1045
|
abortSignal,
|
|
1045
|
-
fetch = getOriginalFetch2()
|
|
1046
|
+
fetch = getOriginalFetch2$1()
|
|
1046
1047
|
}) => {
|
|
1047
1048
|
try {
|
|
1048
1049
|
const response = await fetch(url, {
|
|
1049
1050
|
method: "POST",
|
|
1050
|
-
headers: removeUndefinedEntries(headers),
|
|
1051
|
+
headers: removeUndefinedEntries$1(headers),
|
|
1051
1052
|
body: body.content,
|
|
1052
1053
|
signal: abortSignal
|
|
1053
1054
|
});
|
|
1054
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1055
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1055
1056
|
if (!response.ok) {
|
|
1056
1057
|
let errorInformation;
|
|
1057
1058
|
try {
|
|
@@ -1061,10 +1062,10 @@ var postToApi = async ({
|
|
|
1061
1062
|
requestBodyValues: body.values
|
|
1062
1063
|
});
|
|
1063
1064
|
} catch (error) {
|
|
1064
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
1065
|
+
if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
|
|
1065
1066
|
throw error;
|
|
1066
1067
|
}
|
|
1067
|
-
throw new APICallError({
|
|
1068
|
+
throw new APICallError$1({
|
|
1068
1069
|
message: "Failed to process error response",
|
|
1069
1070
|
cause: error,
|
|
1070
1071
|
statusCode: response.status,
|
|
@@ -1083,11 +1084,11 @@ var postToApi = async ({
|
|
|
1083
1084
|
});
|
|
1084
1085
|
} catch (error) {
|
|
1085
1086
|
if (error instanceof Error) {
|
|
1086
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
1087
|
+
if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
|
|
1087
1088
|
throw error;
|
|
1088
1089
|
}
|
|
1089
1090
|
}
|
|
1090
|
-
throw new APICallError({
|
|
1091
|
+
throw new APICallError$1({
|
|
1091
1092
|
message: "Failed to process successful response",
|
|
1092
1093
|
cause: error,
|
|
1093
1094
|
statusCode: response.status,
|
|
@@ -1097,13 +1098,13 @@ var postToApi = async ({
|
|
|
1097
1098
|
});
|
|
1098
1099
|
}
|
|
1099
1100
|
} catch (error) {
|
|
1100
|
-
if (isAbortError(error)) {
|
|
1101
|
+
if (isAbortError$1(error)) {
|
|
1101
1102
|
throw error;
|
|
1102
1103
|
}
|
|
1103
1104
|
if (error instanceof TypeError && error.message === "fetch failed") {
|
|
1104
1105
|
const cause = error.cause;
|
|
1105
1106
|
if (cause != null) {
|
|
1106
|
-
throw new APICallError({
|
|
1107
|
+
throw new APICallError$1({
|
|
1107
1108
|
message: `Cannot connect to API: ${cause.message}`,
|
|
1108
1109
|
cause,
|
|
1109
1110
|
url,
|
|
@@ -1124,17 +1125,17 @@ async function resolve(value) {
|
|
|
1124
1125
|
}
|
|
1125
1126
|
return Promise.resolve(value);
|
|
1126
1127
|
}
|
|
1127
|
-
var createJsonErrorResponseHandler = ({
|
|
1128
|
+
var createJsonErrorResponseHandler$1 = ({
|
|
1128
1129
|
errorSchema,
|
|
1129
1130
|
errorToMessage,
|
|
1130
1131
|
isRetryable
|
|
1131
1132
|
}) => async ({ response, url, requestBodyValues }) => {
|
|
1132
1133
|
const responseBody = await response.text();
|
|
1133
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1134
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1134
1135
|
if (responseBody.trim() === "") {
|
|
1135
1136
|
return {
|
|
1136
1137
|
responseHeaders,
|
|
1137
|
-
value: new APICallError({
|
|
1138
|
+
value: new APICallError$1({
|
|
1138
1139
|
message: response.statusText,
|
|
1139
1140
|
url,
|
|
1140
1141
|
requestBodyValues,
|
|
@@ -1146,13 +1147,13 @@ var createJsonErrorResponseHandler = ({
|
|
|
1146
1147
|
};
|
|
1147
1148
|
}
|
|
1148
1149
|
try {
|
|
1149
|
-
const parsedError = parseJSON({
|
|
1150
|
+
const parsedError = parseJSON$1({
|
|
1150
1151
|
text: responseBody,
|
|
1151
1152
|
schema: errorSchema
|
|
1152
1153
|
});
|
|
1153
1154
|
return {
|
|
1154
1155
|
responseHeaders,
|
|
1155
|
-
value: new APICallError({
|
|
1156
|
+
value: new APICallError$1({
|
|
1156
1157
|
message: errorToMessage(parsedError),
|
|
1157
1158
|
url,
|
|
1158
1159
|
requestBodyValues,
|
|
@@ -1166,7 +1167,7 @@ var createJsonErrorResponseHandler = ({
|
|
|
1166
1167
|
} catch (parseError) {
|
|
1167
1168
|
return {
|
|
1168
1169
|
responseHeaders,
|
|
1169
|
-
value: new APICallError({
|
|
1170
|
+
value: new APICallError$1({
|
|
1170
1171
|
message: response.statusText,
|
|
1171
1172
|
url,
|
|
1172
1173
|
requestBodyValues,
|
|
@@ -1178,10 +1179,10 @@ var createJsonErrorResponseHandler = ({
|
|
|
1178
1179
|
};
|
|
1179
1180
|
}
|
|
1180
1181
|
};
|
|
1181
|
-
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
1182
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1182
|
+
var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
|
|
1183
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1183
1184
|
if (response.body == null) {
|
|
1184
|
-
throw new EmptyResponseBodyError({});
|
|
1185
|
+
throw new EmptyResponseBodyError$1({});
|
|
1185
1186
|
}
|
|
1186
1187
|
return {
|
|
1187
1188
|
responseHeaders,
|
|
@@ -1192,7 +1193,7 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
|
|
|
1192
1193
|
return;
|
|
1193
1194
|
}
|
|
1194
1195
|
controller.enqueue(
|
|
1195
|
-
safeParseJSON({
|
|
1196
|
+
safeParseJSON$1({
|
|
1196
1197
|
text: data,
|
|
1197
1198
|
schema: chunkSchema
|
|
1198
1199
|
})
|
|
@@ -1202,15 +1203,15 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
|
|
|
1202
1203
|
)
|
|
1203
1204
|
};
|
|
1204
1205
|
};
|
|
1205
|
-
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
1206
|
+
var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
1206
1207
|
const responseBody = await response.text();
|
|
1207
|
-
const parsedResult = safeParseJSON({
|
|
1208
|
+
const parsedResult = safeParseJSON$1({
|
|
1208
1209
|
text: responseBody,
|
|
1209
1210
|
schema: responseSchema
|
|
1210
1211
|
});
|
|
1211
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1212
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1212
1213
|
if (!parsedResult.success) {
|
|
1213
|
-
throw new APICallError({
|
|
1214
|
+
throw new APICallError$1({
|
|
1214
1215
|
message: "Invalid JSON response",
|
|
1215
1216
|
cause: parsedResult.error,
|
|
1216
1217
|
statusCode: response.status,
|
|
@@ -1227,9 +1228,9 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
|
|
|
1227
1228
|
};
|
|
1228
1229
|
};
|
|
1229
1230
|
var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
|
|
1230
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1231
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1231
1232
|
if (!response.body) {
|
|
1232
|
-
throw new APICallError({
|
|
1233
|
+
throw new APICallError$1({
|
|
1233
1234
|
message: "Response body is empty",
|
|
1234
1235
|
url,
|
|
1235
1236
|
requestBodyValues,
|
|
@@ -1245,7 +1246,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
|
|
|
1245
1246
|
value: new Uint8Array(buffer)
|
|
1246
1247
|
};
|
|
1247
1248
|
} catch (error) {
|
|
1248
|
-
throw new APICallError({
|
|
1249
|
+
throw new APICallError$1({
|
|
1249
1250
|
message: "Failed to read response as array buffer",
|
|
1250
1251
|
url,
|
|
1251
1252
|
requestBodyValues,
|
|
@@ -1258,22 +1259,22 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
|
|
|
1258
1259
|
};
|
|
1259
1260
|
|
|
1260
1261
|
// src/uint8-utils.ts
|
|
1261
|
-
var { btoa, atob: atob$1 } = globalThis;
|
|
1262
|
+
var { btoa: btoa$1, atob: atob$1 } = globalThis;
|
|
1262
1263
|
function convertBase64ToUint8Array(base64String) {
|
|
1263
1264
|
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
|
|
1264
1265
|
const latin1string = atob$1(base64Url);
|
|
1265
1266
|
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
|
|
1266
1267
|
}
|
|
1267
|
-
function convertUint8ArrayToBase64(array) {
|
|
1268
|
+
function convertUint8ArrayToBase64$1(array) {
|
|
1268
1269
|
let latin1string = "";
|
|
1269
1270
|
for (let i = 0; i < array.length; i++) {
|
|
1270
1271
|
latin1string += String.fromCodePoint(array[i]);
|
|
1271
1272
|
}
|
|
1272
|
-
return btoa(latin1string);
|
|
1273
|
+
return btoa$1(latin1string);
|
|
1273
1274
|
}
|
|
1274
1275
|
|
|
1275
1276
|
// src/without-trailing-slash.ts
|
|
1276
|
-
function withoutTrailingSlash(url) {
|
|
1277
|
+
function withoutTrailingSlash$1(url) {
|
|
1277
1278
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
1278
1279
|
}
|
|
1279
1280
|
|
|
@@ -5731,7 +5732,7 @@ function convertToOpenAIChatMessages({
|
|
|
5731
5732
|
return {
|
|
5732
5733
|
type: "image_url",
|
|
5733
5734
|
image_url: {
|
|
5734
|
-
url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
|
|
5735
|
+
url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
|
|
5735
5736
|
// OpenAI specific extension: image detail
|
|
5736
5737
|
detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
|
|
5737
5738
|
}
|
|
@@ -5739,7 +5740,7 @@ function convertToOpenAIChatMessages({
|
|
|
5739
5740
|
}
|
|
5740
5741
|
case "file": {
|
|
5741
5742
|
if (part.data instanceof URL) {
|
|
5742
|
-
throw new UnsupportedFunctionalityError({
|
|
5743
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5743
5744
|
functionality: "'File content parts with URL data' functionality not supported."
|
|
5744
5745
|
});
|
|
5745
5746
|
}
|
|
@@ -5767,7 +5768,7 @@ function convertToOpenAIChatMessages({
|
|
|
5767
5768
|
};
|
|
5768
5769
|
}
|
|
5769
5770
|
default: {
|
|
5770
|
-
throw new UnsupportedFunctionalityError({
|
|
5771
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5771
5772
|
functionality: `File content part type ${part.mimeType} in user messages`
|
|
5772
5773
|
});
|
|
5773
5774
|
}
|
|
@@ -5802,7 +5803,7 @@ function convertToOpenAIChatMessages({
|
|
|
5802
5803
|
}
|
|
5803
5804
|
if (useLegacyFunctionCalling) {
|
|
5804
5805
|
if (toolCalls.length > 1) {
|
|
5805
|
-
throw new UnsupportedFunctionalityError({
|
|
5806
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5806
5807
|
functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
|
|
5807
5808
|
});
|
|
5808
5809
|
}
|
|
@@ -5887,7 +5888,7 @@ var openaiErrorDataSchema = z.object({
|
|
|
5887
5888
|
code: z.union([z.string(), z.number()]).nullish()
|
|
5888
5889
|
})
|
|
5889
5890
|
});
|
|
5890
|
-
var openaiFailedResponseHandler = createJsonErrorResponseHandler({
|
|
5891
|
+
var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
5891
5892
|
errorSchema: openaiErrorDataSchema,
|
|
5892
5893
|
errorToMessage: (data) => data.error.message
|
|
5893
5894
|
});
|
|
@@ -5947,7 +5948,7 @@ function prepareTools$3({
|
|
|
5947
5948
|
toolWarnings
|
|
5948
5949
|
};
|
|
5949
5950
|
case "required":
|
|
5950
|
-
throw new UnsupportedFunctionalityError({
|
|
5951
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5951
5952
|
functionality: "useLegacyFunctionCalling and toolChoice: required"
|
|
5952
5953
|
});
|
|
5953
5954
|
default:
|
|
@@ -5996,7 +5997,7 @@ function prepareTools$3({
|
|
|
5996
5997
|
};
|
|
5997
5998
|
default: {
|
|
5998
5999
|
const _exhaustiveCheck = type;
|
|
5999
|
-
throw new UnsupportedFunctionalityError({
|
|
6000
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6000
6001
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
6001
6002
|
});
|
|
6002
6003
|
}
|
|
@@ -6059,12 +6060,12 @@ var OpenAIChatLanguageModel = class {
|
|
|
6059
6060
|
}
|
|
6060
6061
|
const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
|
|
6061
6062
|
if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
|
|
6062
|
-
throw new UnsupportedFunctionalityError({
|
|
6063
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6063
6064
|
functionality: "useLegacyFunctionCalling with parallelToolCalls"
|
|
6064
6065
|
});
|
|
6065
6066
|
}
|
|
6066
6067
|
if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
|
|
6067
|
-
throw new UnsupportedFunctionalityError({
|
|
6068
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6068
6069
|
functionality: "structuredOutputs with useLegacyFunctionCalling"
|
|
6069
6070
|
});
|
|
6070
6071
|
}
|
|
@@ -6265,15 +6266,15 @@ var OpenAIChatLanguageModel = class {
|
|
|
6265
6266
|
responseHeaders,
|
|
6266
6267
|
value: response,
|
|
6267
6268
|
rawValue: rawResponse
|
|
6268
|
-
} = await postJsonToApi({
|
|
6269
|
+
} = await postJsonToApi$1({
|
|
6269
6270
|
url: this.config.url({
|
|
6270
6271
|
path: "/chat/completions",
|
|
6271
6272
|
modelId: this.modelId
|
|
6272
6273
|
}),
|
|
6273
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6274
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6274
6275
|
body,
|
|
6275
6276
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6276
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
6277
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
6277
6278
|
openaiChatResponseSchema
|
|
6278
6279
|
),
|
|
6279
6280
|
abortSignal: options.abortSignal,
|
|
@@ -6301,7 +6302,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6301
6302
|
toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
|
|
6302
6303
|
{
|
|
6303
6304
|
toolCallType: "function",
|
|
6304
|
-
toolCallId: generateId(),
|
|
6305
|
+
toolCallId: generateId$1(),
|
|
6305
6306
|
toolName: choice.message.function_call.name,
|
|
6306
6307
|
args: choice.message.function_call.arguments
|
|
6307
6308
|
}
|
|
@@ -6309,7 +6310,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6309
6310
|
var _a2;
|
|
6310
6311
|
return {
|
|
6311
6312
|
toolCallType: "function",
|
|
6312
|
-
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
6313
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId$1(),
|
|
6313
6314
|
toolName: toolCall.function.name,
|
|
6314
6315
|
args: toolCall.function.arguments
|
|
6315
6316
|
};
|
|
@@ -6379,15 +6380,15 @@ var OpenAIChatLanguageModel = class {
|
|
|
6379
6380
|
// only include stream_options when in strict compatibility mode:
|
|
6380
6381
|
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
6381
6382
|
};
|
|
6382
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
6383
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
6383
6384
|
url: this.config.url({
|
|
6384
6385
|
path: "/chat/completions",
|
|
6385
6386
|
modelId: this.modelId
|
|
6386
6387
|
}),
|
|
6387
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6388
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6388
6389
|
body,
|
|
6389
6390
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6390
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
6391
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
6391
6392
|
openaiChatChunkSchema
|
|
6392
6393
|
),
|
|
6393
6394
|
abortSignal: options.abortSignal,
|
|
@@ -6475,7 +6476,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6475
6476
|
const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
|
|
6476
6477
|
{
|
|
6477
6478
|
type: "function",
|
|
6478
|
-
id: generateId(),
|
|
6479
|
+
id: generateId$1(),
|
|
6479
6480
|
function: delta.function_call,
|
|
6480
6481
|
index: 0
|
|
6481
6482
|
}
|
|
@@ -6485,19 +6486,19 @@ var OpenAIChatLanguageModel = class {
|
|
|
6485
6486
|
const index = toolCallDelta.index;
|
|
6486
6487
|
if (toolCalls[index] == null) {
|
|
6487
6488
|
if (toolCallDelta.type !== "function") {
|
|
6488
|
-
throw new InvalidResponseDataError({
|
|
6489
|
+
throw new InvalidResponseDataError$1({
|
|
6489
6490
|
data: toolCallDelta,
|
|
6490
6491
|
message: `Expected 'function' type.`
|
|
6491
6492
|
});
|
|
6492
6493
|
}
|
|
6493
6494
|
if (toolCallDelta.id == null) {
|
|
6494
|
-
throw new InvalidResponseDataError({
|
|
6495
|
+
throw new InvalidResponseDataError$1({
|
|
6495
6496
|
data: toolCallDelta,
|
|
6496
6497
|
message: `Expected 'id' to be a string.`
|
|
6497
6498
|
});
|
|
6498
6499
|
}
|
|
6499
6500
|
if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
|
|
6500
|
-
throw new InvalidResponseDataError({
|
|
6501
|
+
throw new InvalidResponseDataError$1({
|
|
6501
6502
|
data: toolCallDelta,
|
|
6502
6503
|
message: `Expected 'function.name' to be a string.`
|
|
6503
6504
|
});
|
|
@@ -6522,11 +6523,11 @@ var OpenAIChatLanguageModel = class {
|
|
|
6522
6523
|
argsTextDelta: toolCall2.function.arguments
|
|
6523
6524
|
});
|
|
6524
6525
|
}
|
|
6525
|
-
if (isParsableJson(toolCall2.function.arguments)) {
|
|
6526
|
+
if (isParsableJson$1(toolCall2.function.arguments)) {
|
|
6526
6527
|
controller.enqueue({
|
|
6527
6528
|
type: "tool-call",
|
|
6528
6529
|
toolCallType: "function",
|
|
6529
|
-
toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
|
|
6530
|
+
toolCallId: (_e = toolCall2.id) != null ? _e : generateId$1(),
|
|
6530
6531
|
toolName: toolCall2.function.name,
|
|
6531
6532
|
args: toolCall2.function.arguments
|
|
6532
6533
|
});
|
|
@@ -6549,11 +6550,11 @@ var OpenAIChatLanguageModel = class {
|
|
|
6549
6550
|
toolName: toolCall.function.name,
|
|
6550
6551
|
argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
|
|
6551
6552
|
});
|
|
6552
|
-
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
|
|
6553
|
+
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson$1(toolCall.function.arguments)) {
|
|
6553
6554
|
controller.enqueue({
|
|
6554
6555
|
type: "tool-call",
|
|
6555
6556
|
toolCallType: "function",
|
|
6556
|
-
toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
|
|
6557
|
+
toolCallId: (_l = toolCall.id) != null ? _l : generateId$1(),
|
|
6557
6558
|
toolName: toolCall.function.name,
|
|
6558
6559
|
args: toolCall.function.arguments
|
|
6559
6560
|
});
|
|
@@ -6740,7 +6741,7 @@ function convertToOpenAICompletionPrompt({
|
|
|
6740
6741
|
for (const { role, content } of prompt) {
|
|
6741
6742
|
switch (role) {
|
|
6742
6743
|
case "system": {
|
|
6743
|
-
throw new InvalidPromptError({
|
|
6744
|
+
throw new InvalidPromptError$1({
|
|
6744
6745
|
message: "Unexpected system message in prompt: ${content}",
|
|
6745
6746
|
prompt
|
|
6746
6747
|
});
|
|
@@ -6752,7 +6753,7 @@ function convertToOpenAICompletionPrompt({
|
|
|
6752
6753
|
return part.text;
|
|
6753
6754
|
}
|
|
6754
6755
|
case "image": {
|
|
6755
|
-
throw new UnsupportedFunctionalityError({
|
|
6756
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6756
6757
|
functionality: "images"
|
|
6757
6758
|
});
|
|
6758
6759
|
}
|
|
@@ -6771,7 +6772,7 @@ ${userMessage}
|
|
|
6771
6772
|
return part.text;
|
|
6772
6773
|
}
|
|
6773
6774
|
case "tool-call": {
|
|
6774
|
-
throw new UnsupportedFunctionalityError({
|
|
6775
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6775
6776
|
functionality: "tool-call messages"
|
|
6776
6777
|
});
|
|
6777
6778
|
}
|
|
@@ -6784,7 +6785,7 @@ ${assistantMessage}
|
|
|
6784
6785
|
break;
|
|
6785
6786
|
}
|
|
6786
6787
|
case "tool": {
|
|
6787
|
-
throw new UnsupportedFunctionalityError({
|
|
6788
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6788
6789
|
functionality: "tool messages"
|
|
6789
6790
|
});
|
|
6790
6791
|
}
|
|
@@ -6885,24 +6886,24 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6885
6886
|
switch (type) {
|
|
6886
6887
|
case "regular": {
|
|
6887
6888
|
if ((_a = mode.tools) == null ? void 0 : _a.length) {
|
|
6888
|
-
throw new UnsupportedFunctionalityError({
|
|
6889
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6889
6890
|
functionality: "tools"
|
|
6890
6891
|
});
|
|
6891
6892
|
}
|
|
6892
6893
|
if (mode.toolChoice) {
|
|
6893
|
-
throw new UnsupportedFunctionalityError({
|
|
6894
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6894
6895
|
functionality: "toolChoice"
|
|
6895
6896
|
});
|
|
6896
6897
|
}
|
|
6897
6898
|
return { args: baseArgs, warnings };
|
|
6898
6899
|
}
|
|
6899
6900
|
case "object-json": {
|
|
6900
|
-
throw new UnsupportedFunctionalityError({
|
|
6901
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6901
6902
|
functionality: "object-json mode"
|
|
6902
6903
|
});
|
|
6903
6904
|
}
|
|
6904
6905
|
case "object-tool": {
|
|
6905
|
-
throw new UnsupportedFunctionalityError({
|
|
6906
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6906
6907
|
functionality: "object-tool mode"
|
|
6907
6908
|
});
|
|
6908
6909
|
}
|
|
@@ -6918,15 +6919,15 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6918
6919
|
responseHeaders,
|
|
6919
6920
|
value: response,
|
|
6920
6921
|
rawValue: rawResponse
|
|
6921
|
-
} = await postJsonToApi({
|
|
6922
|
+
} = await postJsonToApi$1({
|
|
6922
6923
|
url: this.config.url({
|
|
6923
6924
|
path: "/completions",
|
|
6924
6925
|
modelId: this.modelId
|
|
6925
6926
|
}),
|
|
6926
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6927
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6927
6928
|
body: args,
|
|
6928
6929
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6929
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
6930
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
6930
6931
|
openaiCompletionResponseSchema
|
|
6931
6932
|
),
|
|
6932
6933
|
abortSignal: options.abortSignal,
|
|
@@ -6957,15 +6958,15 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6957
6958
|
// only include stream_options when in strict compatibility mode:
|
|
6958
6959
|
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
6959
6960
|
};
|
|
6960
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
6961
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
6961
6962
|
url: this.config.url({
|
|
6962
6963
|
path: "/completions",
|
|
6963
6964
|
modelId: this.modelId
|
|
6964
6965
|
}),
|
|
6965
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6966
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6966
6967
|
body,
|
|
6967
6968
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6968
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
6969
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
6969
6970
|
openaiCompletionChunkSchema
|
|
6970
6971
|
),
|
|
6971
6972
|
abortSignal: options.abortSignal,
|
|
@@ -7117,12 +7118,12 @@ var OpenAIEmbeddingModel = class {
|
|
|
7117
7118
|
values
|
|
7118
7119
|
});
|
|
7119
7120
|
}
|
|
7120
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
7121
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
7121
7122
|
url: this.config.url({
|
|
7122
7123
|
path: "/embeddings",
|
|
7123
7124
|
modelId: this.modelId
|
|
7124
7125
|
}),
|
|
7125
|
-
headers: combineHeaders(this.config.headers(), headers),
|
|
7126
|
+
headers: combineHeaders$1(this.config.headers(), headers),
|
|
7126
7127
|
body: {
|
|
7127
7128
|
model: this.modelId,
|
|
7128
7129
|
input: values,
|
|
@@ -7131,7 +7132,7 @@ var OpenAIEmbeddingModel = class {
|
|
|
7131
7132
|
user: this.settings.user
|
|
7132
7133
|
},
|
|
7133
7134
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7134
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7135
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7135
7136
|
openaiTextEmbeddingResponseSchema
|
|
7136
7137
|
),
|
|
7137
7138
|
abortSignal,
|
|
@@ -7195,12 +7196,12 @@ var OpenAIImageModel = class {
|
|
|
7195
7196
|
warnings.push({ type: "unsupported-setting", setting: "seed" });
|
|
7196
7197
|
}
|
|
7197
7198
|
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
|
|
7198
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
7199
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
7199
7200
|
url: this.config.url({
|
|
7200
7201
|
path: "/images/generations",
|
|
7201
7202
|
modelId: this.modelId
|
|
7202
7203
|
}),
|
|
7203
|
-
headers: combineHeaders(this.config.headers(), headers),
|
|
7204
|
+
headers: combineHeaders$1(this.config.headers(), headers),
|
|
7204
7205
|
body: {
|
|
7205
7206
|
model: this.modelId,
|
|
7206
7207
|
prompt,
|
|
@@ -7210,7 +7211,7 @@ var OpenAIImageModel = class {
|
|
|
7210
7211
|
...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
|
|
7211
7212
|
},
|
|
7212
7213
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7213
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7214
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7214
7215
|
openaiImageResponseSchema
|
|
7215
7216
|
),
|
|
7216
7217
|
abortSignal,
|
|
@@ -7354,10 +7355,10 @@ var OpenAITranscriptionModel = class {
|
|
|
7354
7355
|
path: "/audio/transcriptions",
|
|
7355
7356
|
modelId: this.modelId
|
|
7356
7357
|
}),
|
|
7357
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7358
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7358
7359
|
formData,
|
|
7359
7360
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7360
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7361
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7361
7362
|
openaiTranscriptionResponseSchema
|
|
7362
7363
|
),
|
|
7363
7364
|
abortSignal: options.abortSignal,
|
|
@@ -7441,14 +7442,14 @@ function convertToOpenAIResponsesMessages({
|
|
|
7441
7442
|
case "image": {
|
|
7442
7443
|
return {
|
|
7443
7444
|
type: "input_image",
|
|
7444
|
-
image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
|
|
7445
|
+
image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
|
|
7445
7446
|
// OpenAI specific extension: image detail
|
|
7446
7447
|
detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
|
|
7447
7448
|
};
|
|
7448
7449
|
}
|
|
7449
7450
|
case "file": {
|
|
7450
7451
|
if (part.data instanceof URL) {
|
|
7451
|
-
throw new UnsupportedFunctionalityError({
|
|
7452
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7452
7453
|
functionality: "File URLs in user messages"
|
|
7453
7454
|
});
|
|
7454
7455
|
}
|
|
@@ -7461,7 +7462,7 @@ function convertToOpenAIResponsesMessages({
|
|
|
7461
7462
|
};
|
|
7462
7463
|
}
|
|
7463
7464
|
default: {
|
|
7464
|
-
throw new UnsupportedFunctionalityError({
|
|
7465
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7465
7466
|
functionality: "Only PDF files are supported in user messages"
|
|
7466
7467
|
});
|
|
7467
7468
|
}
|
|
@@ -7603,7 +7604,7 @@ function prepareResponsesTools({
|
|
|
7603
7604
|
}
|
|
7604
7605
|
default: {
|
|
7605
7606
|
const _exhaustiveCheck = type;
|
|
7606
|
-
throw new UnsupportedFunctionalityError({
|
|
7607
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7607
7608
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
7608
7609
|
});
|
|
7609
7610
|
}
|
|
@@ -7802,15 +7803,15 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7802
7803
|
responseHeaders,
|
|
7803
7804
|
value: response,
|
|
7804
7805
|
rawValue: rawResponse
|
|
7805
|
-
} = await postJsonToApi({
|
|
7806
|
+
} = await postJsonToApi$1({
|
|
7806
7807
|
url: this.config.url({
|
|
7807
7808
|
path: "/responses",
|
|
7808
7809
|
modelId: this.modelId
|
|
7809
7810
|
}),
|
|
7810
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7811
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7811
7812
|
body,
|
|
7812
7813
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7813
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7814
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7814
7815
|
z.object({
|
|
7815
7816
|
id: z.string(),
|
|
7816
7817
|
created_at: z.number(),
|
|
@@ -7881,7 +7882,7 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7881
7882
|
var _a2, _b2, _c2;
|
|
7882
7883
|
return {
|
|
7883
7884
|
sourceType: "url",
|
|
7884
|
-
id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
|
|
7885
|
+
id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId$1(),
|
|
7885
7886
|
url: annotation.url,
|
|
7886
7887
|
title: annotation.title
|
|
7887
7888
|
};
|
|
@@ -7928,18 +7929,18 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7928
7929
|
}
|
|
7929
7930
|
async doStream(options) {
|
|
7930
7931
|
const { args: body, warnings } = this.getArgs(options);
|
|
7931
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
7932
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
7932
7933
|
url: this.config.url({
|
|
7933
7934
|
path: "/responses",
|
|
7934
7935
|
modelId: this.modelId
|
|
7935
7936
|
}),
|
|
7936
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7937
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7937
7938
|
body: {
|
|
7938
7939
|
...body,
|
|
7939
7940
|
stream: true
|
|
7940
7941
|
},
|
|
7941
7942
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7942
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
7943
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
7943
7944
|
openaiResponsesChunkSchema
|
|
7944
7945
|
),
|
|
7945
7946
|
abortSignal: options.abortSignal,
|
|
@@ -8032,7 +8033,7 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
8032
8033
|
type: "source",
|
|
8033
8034
|
source: {
|
|
8034
8035
|
sourceType: "url",
|
|
8035
|
-
id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
|
|
8036
|
+
id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId$1(),
|
|
8036
8037
|
url: value.annotation.url,
|
|
8037
8038
|
title: value.annotation.title
|
|
8038
8039
|
}
|
|
@@ -8300,12 +8301,12 @@ var OpenAISpeechModel = class {
|
|
|
8300
8301
|
value: audio,
|
|
8301
8302
|
responseHeaders,
|
|
8302
8303
|
rawValue: rawResponse
|
|
8303
|
-
} = await postJsonToApi({
|
|
8304
|
+
} = await postJsonToApi$1({
|
|
8304
8305
|
url: this.config.url({
|
|
8305
8306
|
path: "/audio/speech",
|
|
8306
8307
|
modelId: this.modelId
|
|
8307
8308
|
}),
|
|
8308
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
8309
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
8309
8310
|
body: requestBody,
|
|
8310
8311
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
8311
8312
|
successfulResponseHandler: createBinaryResponseHandler(),
|
|
@@ -8331,11 +8332,11 @@ var OpenAISpeechModel = class {
|
|
|
8331
8332
|
// src/openai-provider.ts
|
|
8332
8333
|
function createOpenAI(options = {}) {
|
|
8333
8334
|
var _a, _b, _c;
|
|
8334
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
|
|
8335
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
|
|
8335
8336
|
const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
|
|
8336
8337
|
const providerName = (_c = options.name) != null ? _c : "openai";
|
|
8337
8338
|
const getHeaders = () => ({
|
|
8338
|
-
Authorization: `Bearer ${loadApiKey({
|
|
8339
|
+
Authorization: `Bearer ${loadApiKey$1({
|
|
8339
8340
|
apiKey: options.apiKey,
|
|
8340
8341
|
environmentVariableName: "OPENAI_API_KEY",
|
|
8341
8342
|
description: "OpenAI"
|
|
@@ -8663,7 +8664,7 @@ var anthropicErrorDataSchema = z.object({
|
|
|
8663
8664
|
message: z.string()
|
|
8664
8665
|
})
|
|
8665
8666
|
});
|
|
8666
|
-
var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
|
|
8667
|
+
var anthropicFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
8667
8668
|
errorSchema: anthropicErrorDataSchema,
|
|
8668
8669
|
errorToMessage: (data) => data.error.message
|
|
8669
8670
|
});
|
|
@@ -8781,7 +8782,7 @@ function prepareTools$2(mode) {
|
|
|
8781
8782
|
};
|
|
8782
8783
|
default: {
|
|
8783
8784
|
const _exhaustiveCheck = type;
|
|
8784
|
-
throw new UnsupportedFunctionalityError({
|
|
8785
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8785
8786
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
8786
8787
|
});
|
|
8787
8788
|
}
|
|
@@ -8810,7 +8811,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8810
8811
|
switch (type) {
|
|
8811
8812
|
case "system": {
|
|
8812
8813
|
if (system != null) {
|
|
8813
|
-
throw new UnsupportedFunctionalityError({
|
|
8814
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8814
8815
|
functionality: "Multiple system messages that are separated by user/assistant messages"
|
|
8815
8816
|
});
|
|
8816
8817
|
}
|
|
@@ -8849,7 +8850,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8849
8850
|
} : {
|
|
8850
8851
|
type: "base64",
|
|
8851
8852
|
media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
|
|
8852
|
-
data: convertUint8ArrayToBase64(part.image)
|
|
8853
|
+
data: convertUint8ArrayToBase64$1(part.image)
|
|
8853
8854
|
},
|
|
8854
8855
|
cache_control: cacheControl
|
|
8855
8856
|
});
|
|
@@ -8857,7 +8858,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8857
8858
|
}
|
|
8858
8859
|
case "file": {
|
|
8859
8860
|
if (part.mimeType !== "application/pdf") {
|
|
8860
|
-
throw new UnsupportedFunctionalityError({
|
|
8861
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8861
8862
|
functionality: "Non-PDF files in user messages"
|
|
8862
8863
|
});
|
|
8863
8864
|
}
|
|
@@ -9154,7 +9155,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9154
9155
|
};
|
|
9155
9156
|
if (isThinking) {
|
|
9156
9157
|
if (thinkingBudget == null) {
|
|
9157
|
-
throw new UnsupportedFunctionalityError({
|
|
9158
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9158
9159
|
functionality: "thinking requires a budget"
|
|
9159
9160
|
});
|
|
9160
9161
|
}
|
|
@@ -9199,7 +9200,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9199
9200
|
};
|
|
9200
9201
|
}
|
|
9201
9202
|
case "object-json": {
|
|
9202
|
-
throw new UnsupportedFunctionalityError({
|
|
9203
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9203
9204
|
functionality: "json-mode object generation"
|
|
9204
9205
|
});
|
|
9205
9206
|
}
|
|
@@ -9225,7 +9226,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9225
9226
|
betas,
|
|
9226
9227
|
headers
|
|
9227
9228
|
}) {
|
|
9228
|
-
return combineHeaders(
|
|
9229
|
+
return combineHeaders$1(
|
|
9229
9230
|
await resolve(this.config.headers),
|
|
9230
9231
|
betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
|
|
9231
9232
|
headers
|
|
@@ -9246,12 +9247,12 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9246
9247
|
responseHeaders,
|
|
9247
9248
|
value: response,
|
|
9248
9249
|
rawValue: rawResponse
|
|
9249
|
-
} = await postJsonToApi({
|
|
9250
|
+
} = await postJsonToApi$1({
|
|
9250
9251
|
url: this.buildRequestUrl(false),
|
|
9251
9252
|
headers: await this.getHeaders({ betas, headers: options.headers }),
|
|
9252
9253
|
body: this.transformRequestBody(args),
|
|
9253
9254
|
failedResponseHandler: anthropicFailedResponseHandler,
|
|
9254
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
9255
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
9255
9256
|
anthropicMessagesResponseSchema
|
|
9256
9257
|
),
|
|
9257
9258
|
abortSignal: options.abortSignal,
|
|
@@ -9321,12 +9322,12 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9321
9322
|
async doStream(options) {
|
|
9322
9323
|
const { args, warnings, betas } = await this.getArgs(options);
|
|
9323
9324
|
const body = { ...args, stream: true };
|
|
9324
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
9325
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
9325
9326
|
url: this.buildRequestUrl(true),
|
|
9326
9327
|
headers: await this.getHeaders({ betas, headers: options.headers }),
|
|
9327
9328
|
body: this.transformRequestBody(body),
|
|
9328
9329
|
failedResponseHandler: anthropicFailedResponseHandler,
|
|
9329
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
9330
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
9330
9331
|
anthropicMessagesChunkSchema
|
|
9331
9332
|
),
|
|
9332
9333
|
abortSignal: options.abortSignal,
|
|
@@ -9767,10 +9768,10 @@ var anthropicTools = {
|
|
|
9767
9768
|
// src/anthropic-provider.ts
|
|
9768
9769
|
function createAnthropic(options = {}) {
|
|
9769
9770
|
var _a;
|
|
9770
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
|
|
9771
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
|
|
9771
9772
|
const getHeaders = () => ({
|
|
9772
9773
|
"anthropic-version": "2023-06-01",
|
|
9773
|
-
"x-api-key": loadApiKey({
|
|
9774
|
+
"x-api-key": loadApiKey$1({
|
|
9774
9775
|
apiKey: options.apiKey,
|
|
9775
9776
|
environmentVariableName: "ANTHROPIC_API_KEY",
|
|
9776
9777
|
description: "Anthropic"
|
|
@@ -9910,7 +9911,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9910
9911
|
switch (role) {
|
|
9911
9912
|
case "system": {
|
|
9912
9913
|
if (!systemMessagesAllowed) {
|
|
9913
|
-
throw new UnsupportedFunctionalityError({
|
|
9914
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9914
9915
|
functionality: "system messages are only supported at the beginning of the conversation"
|
|
9915
9916
|
});
|
|
9916
9917
|
}
|
|
@@ -9936,7 +9937,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9936
9937
|
} : {
|
|
9937
9938
|
inlineData: {
|
|
9938
9939
|
mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
|
|
9939
|
-
data: convertUint8ArrayToBase64(part.image)
|
|
9940
|
+
data: convertUint8ArrayToBase64$1(part.image)
|
|
9940
9941
|
}
|
|
9941
9942
|
}
|
|
9942
9943
|
);
|
|
@@ -9974,12 +9975,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9974
9975
|
}
|
|
9975
9976
|
case "file": {
|
|
9976
9977
|
if (part.mimeType !== "image/png") {
|
|
9977
|
-
throw new UnsupportedFunctionalityError({
|
|
9978
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9978
9979
|
functionality: "Only PNG images are supported in assistant messages"
|
|
9979
9980
|
});
|
|
9980
9981
|
}
|
|
9981
9982
|
if (part.data instanceof URL) {
|
|
9982
|
-
throw new UnsupportedFunctionalityError({
|
|
9983
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9983
9984
|
functionality: "File data URLs in assistant messages are not supported"
|
|
9984
9985
|
});
|
|
9985
9986
|
}
|
|
@@ -10038,7 +10039,7 @@ var googleErrorDataSchema = z.object({
|
|
|
10038
10039
|
status: z.string()
|
|
10039
10040
|
})
|
|
10040
10041
|
});
|
|
10041
|
-
var googleFailedResponseHandler = createJsonErrorResponseHandler({
|
|
10042
|
+
var googleFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
10042
10043
|
errorSchema: googleErrorDataSchema,
|
|
10043
10044
|
errorToMessage: (data) => data.error.message
|
|
10044
10045
|
});
|
|
@@ -10113,7 +10114,7 @@ function prepareTools$1(mode, useSearchGrounding, dynamicRetrievalConfig, modelI
|
|
|
10113
10114
|
};
|
|
10114
10115
|
default: {
|
|
10115
10116
|
const _exhaustiveCheck = type;
|
|
10116
|
-
throw new UnsupportedFunctionalityError({
|
|
10117
|
+
throw new UnsupportedFunctionalityError$1({
|
|
10117
10118
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
10118
10119
|
});
|
|
10119
10120
|
}
|
|
@@ -10284,7 +10285,7 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10284
10285
|
var _a, _b, _c, _d, _e;
|
|
10285
10286
|
const { args, warnings } = await this.getArgs(options);
|
|
10286
10287
|
const body = JSON.stringify(args);
|
|
10287
|
-
const mergedHeaders = combineHeaders(
|
|
10288
|
+
const mergedHeaders = combineHeaders$1(
|
|
10288
10289
|
await resolve(this.config.headers),
|
|
10289
10290
|
options.headers
|
|
10290
10291
|
);
|
|
@@ -10292,14 +10293,14 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10292
10293
|
responseHeaders,
|
|
10293
10294
|
value: response,
|
|
10294
10295
|
rawValue: rawResponse
|
|
10295
|
-
} = await postJsonToApi({
|
|
10296
|
+
} = await postJsonToApi$1({
|
|
10296
10297
|
url: `${this.config.baseURL}/${getModelPath(
|
|
10297
10298
|
this.modelId
|
|
10298
10299
|
)}:generateContent`,
|
|
10299
10300
|
headers: mergedHeaders,
|
|
10300
10301
|
body: args,
|
|
10301
10302
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10302
|
-
successfulResponseHandler: createJsonResponseHandler(responseSchema),
|
|
10303
|
+
successfulResponseHandler: createJsonResponseHandler$1(responseSchema),
|
|
10303
10304
|
abortSignal: options.abortSignal,
|
|
10304
10305
|
fetch: this.config.fetch
|
|
10305
10306
|
});
|
|
@@ -10345,18 +10346,18 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10345
10346
|
async doStream(options) {
|
|
10346
10347
|
const { args, warnings } = await this.getArgs(options);
|
|
10347
10348
|
const body = JSON.stringify(args);
|
|
10348
|
-
const headers = combineHeaders(
|
|
10349
|
+
const headers = combineHeaders$1(
|
|
10349
10350
|
await resolve(this.config.headers),
|
|
10350
10351
|
options.headers
|
|
10351
10352
|
);
|
|
10352
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
10353
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
10353
10354
|
url: `${this.config.baseURL}/${getModelPath(
|
|
10354
10355
|
this.modelId
|
|
10355
10356
|
)}:streamGenerateContent?alt=sse`,
|
|
10356
10357
|
headers,
|
|
10357
10358
|
body: args,
|
|
10358
10359
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10359
|
-
successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
|
|
10360
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(chunkSchema),
|
|
10360
10361
|
abortSignal: options.abortSignal,
|
|
10361
10362
|
fetch: this.config.fetch
|
|
10362
10363
|
});
|
|
@@ -10632,11 +10633,11 @@ var GoogleGenerativeAIEmbeddingModel = class {
|
|
|
10632
10633
|
values
|
|
10633
10634
|
});
|
|
10634
10635
|
}
|
|
10635
|
-
const mergedHeaders = combineHeaders(
|
|
10636
|
+
const mergedHeaders = combineHeaders$1(
|
|
10636
10637
|
await resolve(this.config.headers),
|
|
10637
10638
|
headers
|
|
10638
10639
|
);
|
|
10639
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
10640
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
10640
10641
|
url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
|
|
10641
10642
|
headers: mergedHeaders,
|
|
10642
10643
|
body: {
|
|
@@ -10648,7 +10649,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
|
|
|
10648
10649
|
}))
|
|
10649
10650
|
},
|
|
10650
10651
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10651
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
10652
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
10652
10653
|
googleGenerativeAITextEmbeddingResponseSchema
|
|
10653
10654
|
),
|
|
10654
10655
|
abortSignal,
|
|
@@ -10673,9 +10674,9 @@ function isSupportedFileUrl(url) {
|
|
|
10673
10674
|
// src/google-provider.ts
|
|
10674
10675
|
function createGoogleGenerativeAI(options = {}) {
|
|
10675
10676
|
var _a;
|
|
10676
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
|
|
10677
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
|
|
10677
10678
|
const getHeaders = () => ({
|
|
10678
|
-
"x-goog-api-key": loadApiKey({
|
|
10679
|
+
"x-goog-api-key": loadApiKey$1({
|
|
10679
10680
|
apiKey: options.apiKey,
|
|
10680
10681
|
environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
|
|
10681
10682
|
description: "Google Generative AI"
|
|
@@ -10688,7 +10689,7 @@ function createGoogleGenerativeAI(options = {}) {
|
|
|
10688
10689
|
provider: "google.generative-ai",
|
|
10689
10690
|
baseURL,
|
|
10690
10691
|
headers: getHeaders,
|
|
10691
|
-
generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
|
|
10692
|
+
generateId: (_a2 = options.generateId) != null ? _a2 : generateId$1,
|
|
10692
10693
|
isSupportedUrl: isSupportedFileUrl,
|
|
10693
10694
|
fetch: options.fetch
|
|
10694
10695
|
});
|
|
@@ -11526,9 +11527,9 @@ var BedrockErrorSchema = z.object({
|
|
|
11526
11527
|
type: z.string().nullish()
|
|
11527
11528
|
});
|
|
11528
11529
|
var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
11529
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
11530
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
11530
11531
|
if (response.body == null) {
|
|
11531
|
-
throw new EmptyResponseBodyError({});
|
|
11532
|
+
throw new EmptyResponseBodyError$1({});
|
|
11532
11533
|
}
|
|
11533
11534
|
const codec = new EventStreamCodec(toUtf8, fromUtf8);
|
|
11534
11535
|
let buffer = new Uint8Array(0);
|
|
@@ -11558,7 +11559,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
|
|
|
11558
11559
|
buffer = buffer.slice(totalLength);
|
|
11559
11560
|
if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
|
|
11560
11561
|
const data = textDecoder.decode(decoded.body);
|
|
11561
|
-
const parsedDataResult = safeParseJSON({ text: data });
|
|
11562
|
+
const parsedDataResult = safeParseJSON$1({ text: data });
|
|
11562
11563
|
if (!parsedDataResult.success) {
|
|
11563
11564
|
controller.enqueue(parsedDataResult);
|
|
11564
11565
|
break;
|
|
@@ -11567,7 +11568,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
|
|
|
11567
11568
|
let wrappedData = {
|
|
11568
11569
|
[(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
|
|
11569
11570
|
};
|
|
11570
|
-
const validatedWrappedData = safeValidateTypes({
|
|
11571
|
+
const validatedWrappedData = safeValidateTypes$1({
|
|
11571
11572
|
value: wrappedData,
|
|
11572
11573
|
schema: chunkSchema
|
|
11573
11574
|
});
|
|
@@ -11650,13 +11651,13 @@ function prepareTools(mode) {
|
|
|
11650
11651
|
};
|
|
11651
11652
|
default: {
|
|
11652
11653
|
const _exhaustiveCheck = type;
|
|
11653
|
-
throw new UnsupportedFunctionalityError({
|
|
11654
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11654
11655
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
11655
11656
|
});
|
|
11656
11657
|
}
|
|
11657
11658
|
}
|
|
11658
11659
|
}
|
|
11659
|
-
var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
|
|
11660
|
+
var generateFileId = createIdGenerator$1({ prefix: "file", size: 16 });
|
|
11660
11661
|
function getCachePoint(providerMetadata) {
|
|
11661
11662
|
var _a;
|
|
11662
11663
|
return (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.cachePoint;
|
|
@@ -11673,7 +11674,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11673
11674
|
switch (type) {
|
|
11674
11675
|
case "system": {
|
|
11675
11676
|
if (messages.length > 0) {
|
|
11676
|
-
throw new UnsupportedFunctionalityError({
|
|
11677
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11677
11678
|
functionality: "Multiple system messages that are separated by user/assistant messages"
|
|
11678
11679
|
});
|
|
11679
11680
|
}
|
|
@@ -11702,7 +11703,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11702
11703
|
}
|
|
11703
11704
|
case "image": {
|
|
11704
11705
|
if (part.image instanceof URL) {
|
|
11705
|
-
throw new UnsupportedFunctionalityError({
|
|
11706
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11706
11707
|
functionality: "Image URLs in user messages"
|
|
11707
11708
|
});
|
|
11708
11709
|
}
|
|
@@ -11712,7 +11713,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11712
11713
|
"/"
|
|
11713
11714
|
)) == null ? void 0 : _b[1],
|
|
11714
11715
|
source: {
|
|
11715
|
-
bytes: convertUint8ArrayToBase64(
|
|
11716
|
+
bytes: convertUint8ArrayToBase64$1(
|
|
11716
11717
|
(_c = part.image) != null ? _c : part.image
|
|
11717
11718
|
)
|
|
11718
11719
|
}
|
|
@@ -11722,7 +11723,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11722
11723
|
}
|
|
11723
11724
|
case "file": {
|
|
11724
11725
|
if (part.data instanceof URL) {
|
|
11725
|
-
throw new UnsupportedFunctionalityError({
|
|
11726
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11726
11727
|
functionality: "File URLs in user messages"
|
|
11727
11728
|
});
|
|
11728
11729
|
}
|
|
@@ -12012,7 +12013,7 @@ var BedrockChatLanguageModel = class {
|
|
|
12012
12013
|
(_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.reasoning_config
|
|
12013
12014
|
);
|
|
12014
12015
|
if (!reasoningConfigOptions.success) {
|
|
12015
|
-
throw new InvalidArgumentError({
|
|
12016
|
+
throw new InvalidArgumentError$1({
|
|
12016
12017
|
argument: "providerOptions.bedrock.reasoning_config",
|
|
12017
12018
|
message: "invalid reasoning configuration options",
|
|
12018
12019
|
cause: reasoningConfigOptions.error
|
|
@@ -12077,7 +12078,7 @@ var BedrockChatLanguageModel = class {
|
|
|
12077
12078
|
};
|
|
12078
12079
|
}
|
|
12079
12080
|
case "object-json": {
|
|
12080
|
-
throw new UnsupportedFunctionalityError({
|
|
12081
|
+
throw new UnsupportedFunctionalityError$1({
|
|
12081
12082
|
functionality: "json-mode object generation"
|
|
12082
12083
|
});
|
|
12083
12084
|
}
|
|
@@ -12113,21 +12114,21 @@ var BedrockChatLanguageModel = class {
|
|
|
12113
12114
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
|
|
12114
12115
|
const { command: args, warnings } = this.getArgs(options);
|
|
12115
12116
|
const url = `${this.getUrl(this.modelId)}/converse`;
|
|
12116
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12117
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12117
12118
|
url,
|
|
12118
|
-
headers: combineHeaders(
|
|
12119
|
+
headers: combineHeaders$1(
|
|
12119
12120
|
await resolve(this.config.headers),
|
|
12120
12121
|
options.headers
|
|
12121
12122
|
),
|
|
12122
12123
|
body: args,
|
|
12123
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12124
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12124
12125
|
errorSchema: BedrockErrorSchema,
|
|
12125
12126
|
errorToMessage: (error) => {
|
|
12126
12127
|
var _a2;
|
|
12127
12128
|
return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
|
|
12128
12129
|
}
|
|
12129
12130
|
}),
|
|
12130
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12131
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12131
12132
|
BedrockResponseSchema
|
|
12132
12133
|
),
|
|
12133
12134
|
abortSignal: options.abortSignal,
|
|
@@ -12195,14 +12196,14 @@ var BedrockChatLanguageModel = class {
|
|
|
12195
12196
|
async doStream(options) {
|
|
12196
12197
|
const { command: args, warnings } = this.getArgs(options);
|
|
12197
12198
|
const url = `${this.getUrl(this.modelId)}/converse-stream`;
|
|
12198
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12199
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12199
12200
|
url,
|
|
12200
|
-
headers: combineHeaders(
|
|
12201
|
+
headers: combineHeaders$1(
|
|
12201
12202
|
await resolve(this.config.headers),
|
|
12202
12203
|
options.headers
|
|
12203
12204
|
),
|
|
12204
12205
|
body: args,
|
|
12205
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12206
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12206
12207
|
errorSchema: BedrockErrorSchema,
|
|
12207
12208
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12208
12209
|
}),
|
|
@@ -12485,17 +12486,17 @@ var BedrockEmbeddingModel = class {
|
|
|
12485
12486
|
normalize: this.settings.normalize
|
|
12486
12487
|
};
|
|
12487
12488
|
const url = this.getUrl(this.modelId);
|
|
12488
|
-
const { value: response } = await postJsonToApi({
|
|
12489
|
+
const { value: response } = await postJsonToApi$1({
|
|
12489
12490
|
url,
|
|
12490
12491
|
headers: await resolve(
|
|
12491
|
-
combineHeaders(await resolve(this.config.headers), headers)
|
|
12492
|
+
combineHeaders$1(await resolve(this.config.headers), headers)
|
|
12492
12493
|
),
|
|
12493
12494
|
body: args,
|
|
12494
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12495
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12495
12496
|
errorSchema: BedrockErrorSchema,
|
|
12496
12497
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12497
12498
|
}),
|
|
12498
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12499
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12499
12500
|
BedrockEmbeddingResponseSchema
|
|
12500
12501
|
),
|
|
12501
12502
|
fetch: this.config.fetch,
|
|
@@ -12580,17 +12581,17 @@ var BedrockImageModel = class {
|
|
|
12580
12581
|
});
|
|
12581
12582
|
}
|
|
12582
12583
|
const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
|
|
12583
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12584
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12584
12585
|
url: this.getUrl(this.modelId),
|
|
12585
12586
|
headers: await resolve(
|
|
12586
|
-
combineHeaders(await resolve(this.config.headers), headers)
|
|
12587
|
+
combineHeaders$1(await resolve(this.config.headers), headers)
|
|
12587
12588
|
),
|
|
12588
12589
|
body: args,
|
|
12589
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12590
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12590
12591
|
errorSchema: BedrockErrorSchema,
|
|
12591
12592
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12592
12593
|
}),
|
|
12593
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12594
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12594
12595
|
bedrockImageResponseSchema
|
|
12595
12596
|
),
|
|
12596
12597
|
abortSignal,
|
|
@@ -12649,7 +12650,7 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
|
|
|
12649
12650
|
const signer = new AwsV4Signer({
|
|
12650
12651
|
url,
|
|
12651
12652
|
method: "POST",
|
|
12652
|
-
headers: Object.entries(removeUndefinedEntries(originalHeaders)),
|
|
12653
|
+
headers: Object.entries(removeUndefinedEntries$1(originalHeaders)),
|
|
12653
12654
|
body,
|
|
12654
12655
|
region: credentials.region,
|
|
12655
12656
|
accessKeyId: credentials.accessKeyId,
|
|
@@ -12662,8 +12663,8 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
|
|
|
12662
12663
|
return fetch(input, {
|
|
12663
12664
|
...init,
|
|
12664
12665
|
body,
|
|
12665
|
-
headers: removeUndefinedEntries(
|
|
12666
|
-
combineHeaders(originalHeaders, signedHeaders)
|
|
12666
|
+
headers: removeUndefinedEntries$1(
|
|
12667
|
+
combineHeaders$1(originalHeaders, signedHeaders)
|
|
12667
12668
|
)
|
|
12668
12669
|
});
|
|
12669
12670
|
};
|
|
@@ -12717,7 +12718,7 @@ function createAmazonBedrock(options = {}) {
|
|
|
12717
12718
|
}, options.fetch);
|
|
12718
12719
|
const getBaseUrl = () => {
|
|
12719
12720
|
var _a, _b;
|
|
12720
|
-
return (_b = withoutTrailingSlash(
|
|
12721
|
+
return (_b = withoutTrailingSlash$1(
|
|
12721
12722
|
(_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
|
|
12722
12723
|
settingValue: options.region,
|
|
12723
12724
|
settingName: "region",
|
|
@@ -12732,7 +12733,7 @@ function createAmazonBedrock(options = {}) {
|
|
|
12732
12733
|
baseUrl: getBaseUrl,
|
|
12733
12734
|
headers: (_a = options.headers) != null ? _a : {},
|
|
12734
12735
|
fetch: sigv4Fetch,
|
|
12735
|
-
generateId
|
|
12736
|
+
generateId: generateId$1
|
|
12736
12737
|
});
|
|
12737
12738
|
};
|
|
12738
12739
|
const provider = function(modelId, settings) {
|
|
@@ -12769,29 +12770,2065 @@ function createAmazonBedrock(options = {}) {
|
|
|
12769
12770
|
}
|
|
12770
12771
|
createAmazonBedrock();
|
|
12771
12772
|
|
|
12772
|
-
|
|
12773
|
-
|
|
12774
|
-
|
|
12775
|
-
|
|
12776
|
-
|
|
12777
|
-
|
|
12778
|
-
|
|
12779
|
-
|
|
12780
|
-
|
|
12781
|
-
|
|
12782
|
-
|
|
12783
|
-
|
|
12784
|
-
|
|
12785
|
-
|
|
12786
|
-
|
|
12787
|
-
|
|
12788
|
-
|
|
12789
|
-
|
|
12790
|
-
|
|
12791
|
-
|
|
12792
|
-
|
|
12793
|
-
|
|
12794
|
-
|
|
12773
|
+
// src/errors/ai-sdk-error.ts
|
|
12774
|
+
var marker = "vercel.ai.error";
|
|
12775
|
+
var symbol = Symbol.for(marker);
|
|
12776
|
+
var _a;
|
|
12777
|
+
var _AISDKError = class _AISDKError extends Error {
|
|
12778
|
+
/**
|
|
12779
|
+
* Creates an AI SDK Error.
|
|
12780
|
+
*
|
|
12781
|
+
* @param {Object} params - The parameters for creating the error.
|
|
12782
|
+
* @param {string} params.name - The name of the error.
|
|
12783
|
+
* @param {string} params.message - The error message.
|
|
12784
|
+
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
12785
|
+
*/
|
|
12786
|
+
constructor({
|
|
12787
|
+
name: name14,
|
|
12788
|
+
message,
|
|
12789
|
+
cause
|
|
12790
|
+
}) {
|
|
12791
|
+
super(message);
|
|
12792
|
+
this[_a] = true;
|
|
12793
|
+
this.name = name14;
|
|
12794
|
+
this.cause = cause;
|
|
12795
|
+
}
|
|
12796
|
+
/**
|
|
12797
|
+
* Checks if the given error is an AI SDK Error.
|
|
12798
|
+
* @param {unknown} error - The error to check.
|
|
12799
|
+
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
12800
|
+
*/
|
|
12801
|
+
static isInstance(error) {
|
|
12802
|
+
return _AISDKError.hasMarker(error, marker);
|
|
12803
|
+
}
|
|
12804
|
+
static hasMarker(error, marker15) {
|
|
12805
|
+
const markerSymbol = Symbol.for(marker15);
|
|
12806
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
12807
|
+
}
|
|
12808
|
+
};
|
|
12809
|
+
_a = symbol;
|
|
12810
|
+
var AISDKError = _AISDKError;
|
|
12811
|
+
|
|
12812
|
+
// src/errors/api-call-error.ts
|
|
12813
|
+
var name = "AI_APICallError";
|
|
12814
|
+
var marker2 = `vercel.ai.error.${name}`;
|
|
12815
|
+
var symbol2 = Symbol.for(marker2);
|
|
12816
|
+
var _a2;
|
|
12817
|
+
var APICallError = class extends AISDKError {
|
|
12818
|
+
constructor({
|
|
12819
|
+
message,
|
|
12820
|
+
url,
|
|
12821
|
+
requestBodyValues,
|
|
12822
|
+
statusCode,
|
|
12823
|
+
responseHeaders,
|
|
12824
|
+
responseBody,
|
|
12825
|
+
cause,
|
|
12826
|
+
isRetryable = statusCode != null && (statusCode === 408 || // request timeout
|
|
12827
|
+
statusCode === 409 || // conflict
|
|
12828
|
+
statusCode === 429 || // too many requests
|
|
12829
|
+
statusCode >= 500),
|
|
12830
|
+
// server error
|
|
12831
|
+
data
|
|
12832
|
+
}) {
|
|
12833
|
+
super({ name, message, cause });
|
|
12834
|
+
this[_a2] = true;
|
|
12835
|
+
this.url = url;
|
|
12836
|
+
this.requestBodyValues = requestBodyValues;
|
|
12837
|
+
this.statusCode = statusCode;
|
|
12838
|
+
this.responseHeaders = responseHeaders;
|
|
12839
|
+
this.responseBody = responseBody;
|
|
12840
|
+
this.isRetryable = isRetryable;
|
|
12841
|
+
this.data = data;
|
|
12842
|
+
}
|
|
12843
|
+
static isInstance(error) {
|
|
12844
|
+
return AISDKError.hasMarker(error, marker2);
|
|
12845
|
+
}
|
|
12846
|
+
};
|
|
12847
|
+
_a2 = symbol2;
|
|
12848
|
+
|
|
12849
|
+
// src/errors/empty-response-body-error.ts
|
|
12850
|
+
var name2 = "AI_EmptyResponseBodyError";
|
|
12851
|
+
var marker3 = `vercel.ai.error.${name2}`;
|
|
12852
|
+
var symbol3 = Symbol.for(marker3);
|
|
12853
|
+
var _a3;
|
|
12854
|
+
var EmptyResponseBodyError = class extends AISDKError {
|
|
12855
|
+
// used in isInstance
|
|
12856
|
+
constructor({ message = "Empty response body" } = {}) {
|
|
12857
|
+
super({ name: name2, message });
|
|
12858
|
+
this[_a3] = true;
|
|
12859
|
+
}
|
|
12860
|
+
static isInstance(error) {
|
|
12861
|
+
return AISDKError.hasMarker(error, marker3);
|
|
12862
|
+
}
|
|
12863
|
+
};
|
|
12864
|
+
_a3 = symbol3;
|
|
12865
|
+
|
|
12866
|
+
// src/errors/get-error-message.ts
|
|
12867
|
+
function getErrorMessage(error) {
|
|
12868
|
+
if (error == null) {
|
|
12869
|
+
return "unknown error";
|
|
12870
|
+
}
|
|
12871
|
+
if (typeof error === "string") {
|
|
12872
|
+
return error;
|
|
12873
|
+
}
|
|
12874
|
+
if (error instanceof Error) {
|
|
12875
|
+
return error.message;
|
|
12876
|
+
}
|
|
12877
|
+
return JSON.stringify(error);
|
|
12878
|
+
}
|
|
12879
|
+
|
|
12880
|
+
// src/errors/invalid-argument-error.ts
|
|
12881
|
+
var name3 = "AI_InvalidArgumentError";
|
|
12882
|
+
var marker4 = `vercel.ai.error.${name3}`;
|
|
12883
|
+
var symbol4 = Symbol.for(marker4);
|
|
12884
|
+
var _a4;
|
|
12885
|
+
var InvalidArgumentError = class extends AISDKError {
|
|
12886
|
+
constructor({
|
|
12887
|
+
message,
|
|
12888
|
+
cause,
|
|
12889
|
+
argument
|
|
12890
|
+
}) {
|
|
12891
|
+
super({ name: name3, message, cause });
|
|
12892
|
+
this[_a4] = true;
|
|
12893
|
+
this.argument = argument;
|
|
12894
|
+
}
|
|
12895
|
+
static isInstance(error) {
|
|
12896
|
+
return AISDKError.hasMarker(error, marker4);
|
|
12897
|
+
}
|
|
12898
|
+
};
|
|
12899
|
+
_a4 = symbol4;
|
|
12900
|
+
|
|
12901
|
+
// src/errors/invalid-prompt-error.ts
|
|
12902
|
+
var name4 = "AI_InvalidPromptError";
|
|
12903
|
+
var marker5 = `vercel.ai.error.${name4}`;
|
|
12904
|
+
var symbol5 = Symbol.for(marker5);
|
|
12905
|
+
var _a5;
|
|
12906
|
+
var InvalidPromptError = class extends AISDKError {
|
|
12907
|
+
constructor({
|
|
12908
|
+
prompt,
|
|
12909
|
+
message,
|
|
12910
|
+
cause
|
|
12911
|
+
}) {
|
|
12912
|
+
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
12913
|
+
this[_a5] = true;
|
|
12914
|
+
this.prompt = prompt;
|
|
12915
|
+
}
|
|
12916
|
+
static isInstance(error) {
|
|
12917
|
+
return AISDKError.hasMarker(error, marker5);
|
|
12918
|
+
}
|
|
12919
|
+
};
|
|
12920
|
+
_a5 = symbol5;
|
|
12921
|
+
|
|
12922
|
+
// src/errors/invalid-response-data-error.ts
|
|
12923
|
+
var name5 = "AI_InvalidResponseDataError";
|
|
12924
|
+
var marker6 = `vercel.ai.error.${name5}`;
|
|
12925
|
+
var symbol6 = Symbol.for(marker6);
|
|
12926
|
+
var _a6;
|
|
12927
|
+
var InvalidResponseDataError = class extends AISDKError {
|
|
12928
|
+
constructor({
|
|
12929
|
+
data,
|
|
12930
|
+
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
12931
|
+
}) {
|
|
12932
|
+
super({ name: name5, message });
|
|
12933
|
+
this[_a6] = true;
|
|
12934
|
+
this.data = data;
|
|
12935
|
+
}
|
|
12936
|
+
static isInstance(error) {
|
|
12937
|
+
return AISDKError.hasMarker(error, marker6);
|
|
12938
|
+
}
|
|
12939
|
+
};
|
|
12940
|
+
_a6 = symbol6;
|
|
12941
|
+
|
|
12942
|
+
// src/errors/json-parse-error.ts
|
|
12943
|
+
var name6 = "AI_JSONParseError";
|
|
12944
|
+
var marker7 = `vercel.ai.error.${name6}`;
|
|
12945
|
+
var symbol7 = Symbol.for(marker7);
|
|
12946
|
+
var _a7;
|
|
12947
|
+
var JSONParseError = class extends AISDKError {
|
|
12948
|
+
constructor({ text, cause }) {
|
|
12949
|
+
super({
|
|
12950
|
+
name: name6,
|
|
12951
|
+
message: `JSON parsing failed: Text: ${text}.
|
|
12952
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
12953
|
+
cause
|
|
12954
|
+
});
|
|
12955
|
+
this[_a7] = true;
|
|
12956
|
+
this.text = text;
|
|
12957
|
+
}
|
|
12958
|
+
static isInstance(error) {
|
|
12959
|
+
return AISDKError.hasMarker(error, marker7);
|
|
12960
|
+
}
|
|
12961
|
+
};
|
|
12962
|
+
_a7 = symbol7;
|
|
12963
|
+
|
|
12964
|
+
// src/errors/load-api-key-error.ts
|
|
12965
|
+
var name7 = "AI_LoadAPIKeyError";
|
|
12966
|
+
var marker8 = `vercel.ai.error.${name7}`;
|
|
12967
|
+
var symbol8 = Symbol.for(marker8);
|
|
12968
|
+
var _a8;
|
|
12969
|
+
var LoadAPIKeyError = class extends AISDKError {
|
|
12970
|
+
// used in isInstance
|
|
12971
|
+
constructor({ message }) {
|
|
12972
|
+
super({ name: name7, message });
|
|
12973
|
+
this[_a8] = true;
|
|
12974
|
+
}
|
|
12975
|
+
static isInstance(error) {
|
|
12976
|
+
return AISDKError.hasMarker(error, marker8);
|
|
12977
|
+
}
|
|
12978
|
+
};
|
|
12979
|
+
_a8 = symbol8;
|
|
12980
|
+
|
|
12981
|
+
// src/errors/type-validation-error.ts
|
|
12982
|
+
var name12 = "AI_TypeValidationError";
|
|
12983
|
+
var marker13 = `vercel.ai.error.${name12}`;
|
|
12984
|
+
var symbol13 = Symbol.for(marker13);
|
|
12985
|
+
var _a13;
|
|
12986
|
+
var _TypeValidationError = class _TypeValidationError extends AISDKError {
|
|
12987
|
+
constructor({ value, cause }) {
|
|
12988
|
+
super({
|
|
12989
|
+
name: name12,
|
|
12990
|
+
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
12991
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
12992
|
+
cause
|
|
12993
|
+
});
|
|
12994
|
+
this[_a13] = true;
|
|
12995
|
+
this.value = value;
|
|
12996
|
+
}
|
|
12997
|
+
static isInstance(error) {
|
|
12998
|
+
return AISDKError.hasMarker(error, marker13);
|
|
12999
|
+
}
|
|
13000
|
+
/**
|
|
13001
|
+
* Wraps an error into a TypeValidationError.
|
|
13002
|
+
* If the cause is already a TypeValidationError with the same value, it returns the cause.
|
|
13003
|
+
* Otherwise, it creates a new TypeValidationError.
|
|
13004
|
+
*
|
|
13005
|
+
* @param {Object} params - The parameters for wrapping the error.
|
|
13006
|
+
* @param {unknown} params.value - The value that failed validation.
|
|
13007
|
+
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
13008
|
+
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
13009
|
+
*/
|
|
13010
|
+
static wrap({
|
|
13011
|
+
value,
|
|
13012
|
+
cause
|
|
13013
|
+
}) {
|
|
13014
|
+
return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
|
|
13015
|
+
}
|
|
13016
|
+
};
|
|
13017
|
+
_a13 = symbol13;
|
|
13018
|
+
var TypeValidationError = _TypeValidationError;
|
|
13019
|
+
|
|
13020
|
+
// src/errors/unsupported-functionality-error.ts
|
|
13021
|
+
var name13 = "AI_UnsupportedFunctionalityError";
|
|
13022
|
+
var marker14 = `vercel.ai.error.${name13}`;
|
|
13023
|
+
var symbol14 = Symbol.for(marker14);
|
|
13024
|
+
var _a14;
|
|
13025
|
+
var UnsupportedFunctionalityError = class extends AISDKError {
|
|
13026
|
+
constructor({
|
|
13027
|
+
functionality,
|
|
13028
|
+
message = `'${functionality}' functionality not supported.`
|
|
13029
|
+
}) {
|
|
13030
|
+
super({ name: name13, message });
|
|
13031
|
+
this[_a14] = true;
|
|
13032
|
+
this.functionality = functionality;
|
|
13033
|
+
}
|
|
13034
|
+
static isInstance(error) {
|
|
13035
|
+
return AISDKError.hasMarker(error, marker14);
|
|
13036
|
+
}
|
|
13037
|
+
};
|
|
13038
|
+
_a14 = symbol14;
|
|
13039
|
+
|
|
13040
|
+
var secureJsonParse = {exports: {}};
|
|
13041
|
+
|
|
13042
|
+
var hasRequiredSecureJsonParse;
|
|
13043
|
+
|
|
13044
|
+
function requireSecureJsonParse () {
|
|
13045
|
+
if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
|
|
13046
|
+
hasRequiredSecureJsonParse = 1;
|
|
13047
|
+
|
|
13048
|
+
const hasBuffer = typeof Buffer !== 'undefined';
|
|
13049
|
+
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
13050
|
+
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
13051
|
+
|
|
13052
|
+
function _parse (text, reviver, options) {
|
|
13053
|
+
// Normalize arguments
|
|
13054
|
+
if (options == null) {
|
|
13055
|
+
if (reviver !== null && typeof reviver === 'object') {
|
|
13056
|
+
options = reviver;
|
|
13057
|
+
reviver = undefined;
|
|
13058
|
+
}
|
|
13059
|
+
}
|
|
13060
|
+
|
|
13061
|
+
if (hasBuffer && Buffer.isBuffer(text)) {
|
|
13062
|
+
text = text.toString();
|
|
13063
|
+
}
|
|
13064
|
+
|
|
13065
|
+
// BOM checker
|
|
13066
|
+
if (text && text.charCodeAt(0) === 0xFEFF) {
|
|
13067
|
+
text = text.slice(1);
|
|
13068
|
+
}
|
|
13069
|
+
|
|
13070
|
+
// Parse normally, allowing exceptions
|
|
13071
|
+
const obj = JSON.parse(text, reviver);
|
|
13072
|
+
|
|
13073
|
+
// Ignore null and non-objects
|
|
13074
|
+
if (obj === null || typeof obj !== 'object') {
|
|
13075
|
+
return obj
|
|
13076
|
+
}
|
|
13077
|
+
|
|
13078
|
+
const protoAction = (options && options.protoAction) || 'error';
|
|
13079
|
+
const constructorAction = (options && options.constructorAction) || 'error';
|
|
13080
|
+
|
|
13081
|
+
// options: 'error' (default) / 'remove' / 'ignore'
|
|
13082
|
+
if (protoAction === 'ignore' && constructorAction === 'ignore') {
|
|
13083
|
+
return obj
|
|
13084
|
+
}
|
|
13085
|
+
|
|
13086
|
+
if (protoAction !== 'ignore' && constructorAction !== 'ignore') {
|
|
13087
|
+
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
|
|
13088
|
+
return obj
|
|
13089
|
+
}
|
|
13090
|
+
} else if (protoAction !== 'ignore' && constructorAction === 'ignore') {
|
|
13091
|
+
if (suspectProtoRx.test(text) === false) {
|
|
13092
|
+
return obj
|
|
13093
|
+
}
|
|
13094
|
+
} else {
|
|
13095
|
+
if (suspectConstructorRx.test(text) === false) {
|
|
13096
|
+
return obj
|
|
13097
|
+
}
|
|
13098
|
+
}
|
|
13099
|
+
|
|
13100
|
+
// Scan result for proto keys
|
|
13101
|
+
return filter(obj, { protoAction, constructorAction, safe: options && options.safe })
|
|
13102
|
+
}
|
|
13103
|
+
|
|
13104
|
+
function filter (obj, { protoAction = 'error', constructorAction = 'error', safe } = {}) {
|
|
13105
|
+
let next = [obj];
|
|
13106
|
+
|
|
13107
|
+
while (next.length) {
|
|
13108
|
+
const nodes = next;
|
|
13109
|
+
next = [];
|
|
13110
|
+
|
|
13111
|
+
for (const node of nodes) {
|
|
13112
|
+
if (protoAction !== 'ignore' && Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
|
|
13113
|
+
if (safe === true) {
|
|
13114
|
+
return null
|
|
13115
|
+
} else if (protoAction === 'error') {
|
|
13116
|
+
throw new SyntaxError('Object contains forbidden prototype property')
|
|
13117
|
+
}
|
|
13118
|
+
|
|
13119
|
+
delete node.__proto__; // eslint-disable-line no-proto
|
|
13120
|
+
}
|
|
13121
|
+
|
|
13122
|
+
if (constructorAction !== 'ignore' &&
|
|
13123
|
+
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
|
|
13124
|
+
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')) { // Avoid calling node.hasOwnProperty directly
|
|
13125
|
+
if (safe === true) {
|
|
13126
|
+
return null
|
|
13127
|
+
} else if (constructorAction === 'error') {
|
|
13128
|
+
throw new SyntaxError('Object contains forbidden prototype property')
|
|
13129
|
+
}
|
|
13130
|
+
|
|
13131
|
+
delete node.constructor;
|
|
13132
|
+
}
|
|
13133
|
+
|
|
13134
|
+
for (const key in node) {
|
|
13135
|
+
const value = node[key];
|
|
13136
|
+
if (value && typeof value === 'object') {
|
|
13137
|
+
next.push(value);
|
|
13138
|
+
}
|
|
13139
|
+
}
|
|
13140
|
+
}
|
|
13141
|
+
}
|
|
13142
|
+
return obj
|
|
13143
|
+
}
|
|
13144
|
+
|
|
13145
|
+
function parse (text, reviver, options) {
|
|
13146
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
13147
|
+
Error.stackTraceLimit = 0;
|
|
13148
|
+
try {
|
|
13149
|
+
return _parse(text, reviver, options)
|
|
13150
|
+
} finally {
|
|
13151
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
13152
|
+
}
|
|
13153
|
+
}
|
|
13154
|
+
|
|
13155
|
+
function safeParse (text, reviver) {
|
|
13156
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
13157
|
+
Error.stackTraceLimit = 0;
|
|
13158
|
+
try {
|
|
13159
|
+
return _parse(text, reviver, { safe: true })
|
|
13160
|
+
} catch (_e) {
|
|
13161
|
+
return null
|
|
13162
|
+
} finally {
|
|
13163
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
13164
|
+
}
|
|
13165
|
+
}
|
|
13166
|
+
|
|
13167
|
+
secureJsonParse.exports = parse;
|
|
13168
|
+
secureJsonParse.exports.default = parse;
|
|
13169
|
+
secureJsonParse.exports.parse = parse;
|
|
13170
|
+
secureJsonParse.exports.safeParse = safeParse;
|
|
13171
|
+
secureJsonParse.exports.scan = filter;
|
|
13172
|
+
return secureJsonParse.exports;
|
|
13173
|
+
}
|
|
13174
|
+
|
|
13175
|
+
var secureJsonParseExports = requireSecureJsonParse();
|
|
13176
|
+
var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
|
|
13177
|
+
|
|
13178
|
+
class ParseError extends Error {
|
|
13179
|
+
constructor(message, options) {
|
|
13180
|
+
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
|
|
13181
|
+
}
|
|
13182
|
+
}
|
|
13183
|
+
function noop(_arg) {
|
|
13184
|
+
}
|
|
13185
|
+
function createParser(callbacks) {
|
|
13186
|
+
if (typeof callbacks == "function")
|
|
13187
|
+
throw new TypeError(
|
|
13188
|
+
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
13189
|
+
);
|
|
13190
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
13191
|
+
let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
|
|
13192
|
+
function feed(newChunk) {
|
|
13193
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
13194
|
+
for (const line of complete)
|
|
13195
|
+
parseLine(line);
|
|
13196
|
+
incompleteLine = incomplete, isFirstChunk = false;
|
|
13197
|
+
}
|
|
13198
|
+
function parseLine(line) {
|
|
13199
|
+
if (line === "") {
|
|
13200
|
+
dispatchEvent();
|
|
13201
|
+
return;
|
|
13202
|
+
}
|
|
13203
|
+
if (line.startsWith(":")) {
|
|
13204
|
+
onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
13205
|
+
return;
|
|
13206
|
+
}
|
|
13207
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
13208
|
+
if (fieldSeparatorIndex !== -1) {
|
|
13209
|
+
const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
|
|
13210
|
+
processField(field, value, line);
|
|
13211
|
+
return;
|
|
13212
|
+
}
|
|
13213
|
+
processField(line, "", line);
|
|
13214
|
+
}
|
|
13215
|
+
function processField(field, value, line) {
|
|
13216
|
+
switch (field) {
|
|
13217
|
+
case "event":
|
|
13218
|
+
eventType = value;
|
|
13219
|
+
break;
|
|
13220
|
+
case "data":
|
|
13221
|
+
data = `${data}${value}
|
|
13222
|
+
`;
|
|
13223
|
+
break;
|
|
13224
|
+
case "id":
|
|
13225
|
+
id = value.includes("\0") ? void 0 : value;
|
|
13226
|
+
break;
|
|
13227
|
+
case "retry":
|
|
13228
|
+
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
13229
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
13230
|
+
type: "invalid-retry",
|
|
13231
|
+
value,
|
|
13232
|
+
line
|
|
13233
|
+
})
|
|
13234
|
+
);
|
|
13235
|
+
break;
|
|
13236
|
+
default:
|
|
13237
|
+
onError(
|
|
13238
|
+
new ParseError(
|
|
13239
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
13240
|
+
{ type: "unknown-field", field, value, line }
|
|
13241
|
+
)
|
|
13242
|
+
);
|
|
13243
|
+
break;
|
|
13244
|
+
}
|
|
13245
|
+
}
|
|
13246
|
+
function dispatchEvent() {
|
|
13247
|
+
data.length > 0 && onEvent({
|
|
13248
|
+
id,
|
|
13249
|
+
event: eventType || void 0,
|
|
13250
|
+
// If the data buffer's last character is a U+000A LINE FEED (LF) character,
|
|
13251
|
+
// then remove the last character from the data buffer.
|
|
13252
|
+
data: data.endsWith(`
|
|
13253
|
+
`) ? data.slice(0, -1) : data
|
|
13254
|
+
}), id = void 0, data = "", eventType = "";
|
|
13255
|
+
}
|
|
13256
|
+
function reset(options = {}) {
|
|
13257
|
+
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
|
|
13258
|
+
}
|
|
13259
|
+
return { feed, reset };
|
|
13260
|
+
}
|
|
13261
|
+
function splitLines(chunk) {
|
|
13262
|
+
const lines = [];
|
|
13263
|
+
let incompleteLine = "", searchIndex = 0;
|
|
13264
|
+
for (; searchIndex < chunk.length; ) {
|
|
13265
|
+
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
13266
|
+
`, searchIndex);
|
|
13267
|
+
let lineEnd = -1;
|
|
13268
|
+
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
|
|
13269
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
13270
|
+
break;
|
|
13271
|
+
} else {
|
|
13272
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
13273
|
+
lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
|
|
13274
|
+
` && searchIndex++;
|
|
13275
|
+
}
|
|
13276
|
+
}
|
|
13277
|
+
return [lines, incompleteLine];
|
|
13278
|
+
}
|
|
13279
|
+
|
|
13280
|
+
class EventSourceParserStream extends TransformStream {
|
|
13281
|
+
constructor({ onError, onRetry, onComment } = {}) {
|
|
13282
|
+
let parser;
|
|
13283
|
+
super({
|
|
13284
|
+
start(controller) {
|
|
13285
|
+
parser = createParser({
|
|
13286
|
+
onEvent: (event) => {
|
|
13287
|
+
controller.enqueue(event);
|
|
13288
|
+
},
|
|
13289
|
+
onError(error) {
|
|
13290
|
+
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
|
|
13291
|
+
},
|
|
13292
|
+
onRetry,
|
|
13293
|
+
onComment
|
|
13294
|
+
});
|
|
13295
|
+
},
|
|
13296
|
+
transform(chunk) {
|
|
13297
|
+
parser.feed(chunk);
|
|
13298
|
+
}
|
|
13299
|
+
});
|
|
13300
|
+
}
|
|
13301
|
+
}
|
|
13302
|
+
|
|
13303
|
+
// src/combine-headers.ts
|
|
13304
|
+
function combineHeaders(...headers) {
|
|
13305
|
+
return headers.reduce(
|
|
13306
|
+
(combinedHeaders, currentHeaders) => ({
|
|
13307
|
+
...combinedHeaders,
|
|
13308
|
+
...currentHeaders != null ? currentHeaders : {}
|
|
13309
|
+
}),
|
|
13310
|
+
{}
|
|
13311
|
+
);
|
|
13312
|
+
}
|
|
13313
|
+
|
|
13314
|
+
// src/extract-response-headers.ts
|
|
13315
|
+
function extractResponseHeaders(response) {
|
|
13316
|
+
const headers = {};
|
|
13317
|
+
response.headers.forEach((value, key) => {
|
|
13318
|
+
headers[key] = value;
|
|
13319
|
+
});
|
|
13320
|
+
return headers;
|
|
13321
|
+
}
|
|
13322
|
+
var createIdGenerator = ({
|
|
13323
|
+
prefix,
|
|
13324
|
+
size: defaultSize = 16,
|
|
13325
|
+
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
13326
|
+
separator = "-"
|
|
13327
|
+
} = {}) => {
|
|
13328
|
+
const generator = customAlphabet(alphabet, defaultSize);
|
|
13329
|
+
if (prefix == null) {
|
|
13330
|
+
return generator;
|
|
13331
|
+
}
|
|
13332
|
+
if (alphabet.includes(separator)) {
|
|
13333
|
+
throw new InvalidArgumentError({
|
|
13334
|
+
argument: "separator",
|
|
13335
|
+
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
13336
|
+
});
|
|
13337
|
+
}
|
|
13338
|
+
return (size) => `${prefix}${separator}${generator(size)}`;
|
|
13339
|
+
};
|
|
13340
|
+
var generateId = createIdGenerator();
|
|
13341
|
+
|
|
13342
|
+
// src/remove-undefined-entries.ts
|
|
13343
|
+
function removeUndefinedEntries(record) {
|
|
13344
|
+
return Object.fromEntries(
|
|
13345
|
+
Object.entries(record).filter(([_key, value]) => value != null)
|
|
13346
|
+
);
|
|
13347
|
+
}
|
|
13348
|
+
|
|
13349
|
+
// src/is-abort-error.ts
|
|
13350
|
+
function isAbortError(error) {
|
|
13351
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
13352
|
+
}
|
|
13353
|
+
function loadApiKey({
|
|
13354
|
+
apiKey,
|
|
13355
|
+
environmentVariableName,
|
|
13356
|
+
apiKeyParameterName = "apiKey",
|
|
13357
|
+
description
|
|
13358
|
+
}) {
|
|
13359
|
+
if (typeof apiKey === "string") {
|
|
13360
|
+
return apiKey;
|
|
13361
|
+
}
|
|
13362
|
+
if (apiKey != null) {
|
|
13363
|
+
throw new LoadAPIKeyError({
|
|
13364
|
+
message: `${description} API key must be a string.`
|
|
13365
|
+
});
|
|
13366
|
+
}
|
|
13367
|
+
if (typeof process === "undefined") {
|
|
13368
|
+
throw new LoadAPIKeyError({
|
|
13369
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
|
13370
|
+
});
|
|
13371
|
+
}
|
|
13372
|
+
apiKey = process.env[environmentVariableName];
|
|
13373
|
+
if (apiKey == null) {
|
|
13374
|
+
throw new LoadAPIKeyError({
|
|
13375
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
|
13376
|
+
});
|
|
13377
|
+
}
|
|
13378
|
+
if (typeof apiKey !== "string") {
|
|
13379
|
+
throw new LoadAPIKeyError({
|
|
13380
|
+
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
|
13381
|
+
});
|
|
13382
|
+
}
|
|
13383
|
+
return apiKey;
|
|
13384
|
+
}
|
|
13385
|
+
|
|
13386
|
+
// src/validator.ts
|
|
13387
|
+
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
13388
|
+
function validator(validate) {
|
|
13389
|
+
return { [validatorSymbol]: true, validate };
|
|
13390
|
+
}
|
|
13391
|
+
function isValidator(value) {
|
|
13392
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
13393
|
+
}
|
|
13394
|
+
function asValidator(value) {
|
|
13395
|
+
return isValidator(value) ? value : zodValidator(value);
|
|
13396
|
+
}
|
|
13397
|
+
function zodValidator(zodSchema) {
|
|
13398
|
+
return validator((value) => {
|
|
13399
|
+
const result = zodSchema.safeParse(value);
|
|
13400
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
13401
|
+
});
|
|
13402
|
+
}
|
|
13403
|
+
|
|
13404
|
+
// src/validate-types.ts
|
|
13405
|
+
function validateTypes({
|
|
13406
|
+
value,
|
|
13407
|
+
schema: inputSchema
|
|
13408
|
+
}) {
|
|
13409
|
+
const result = safeValidateTypes({ value, schema: inputSchema });
|
|
13410
|
+
if (!result.success) {
|
|
13411
|
+
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
13412
|
+
}
|
|
13413
|
+
return result.value;
|
|
13414
|
+
}
|
|
13415
|
+
function safeValidateTypes({
|
|
13416
|
+
value,
|
|
13417
|
+
schema
|
|
13418
|
+
}) {
|
|
13419
|
+
const validator2 = asValidator(schema);
|
|
13420
|
+
try {
|
|
13421
|
+
if (validator2.validate == null) {
|
|
13422
|
+
return { success: true, value };
|
|
13423
|
+
}
|
|
13424
|
+
const result = validator2.validate(value);
|
|
13425
|
+
if (result.success) {
|
|
13426
|
+
return result;
|
|
13427
|
+
}
|
|
13428
|
+
return {
|
|
13429
|
+
success: false,
|
|
13430
|
+
error: TypeValidationError.wrap({ value, cause: result.error })
|
|
13431
|
+
};
|
|
13432
|
+
} catch (error) {
|
|
13433
|
+
return {
|
|
13434
|
+
success: false,
|
|
13435
|
+
error: TypeValidationError.wrap({ value, cause: error })
|
|
13436
|
+
};
|
|
13437
|
+
}
|
|
13438
|
+
}
|
|
13439
|
+
|
|
13440
|
+
// src/parse-json.ts
|
|
13441
|
+
function parseJSON({
|
|
13442
|
+
text,
|
|
13443
|
+
schema
|
|
13444
|
+
}) {
|
|
13445
|
+
try {
|
|
13446
|
+
const value = SecureJSON.parse(text);
|
|
13447
|
+
if (schema == null) {
|
|
13448
|
+
return value;
|
|
13449
|
+
}
|
|
13450
|
+
return validateTypes({ value, schema });
|
|
13451
|
+
} catch (error) {
|
|
13452
|
+
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
|
|
13453
|
+
throw error;
|
|
13454
|
+
}
|
|
13455
|
+
throw new JSONParseError({ text, cause: error });
|
|
13456
|
+
}
|
|
13457
|
+
}
|
|
13458
|
+
function safeParseJSON({
|
|
13459
|
+
text,
|
|
13460
|
+
schema
|
|
13461
|
+
}) {
|
|
13462
|
+
try {
|
|
13463
|
+
const value = SecureJSON.parse(text);
|
|
13464
|
+
if (schema == null) {
|
|
13465
|
+
return { success: true, value, rawValue: value };
|
|
13466
|
+
}
|
|
13467
|
+
const validationResult = safeValidateTypes({ value, schema });
|
|
13468
|
+
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
|
|
13469
|
+
} catch (error) {
|
|
13470
|
+
return {
|
|
13471
|
+
success: false,
|
|
13472
|
+
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
|
|
13473
|
+
};
|
|
13474
|
+
}
|
|
13475
|
+
}
|
|
13476
|
+
function isParsableJson(input) {
|
|
13477
|
+
try {
|
|
13478
|
+
SecureJSON.parse(input);
|
|
13479
|
+
return true;
|
|
13480
|
+
} catch (e) {
|
|
13481
|
+
return false;
|
|
13482
|
+
}
|
|
13483
|
+
}
|
|
13484
|
+
var getOriginalFetch2 = () => globalThis.fetch;
|
|
13485
|
+
var postJsonToApi = async ({
|
|
13486
|
+
url,
|
|
13487
|
+
headers,
|
|
13488
|
+
body,
|
|
13489
|
+
failedResponseHandler,
|
|
13490
|
+
successfulResponseHandler,
|
|
13491
|
+
abortSignal,
|
|
13492
|
+
fetch
|
|
13493
|
+
}) => postToApi({
|
|
13494
|
+
url,
|
|
13495
|
+
headers: {
|
|
13496
|
+
"Content-Type": "application/json",
|
|
13497
|
+
...headers
|
|
13498
|
+
},
|
|
13499
|
+
body: {
|
|
13500
|
+
content: JSON.stringify(body),
|
|
13501
|
+
values: body
|
|
13502
|
+
},
|
|
13503
|
+
failedResponseHandler,
|
|
13504
|
+
successfulResponseHandler,
|
|
13505
|
+
abortSignal,
|
|
13506
|
+
fetch
|
|
13507
|
+
});
|
|
13508
|
+
var postToApi = async ({
|
|
13509
|
+
url,
|
|
13510
|
+
headers = {},
|
|
13511
|
+
body,
|
|
13512
|
+
successfulResponseHandler,
|
|
13513
|
+
failedResponseHandler,
|
|
13514
|
+
abortSignal,
|
|
13515
|
+
fetch = getOriginalFetch2()
|
|
13516
|
+
}) => {
|
|
13517
|
+
try {
|
|
13518
|
+
const response = await fetch(url, {
|
|
13519
|
+
method: "POST",
|
|
13520
|
+
headers: removeUndefinedEntries(headers),
|
|
13521
|
+
body: body.content,
|
|
13522
|
+
signal: abortSignal
|
|
13523
|
+
});
|
|
13524
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13525
|
+
if (!response.ok) {
|
|
13526
|
+
let errorInformation;
|
|
13527
|
+
try {
|
|
13528
|
+
errorInformation = await failedResponseHandler({
|
|
13529
|
+
response,
|
|
13530
|
+
url,
|
|
13531
|
+
requestBodyValues: body.values
|
|
13532
|
+
});
|
|
13533
|
+
} catch (error) {
|
|
13534
|
+
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
13535
|
+
throw error;
|
|
13536
|
+
}
|
|
13537
|
+
throw new APICallError({
|
|
13538
|
+
message: "Failed to process error response",
|
|
13539
|
+
cause: error,
|
|
13540
|
+
statusCode: response.status,
|
|
13541
|
+
url,
|
|
13542
|
+
responseHeaders,
|
|
13543
|
+
requestBodyValues: body.values
|
|
13544
|
+
});
|
|
13545
|
+
}
|
|
13546
|
+
throw errorInformation.value;
|
|
13547
|
+
}
|
|
13548
|
+
try {
|
|
13549
|
+
return await successfulResponseHandler({
|
|
13550
|
+
response,
|
|
13551
|
+
url,
|
|
13552
|
+
requestBodyValues: body.values
|
|
13553
|
+
});
|
|
13554
|
+
} catch (error) {
|
|
13555
|
+
if (error instanceof Error) {
|
|
13556
|
+
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
13557
|
+
throw error;
|
|
13558
|
+
}
|
|
13559
|
+
}
|
|
13560
|
+
throw new APICallError({
|
|
13561
|
+
message: "Failed to process successful response",
|
|
13562
|
+
cause: error,
|
|
13563
|
+
statusCode: response.status,
|
|
13564
|
+
url,
|
|
13565
|
+
responseHeaders,
|
|
13566
|
+
requestBodyValues: body.values
|
|
13567
|
+
});
|
|
13568
|
+
}
|
|
13569
|
+
} catch (error) {
|
|
13570
|
+
if (isAbortError(error)) {
|
|
13571
|
+
throw error;
|
|
13572
|
+
}
|
|
13573
|
+
if (error instanceof TypeError && error.message === "fetch failed") {
|
|
13574
|
+
const cause = error.cause;
|
|
13575
|
+
if (cause != null) {
|
|
13576
|
+
throw new APICallError({
|
|
13577
|
+
message: `Cannot connect to API: ${cause.message}`,
|
|
13578
|
+
cause,
|
|
13579
|
+
url,
|
|
13580
|
+
requestBodyValues: body.values,
|
|
13581
|
+
isRetryable: true
|
|
13582
|
+
// retry when network error
|
|
13583
|
+
});
|
|
13584
|
+
}
|
|
13585
|
+
}
|
|
13586
|
+
throw error;
|
|
13587
|
+
}
|
|
13588
|
+
};
|
|
13589
|
+
var createJsonErrorResponseHandler = ({
|
|
13590
|
+
errorSchema,
|
|
13591
|
+
errorToMessage,
|
|
13592
|
+
isRetryable
|
|
13593
|
+
}) => async ({ response, url, requestBodyValues }) => {
|
|
13594
|
+
const responseBody = await response.text();
|
|
13595
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13596
|
+
if (responseBody.trim() === "") {
|
|
13597
|
+
return {
|
|
13598
|
+
responseHeaders,
|
|
13599
|
+
value: new APICallError({
|
|
13600
|
+
message: response.statusText,
|
|
13601
|
+
url,
|
|
13602
|
+
requestBodyValues,
|
|
13603
|
+
statusCode: response.status,
|
|
13604
|
+
responseHeaders,
|
|
13605
|
+
responseBody,
|
|
13606
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
13607
|
+
})
|
|
13608
|
+
};
|
|
13609
|
+
}
|
|
13610
|
+
try {
|
|
13611
|
+
const parsedError = parseJSON({
|
|
13612
|
+
text: responseBody,
|
|
13613
|
+
schema: errorSchema
|
|
13614
|
+
});
|
|
13615
|
+
return {
|
|
13616
|
+
responseHeaders,
|
|
13617
|
+
value: new APICallError({
|
|
13618
|
+
message: errorToMessage(parsedError),
|
|
13619
|
+
url,
|
|
13620
|
+
requestBodyValues,
|
|
13621
|
+
statusCode: response.status,
|
|
13622
|
+
responseHeaders,
|
|
13623
|
+
responseBody,
|
|
13624
|
+
data: parsedError,
|
|
13625
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
|
|
13626
|
+
})
|
|
13627
|
+
};
|
|
13628
|
+
} catch (parseError) {
|
|
13629
|
+
return {
|
|
13630
|
+
responseHeaders,
|
|
13631
|
+
value: new APICallError({
|
|
13632
|
+
message: response.statusText,
|
|
13633
|
+
url,
|
|
13634
|
+
requestBodyValues,
|
|
13635
|
+
statusCode: response.status,
|
|
13636
|
+
responseHeaders,
|
|
13637
|
+
responseBody,
|
|
13638
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
13639
|
+
})
|
|
13640
|
+
};
|
|
13641
|
+
}
|
|
13642
|
+
};
|
|
13643
|
+
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
13644
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13645
|
+
if (response.body == null) {
|
|
13646
|
+
throw new EmptyResponseBodyError({});
|
|
13647
|
+
}
|
|
13648
|
+
return {
|
|
13649
|
+
responseHeaders,
|
|
13650
|
+
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
|
|
13651
|
+
new TransformStream({
|
|
13652
|
+
transform({ data }, controller) {
|
|
13653
|
+
if (data === "[DONE]") {
|
|
13654
|
+
return;
|
|
13655
|
+
}
|
|
13656
|
+
controller.enqueue(
|
|
13657
|
+
safeParseJSON({
|
|
13658
|
+
text: data,
|
|
13659
|
+
schema: chunkSchema
|
|
13660
|
+
})
|
|
13661
|
+
);
|
|
13662
|
+
}
|
|
13663
|
+
})
|
|
13664
|
+
)
|
|
13665
|
+
};
|
|
13666
|
+
};
|
|
13667
|
+
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
13668
|
+
const responseBody = await response.text();
|
|
13669
|
+
const parsedResult = safeParseJSON({
|
|
13670
|
+
text: responseBody,
|
|
13671
|
+
schema: responseSchema
|
|
13672
|
+
});
|
|
13673
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13674
|
+
if (!parsedResult.success) {
|
|
13675
|
+
throw new APICallError({
|
|
13676
|
+
message: "Invalid JSON response",
|
|
13677
|
+
cause: parsedResult.error,
|
|
13678
|
+
statusCode: response.status,
|
|
13679
|
+
responseHeaders,
|
|
13680
|
+
responseBody,
|
|
13681
|
+
url,
|
|
13682
|
+
requestBodyValues
|
|
13683
|
+
});
|
|
13684
|
+
}
|
|
13685
|
+
return {
|
|
13686
|
+
responseHeaders,
|
|
13687
|
+
value: parsedResult.value,
|
|
13688
|
+
rawValue: parsedResult.rawValue
|
|
13689
|
+
};
|
|
13690
|
+
};
|
|
13691
|
+
|
|
13692
|
+
// src/uint8-utils.ts
|
|
13693
|
+
var { btoa} = globalThis;
|
|
13694
|
+
function convertUint8ArrayToBase64(array) {
|
|
13695
|
+
let latin1string = "";
|
|
13696
|
+
for (let i = 0; i < array.length; i++) {
|
|
13697
|
+
latin1string += String.fromCodePoint(array[i]);
|
|
13698
|
+
}
|
|
13699
|
+
return btoa(latin1string);
|
|
13700
|
+
}
|
|
13701
|
+
|
|
13702
|
+
// src/without-trailing-slash.ts
|
|
13703
|
+
function withoutTrailingSlash(url) {
|
|
13704
|
+
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
13705
|
+
}
|
|
13706
|
+
|
|
13707
|
+
var __defProp = Object.defineProperty;
|
|
13708
|
+
var __defProps = Object.defineProperties;
|
|
13709
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
13710
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
13711
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
13712
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
13713
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
13714
|
+
var __spreadValues = (a, b) => {
|
|
13715
|
+
for (var prop in b || (b = {}))
|
|
13716
|
+
if (__hasOwnProp.call(b, prop))
|
|
13717
|
+
__defNormalProp(a, prop, b[prop]);
|
|
13718
|
+
if (__getOwnPropSymbols)
|
|
13719
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
13720
|
+
if (__propIsEnum.call(b, prop))
|
|
13721
|
+
__defNormalProp(a, prop, b[prop]);
|
|
13722
|
+
}
|
|
13723
|
+
return a;
|
|
13724
|
+
};
|
|
13725
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
13726
|
+
var __objRest = (source, exclude) => {
|
|
13727
|
+
var target = {};
|
|
13728
|
+
for (var prop in source)
|
|
13729
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
13730
|
+
target[prop] = source[prop];
|
|
13731
|
+
if (source != null && __getOwnPropSymbols)
|
|
13732
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
13733
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
13734
|
+
target[prop] = source[prop];
|
|
13735
|
+
}
|
|
13736
|
+
return target;
|
|
13737
|
+
};
|
|
13738
|
+
function getCacheControl(providerMetadata) {
|
|
13739
|
+
var _a, _b, _c;
|
|
13740
|
+
const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
|
|
13741
|
+
const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
|
|
13742
|
+
return (_c = (_b = (_a = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
|
|
13743
|
+
}
|
|
13744
|
+
function convertToOpenRouterChatMessages(prompt) {
|
|
13745
|
+
var _a, _b, _c;
|
|
13746
|
+
const messages = [];
|
|
13747
|
+
for (const { role, content, providerMetadata } of prompt) {
|
|
13748
|
+
switch (role) {
|
|
13749
|
+
case "system": {
|
|
13750
|
+
messages.push({
|
|
13751
|
+
role: "system",
|
|
13752
|
+
content,
|
|
13753
|
+
cache_control: getCacheControl(providerMetadata)
|
|
13754
|
+
});
|
|
13755
|
+
break;
|
|
13756
|
+
}
|
|
13757
|
+
case "user": {
|
|
13758
|
+
if (content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
|
|
13759
|
+
messages.push({
|
|
13760
|
+
role: "user",
|
|
13761
|
+
content: content[0].text,
|
|
13762
|
+
cache_control: (_b = getCacheControl(providerMetadata)) != null ? _b : getCacheControl(content[0].providerMetadata)
|
|
13763
|
+
});
|
|
13764
|
+
break;
|
|
13765
|
+
}
|
|
13766
|
+
const messageCacheControl = getCacheControl(providerMetadata);
|
|
13767
|
+
const contentParts = content.map(
|
|
13768
|
+
(part) => {
|
|
13769
|
+
var _a2, _b2, _c2, _d;
|
|
13770
|
+
switch (part.type) {
|
|
13771
|
+
case "text":
|
|
13772
|
+
return {
|
|
13773
|
+
type: "text",
|
|
13774
|
+
text: part.text,
|
|
13775
|
+
// For text parts, only use part-specific cache control
|
|
13776
|
+
cache_control: (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl
|
|
13777
|
+
};
|
|
13778
|
+
case "image":
|
|
13779
|
+
return {
|
|
13780
|
+
type: "image_url",
|
|
13781
|
+
image_url: {
|
|
13782
|
+
url: part.image instanceof URL ? part.image.toString() : `data:${(_b2 = part.mimeType) != null ? _b2 : "image/jpeg"};base64,${convertUint8ArrayToBase64(
|
|
13783
|
+
part.image
|
|
13784
|
+
)}`
|
|
13785
|
+
},
|
|
13786
|
+
// For image parts, use part-specific or message-level cache control
|
|
13787
|
+
cache_control: (_c2 = getCacheControl(part.providerMetadata)) != null ? _c2 : messageCacheControl
|
|
13788
|
+
};
|
|
13789
|
+
case "file":
|
|
13790
|
+
return {
|
|
13791
|
+
type: "text",
|
|
13792
|
+
text: part.data instanceof URL ? part.data.toString() : part.data,
|
|
13793
|
+
cache_control: (_d = getCacheControl(part.providerMetadata)) != null ? _d : messageCacheControl
|
|
13794
|
+
};
|
|
13795
|
+
default: {
|
|
13796
|
+
const _exhaustiveCheck = part;
|
|
13797
|
+
throw new Error(
|
|
13798
|
+
`Unsupported content part type: ${_exhaustiveCheck}`
|
|
13799
|
+
);
|
|
13800
|
+
}
|
|
13801
|
+
}
|
|
13802
|
+
}
|
|
13803
|
+
);
|
|
13804
|
+
messages.push({
|
|
13805
|
+
role: "user",
|
|
13806
|
+
content: contentParts
|
|
13807
|
+
});
|
|
13808
|
+
break;
|
|
13809
|
+
}
|
|
13810
|
+
case "assistant": {
|
|
13811
|
+
let text = "";
|
|
13812
|
+
const toolCalls = [];
|
|
13813
|
+
for (const part of content) {
|
|
13814
|
+
switch (part.type) {
|
|
13815
|
+
case "text": {
|
|
13816
|
+
text += part.text;
|
|
13817
|
+
break;
|
|
13818
|
+
}
|
|
13819
|
+
case "tool-call": {
|
|
13820
|
+
toolCalls.push({
|
|
13821
|
+
id: part.toolCallId,
|
|
13822
|
+
type: "function",
|
|
13823
|
+
function: {
|
|
13824
|
+
name: part.toolName,
|
|
13825
|
+
arguments: JSON.stringify(part.args)
|
|
13826
|
+
}
|
|
13827
|
+
});
|
|
13828
|
+
break;
|
|
13829
|
+
}
|
|
13830
|
+
// TODO: Handle reasoning and redacted-reasoning
|
|
13831
|
+
case "reasoning":
|
|
13832
|
+
case "redacted-reasoning":
|
|
13833
|
+
break;
|
|
13834
|
+
default: {
|
|
13835
|
+
const _exhaustiveCheck = part;
|
|
13836
|
+
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
|
13837
|
+
}
|
|
13838
|
+
}
|
|
13839
|
+
}
|
|
13840
|
+
messages.push({
|
|
13841
|
+
role: "assistant",
|
|
13842
|
+
content: text,
|
|
13843
|
+
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
|
|
13844
|
+
cache_control: getCacheControl(providerMetadata)
|
|
13845
|
+
});
|
|
13846
|
+
break;
|
|
13847
|
+
}
|
|
13848
|
+
case "tool": {
|
|
13849
|
+
for (const toolResponse of content) {
|
|
13850
|
+
messages.push({
|
|
13851
|
+
role: "tool",
|
|
13852
|
+
tool_call_id: toolResponse.toolCallId,
|
|
13853
|
+
content: JSON.stringify(toolResponse.result),
|
|
13854
|
+
cache_control: (_c = getCacheControl(providerMetadata)) != null ? _c : getCacheControl(toolResponse.providerMetadata)
|
|
13855
|
+
});
|
|
13856
|
+
}
|
|
13857
|
+
break;
|
|
13858
|
+
}
|
|
13859
|
+
default: {
|
|
13860
|
+
const _exhaustiveCheck = role;
|
|
13861
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
|
13862
|
+
}
|
|
13863
|
+
}
|
|
13864
|
+
}
|
|
13865
|
+
return messages;
|
|
13866
|
+
}
|
|
13867
|
+
|
|
13868
|
+
// src/map-openrouter-chat-logprobs.ts
|
|
13869
|
+
function mapOpenRouterChatLogProbsOutput(logprobs) {
|
|
13870
|
+
var _a, _b;
|
|
13871
|
+
return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
|
|
13872
|
+
token,
|
|
13873
|
+
logprob,
|
|
13874
|
+
topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
|
|
13875
|
+
token: token2,
|
|
13876
|
+
logprob: logprob2
|
|
13877
|
+
})) : []
|
|
13878
|
+
}))) != null ? _b : void 0;
|
|
13879
|
+
}
|
|
13880
|
+
|
|
13881
|
+
// src/map-openrouter-finish-reason.ts
|
|
13882
|
+
function mapOpenRouterFinishReason(finishReason) {
|
|
13883
|
+
switch (finishReason) {
|
|
13884
|
+
case "stop":
|
|
13885
|
+
return "stop";
|
|
13886
|
+
case "length":
|
|
13887
|
+
return "length";
|
|
13888
|
+
case "content_filter":
|
|
13889
|
+
return "content-filter";
|
|
13890
|
+
case "function_call":
|
|
13891
|
+
case "tool_calls":
|
|
13892
|
+
return "tool-calls";
|
|
13893
|
+
default:
|
|
13894
|
+
return "unknown";
|
|
13895
|
+
}
|
|
13896
|
+
}
|
|
13897
|
+
var OpenRouterErrorResponseSchema = z.object({
|
|
13898
|
+
error: z.object({
|
|
13899
|
+
message: z.string(),
|
|
13900
|
+
type: z.string(),
|
|
13901
|
+
param: z.any().nullable(),
|
|
13902
|
+
code: z.string().nullable()
|
|
13903
|
+
})
|
|
13904
|
+
});
|
|
13905
|
+
var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
|
|
13906
|
+
errorSchema: OpenRouterErrorResponseSchema,
|
|
13907
|
+
errorToMessage: (data) => data.error.message
|
|
13908
|
+
});
|
|
13909
|
+
|
|
13910
|
+
// src/openrouter-chat-language-model.ts
|
|
13911
|
+
function isFunctionTool(tool) {
|
|
13912
|
+
return "parameters" in tool;
|
|
13913
|
+
}
|
|
13914
|
+
var OpenRouterChatLanguageModel = class {
|
|
13915
|
+
constructor(modelId, settings, config) {
|
|
13916
|
+
this.specificationVersion = "v1";
|
|
13917
|
+
this.defaultObjectGenerationMode = "tool";
|
|
13918
|
+
this.modelId = modelId;
|
|
13919
|
+
this.settings = settings;
|
|
13920
|
+
this.config = config;
|
|
13921
|
+
}
|
|
13922
|
+
get provider() {
|
|
13923
|
+
return this.config.provider;
|
|
13924
|
+
}
|
|
13925
|
+
getArgs({
|
|
13926
|
+
mode,
|
|
13927
|
+
prompt,
|
|
13928
|
+
maxTokens,
|
|
13929
|
+
temperature,
|
|
13930
|
+
topP,
|
|
13931
|
+
frequencyPenalty,
|
|
13932
|
+
presencePenalty,
|
|
13933
|
+
seed,
|
|
13934
|
+
stopSequences,
|
|
13935
|
+
responseFormat,
|
|
13936
|
+
topK,
|
|
13937
|
+
providerMetadata
|
|
13938
|
+
}) {
|
|
13939
|
+
var _a;
|
|
13940
|
+
const type = mode.type;
|
|
13941
|
+
const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
|
|
13942
|
+
const baseArgs = __spreadValues(__spreadValues(__spreadValues({
|
|
13943
|
+
// model id:
|
|
13944
|
+
model: this.modelId,
|
|
13945
|
+
models: this.settings.models,
|
|
13946
|
+
// model specific settings:
|
|
13947
|
+
logit_bias: this.settings.logitBias,
|
|
13948
|
+
logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
|
|
13949
|
+
top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
|
|
13950
|
+
user: this.settings.user,
|
|
13951
|
+
parallel_tool_calls: this.settings.parallelToolCalls,
|
|
13952
|
+
// standardized settings:
|
|
13953
|
+
max_tokens: maxTokens,
|
|
13954
|
+
temperature,
|
|
13955
|
+
top_p: topP,
|
|
13956
|
+
frequency_penalty: frequencyPenalty,
|
|
13957
|
+
presence_penalty: presencePenalty,
|
|
13958
|
+
seed,
|
|
13959
|
+
stop: stopSequences,
|
|
13960
|
+
response_format: responseFormat,
|
|
13961
|
+
top_k: topK,
|
|
13962
|
+
// messages:
|
|
13963
|
+
messages: convertToOpenRouterChatMessages(prompt),
|
|
13964
|
+
// OpenRouter specific settings:
|
|
13965
|
+
include_reasoning: this.settings.includeReasoning,
|
|
13966
|
+
reasoning: this.settings.reasoning
|
|
13967
|
+
}, this.config.extraBody), this.settings.extraBody), extraCallingBody);
|
|
13968
|
+
switch (type) {
|
|
13969
|
+
case "regular": {
|
|
13970
|
+
return __spreadValues(__spreadValues({}, baseArgs), prepareToolsAndToolChoice(mode));
|
|
13971
|
+
}
|
|
13972
|
+
case "object-json": {
|
|
13973
|
+
return __spreadProps(__spreadValues({}, baseArgs), {
|
|
13974
|
+
response_format: { type: "json_object" }
|
|
13975
|
+
});
|
|
13976
|
+
}
|
|
13977
|
+
case "object-tool": {
|
|
13978
|
+
return __spreadProps(__spreadValues({}, baseArgs), {
|
|
13979
|
+
tool_choice: { type: "function", function: { name: mode.tool.name } },
|
|
13980
|
+
tools: [
|
|
13981
|
+
{
|
|
13982
|
+
type: "function",
|
|
13983
|
+
function: {
|
|
13984
|
+
name: mode.tool.name,
|
|
13985
|
+
description: mode.tool.description,
|
|
13986
|
+
parameters: mode.tool.parameters
|
|
13987
|
+
}
|
|
13988
|
+
}
|
|
13989
|
+
]
|
|
13990
|
+
});
|
|
13991
|
+
}
|
|
13992
|
+
// Handle all non-text types with a single default case
|
|
13993
|
+
default: {
|
|
13994
|
+
const _exhaustiveCheck = type;
|
|
13995
|
+
throw new UnsupportedFunctionalityError({
|
|
13996
|
+
functionality: `${_exhaustiveCheck} mode`
|
|
13997
|
+
});
|
|
13998
|
+
}
|
|
13999
|
+
}
|
|
14000
|
+
}
|
|
14001
|
+
async doGenerate(options) {
|
|
14002
|
+
var _b, _c, _d, _e, _f, _g, _h;
|
|
14003
|
+
const args = this.getArgs(options);
|
|
14004
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14005
|
+
url: this.config.url({
|
|
14006
|
+
path: "/chat/completions",
|
|
14007
|
+
modelId: this.modelId
|
|
14008
|
+
}),
|
|
14009
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14010
|
+
body: args,
|
|
14011
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14012
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
14013
|
+
OpenRouterNonStreamChatCompletionResponseSchema
|
|
14014
|
+
),
|
|
14015
|
+
abortSignal: options.abortSignal,
|
|
14016
|
+
fetch: this.config.fetch
|
|
14017
|
+
});
|
|
14018
|
+
const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
|
|
14019
|
+
const choice = response.choices[0];
|
|
14020
|
+
if (!choice) {
|
|
14021
|
+
throw new Error("No choice in response");
|
|
14022
|
+
}
|
|
14023
|
+
return {
|
|
14024
|
+
response: {
|
|
14025
|
+
id: response.id,
|
|
14026
|
+
modelId: response.model
|
|
14027
|
+
},
|
|
14028
|
+
text: (_b = choice.message.content) != null ? _b : void 0,
|
|
14029
|
+
reasoning: (_c = choice.message.reasoning) != null ? _c : void 0,
|
|
14030
|
+
toolCalls: (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
|
|
14031
|
+
var _a2;
|
|
14032
|
+
return {
|
|
14033
|
+
toolCallType: "function",
|
|
14034
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
14035
|
+
toolName: toolCall.function.name,
|
|
14036
|
+
args: toolCall.function.arguments
|
|
14037
|
+
};
|
|
14038
|
+
}),
|
|
14039
|
+
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
|
|
14040
|
+
usage: {
|
|
14041
|
+
promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : 0,
|
|
14042
|
+
completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0
|
|
14043
|
+
},
|
|
14044
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14045
|
+
rawResponse: { headers: responseHeaders },
|
|
14046
|
+
warnings: [],
|
|
14047
|
+
logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
|
|
14048
|
+
};
|
|
14049
|
+
}
|
|
14050
|
+
async doStream(options) {
|
|
14051
|
+
const args = this.getArgs(options);
|
|
14052
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14053
|
+
url: this.config.url({
|
|
14054
|
+
path: "/chat/completions",
|
|
14055
|
+
modelId: this.modelId
|
|
14056
|
+
}),
|
|
14057
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14058
|
+
body: __spreadProps(__spreadValues({}, args), {
|
|
14059
|
+
stream: true,
|
|
14060
|
+
// only include stream_options when in strict compatibility mode:
|
|
14061
|
+
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
14062
|
+
}),
|
|
14063
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14064
|
+
successfulResponseHandler: createEventSourceResponseHandler(
|
|
14065
|
+
OpenRouterStreamChatCompletionChunkSchema
|
|
14066
|
+
),
|
|
14067
|
+
abortSignal: options.abortSignal,
|
|
14068
|
+
fetch: this.config.fetch
|
|
14069
|
+
});
|
|
14070
|
+
const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
|
|
14071
|
+
const toolCalls = [];
|
|
14072
|
+
let finishReason = "other";
|
|
14073
|
+
let usage = {
|
|
14074
|
+
promptTokens: Number.NaN,
|
|
14075
|
+
completionTokens: Number.NaN
|
|
14076
|
+
};
|
|
14077
|
+
let logprobs;
|
|
14078
|
+
return {
|
|
14079
|
+
stream: response.pipeThrough(
|
|
14080
|
+
new TransformStream({
|
|
14081
|
+
transform(chunk, controller) {
|
|
14082
|
+
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
14083
|
+
if (!chunk.success) {
|
|
14084
|
+
finishReason = "error";
|
|
14085
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
|
14086
|
+
return;
|
|
14087
|
+
}
|
|
14088
|
+
const value = chunk.value;
|
|
14089
|
+
if ("error" in value) {
|
|
14090
|
+
finishReason = "error";
|
|
14091
|
+
controller.enqueue({ type: "error", error: value.error });
|
|
14092
|
+
return;
|
|
14093
|
+
}
|
|
14094
|
+
if (value.id) {
|
|
14095
|
+
controller.enqueue({
|
|
14096
|
+
type: "response-metadata",
|
|
14097
|
+
id: value.id
|
|
14098
|
+
});
|
|
14099
|
+
}
|
|
14100
|
+
if (value.model) {
|
|
14101
|
+
controller.enqueue({
|
|
14102
|
+
type: "response-metadata",
|
|
14103
|
+
modelId: value.model
|
|
14104
|
+
});
|
|
14105
|
+
}
|
|
14106
|
+
if (value.usage != null) {
|
|
14107
|
+
usage = {
|
|
14108
|
+
promptTokens: value.usage.prompt_tokens,
|
|
14109
|
+
completionTokens: value.usage.completion_tokens
|
|
14110
|
+
};
|
|
14111
|
+
}
|
|
14112
|
+
const choice = value.choices[0];
|
|
14113
|
+
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
14114
|
+
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
14115
|
+
}
|
|
14116
|
+
if ((choice == null ? void 0 : choice.delta) == null) {
|
|
14117
|
+
return;
|
|
14118
|
+
}
|
|
14119
|
+
const delta = choice.delta;
|
|
14120
|
+
if (delta.content != null) {
|
|
14121
|
+
controller.enqueue({
|
|
14122
|
+
type: "text-delta",
|
|
14123
|
+
textDelta: delta.content
|
|
14124
|
+
});
|
|
14125
|
+
}
|
|
14126
|
+
if (delta.reasoning != null) {
|
|
14127
|
+
controller.enqueue({
|
|
14128
|
+
type: "reasoning",
|
|
14129
|
+
textDelta: delta.reasoning
|
|
14130
|
+
});
|
|
14131
|
+
}
|
|
14132
|
+
const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
|
|
14133
|
+
choice == null ? void 0 : choice.logprobs
|
|
14134
|
+
);
|
|
14135
|
+
if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
|
|
14136
|
+
if (logprobs === void 0) logprobs = [];
|
|
14137
|
+
logprobs.push(...mappedLogprobs);
|
|
14138
|
+
}
|
|
14139
|
+
if (delta.tool_calls != null) {
|
|
14140
|
+
for (const toolCallDelta of delta.tool_calls) {
|
|
14141
|
+
const index = toolCallDelta.index;
|
|
14142
|
+
if (toolCalls[index] == null) {
|
|
14143
|
+
if (toolCallDelta.type !== "function") {
|
|
14144
|
+
throw new InvalidResponseDataError({
|
|
14145
|
+
data: toolCallDelta,
|
|
14146
|
+
message: `Expected 'function' type.`
|
|
14147
|
+
});
|
|
14148
|
+
}
|
|
14149
|
+
if (toolCallDelta.id == null) {
|
|
14150
|
+
throw new InvalidResponseDataError({
|
|
14151
|
+
data: toolCallDelta,
|
|
14152
|
+
message: `Expected 'id' to be a string.`
|
|
14153
|
+
});
|
|
14154
|
+
}
|
|
14155
|
+
if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
|
|
14156
|
+
throw new InvalidResponseDataError({
|
|
14157
|
+
data: toolCallDelta,
|
|
14158
|
+
message: `Expected 'function.name' to be a string.`
|
|
14159
|
+
});
|
|
14160
|
+
}
|
|
14161
|
+
toolCalls[index] = {
|
|
14162
|
+
id: toolCallDelta.id,
|
|
14163
|
+
type: "function",
|
|
14164
|
+
function: {
|
|
14165
|
+
name: toolCallDelta.function.name,
|
|
14166
|
+
arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
|
|
14167
|
+
},
|
|
14168
|
+
sent: false
|
|
14169
|
+
};
|
|
14170
|
+
const toolCall2 = toolCalls[index];
|
|
14171
|
+
if (toolCall2 == null) {
|
|
14172
|
+
throw new Error("Tool call is missing");
|
|
14173
|
+
}
|
|
14174
|
+
if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
|
|
14175
|
+
controller.enqueue({
|
|
14176
|
+
type: "tool-call-delta",
|
|
14177
|
+
toolCallType: "function",
|
|
14178
|
+
toolCallId: toolCall2.id,
|
|
14179
|
+
toolName: toolCall2.function.name,
|
|
14180
|
+
argsTextDelta: toolCall2.function.arguments
|
|
14181
|
+
});
|
|
14182
|
+
controller.enqueue({
|
|
14183
|
+
type: "tool-call",
|
|
14184
|
+
toolCallType: "function",
|
|
14185
|
+
toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
|
|
14186
|
+
toolName: toolCall2.function.name,
|
|
14187
|
+
args: toolCall2.function.arguments
|
|
14188
|
+
});
|
|
14189
|
+
toolCall2.sent = true;
|
|
14190
|
+
}
|
|
14191
|
+
continue;
|
|
14192
|
+
}
|
|
14193
|
+
const toolCall = toolCalls[index];
|
|
14194
|
+
if (toolCall == null) {
|
|
14195
|
+
throw new Error("Tool call is missing");
|
|
14196
|
+
}
|
|
14197
|
+
if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
|
|
14198
|
+
toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
|
|
14199
|
+
}
|
|
14200
|
+
controller.enqueue({
|
|
14201
|
+
type: "tool-call-delta",
|
|
14202
|
+
toolCallType: "function",
|
|
14203
|
+
toolCallId: toolCall.id,
|
|
14204
|
+
toolName: toolCall.function.name,
|
|
14205
|
+
argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
|
|
14206
|
+
});
|
|
14207
|
+
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
|
|
14208
|
+
controller.enqueue({
|
|
14209
|
+
type: "tool-call",
|
|
14210
|
+
toolCallType: "function",
|
|
14211
|
+
toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
|
|
14212
|
+
toolName: toolCall.function.name,
|
|
14213
|
+
args: toolCall.function.arguments
|
|
14214
|
+
});
|
|
14215
|
+
toolCall.sent = true;
|
|
14216
|
+
}
|
|
14217
|
+
}
|
|
14218
|
+
}
|
|
14219
|
+
},
|
|
14220
|
+
flush(controller) {
|
|
14221
|
+
var _a2;
|
|
14222
|
+
if (finishReason === "tool-calls") {
|
|
14223
|
+
for (const toolCall of toolCalls) {
|
|
14224
|
+
if (!toolCall.sent) {
|
|
14225
|
+
controller.enqueue({
|
|
14226
|
+
type: "tool-call",
|
|
14227
|
+
toolCallType: "function",
|
|
14228
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
14229
|
+
toolName: toolCall.function.name,
|
|
14230
|
+
// Coerce invalid arguments to an empty JSON object
|
|
14231
|
+
args: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
|
|
14232
|
+
});
|
|
14233
|
+
toolCall.sent = true;
|
|
14234
|
+
}
|
|
14235
|
+
}
|
|
14236
|
+
}
|
|
14237
|
+
controller.enqueue({
|
|
14238
|
+
type: "finish",
|
|
14239
|
+
finishReason,
|
|
14240
|
+
logprobs,
|
|
14241
|
+
usage
|
|
14242
|
+
});
|
|
14243
|
+
}
|
|
14244
|
+
})
|
|
14245
|
+
),
|
|
14246
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14247
|
+
rawResponse: { headers: responseHeaders },
|
|
14248
|
+
warnings: []
|
|
14249
|
+
};
|
|
14250
|
+
}
|
|
14251
|
+
};
|
|
14252
|
+
var OpenRouterChatCompletionBaseResponseSchema = z.object({
|
|
14253
|
+
id: z.string().optional(),
|
|
14254
|
+
model: z.string().optional(),
|
|
14255
|
+
usage: z.object({
|
|
14256
|
+
prompt_tokens: z.number(),
|
|
14257
|
+
completion_tokens: z.number(),
|
|
14258
|
+
total_tokens: z.number()
|
|
14259
|
+
}).nullish()
|
|
14260
|
+
});
|
|
14261
|
+
var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
14262
|
+
choices: z.array(
|
|
14263
|
+
z.object({
|
|
14264
|
+
message: z.object({
|
|
14265
|
+
role: z.literal("assistant"),
|
|
14266
|
+
content: z.string().nullable().optional(),
|
|
14267
|
+
reasoning: z.string().nullable().optional(),
|
|
14268
|
+
tool_calls: z.array(
|
|
14269
|
+
z.object({
|
|
14270
|
+
id: z.string().optional().nullable(),
|
|
14271
|
+
type: z.literal("function"),
|
|
14272
|
+
function: z.object({
|
|
14273
|
+
name: z.string(),
|
|
14274
|
+
arguments: z.string()
|
|
14275
|
+
})
|
|
14276
|
+
})
|
|
14277
|
+
).optional()
|
|
14278
|
+
}),
|
|
14279
|
+
index: z.number(),
|
|
14280
|
+
logprobs: z.object({
|
|
14281
|
+
content: z.array(
|
|
14282
|
+
z.object({
|
|
14283
|
+
token: z.string(),
|
|
14284
|
+
logprob: z.number(),
|
|
14285
|
+
top_logprobs: z.array(
|
|
14286
|
+
z.object({
|
|
14287
|
+
token: z.string(),
|
|
14288
|
+
logprob: z.number()
|
|
14289
|
+
})
|
|
14290
|
+
)
|
|
14291
|
+
})
|
|
14292
|
+
).nullable()
|
|
14293
|
+
}).nullable().optional(),
|
|
14294
|
+
finish_reason: z.string().optional().nullable()
|
|
14295
|
+
})
|
|
14296
|
+
)
|
|
14297
|
+
});
|
|
14298
|
+
var OpenRouterStreamChatCompletionChunkSchema = z.union([
|
|
14299
|
+
OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
14300
|
+
choices: z.array(
|
|
14301
|
+
z.object({
|
|
14302
|
+
delta: z.object({
|
|
14303
|
+
role: z.enum(["assistant"]).optional(),
|
|
14304
|
+
content: z.string().nullish(),
|
|
14305
|
+
reasoning: z.string().nullish().optional(),
|
|
14306
|
+
tool_calls: z.array(
|
|
14307
|
+
z.object({
|
|
14308
|
+
index: z.number(),
|
|
14309
|
+
id: z.string().nullish(),
|
|
14310
|
+
type: z.literal("function").optional(),
|
|
14311
|
+
function: z.object({
|
|
14312
|
+
name: z.string().nullish(),
|
|
14313
|
+
arguments: z.string().nullish()
|
|
14314
|
+
})
|
|
14315
|
+
})
|
|
14316
|
+
).nullish()
|
|
14317
|
+
}).nullish(),
|
|
14318
|
+
logprobs: z.object({
|
|
14319
|
+
content: z.array(
|
|
14320
|
+
z.object({
|
|
14321
|
+
token: z.string(),
|
|
14322
|
+
logprob: z.number(),
|
|
14323
|
+
top_logprobs: z.array(
|
|
14324
|
+
z.object({
|
|
14325
|
+
token: z.string(),
|
|
14326
|
+
logprob: z.number()
|
|
14327
|
+
})
|
|
14328
|
+
)
|
|
14329
|
+
})
|
|
14330
|
+
).nullable()
|
|
14331
|
+
}).nullish(),
|
|
14332
|
+
finish_reason: z.string().nullable().optional(),
|
|
14333
|
+
index: z.number()
|
|
14334
|
+
})
|
|
14335
|
+
)
|
|
14336
|
+
}),
|
|
14337
|
+
OpenRouterErrorResponseSchema
|
|
14338
|
+
]);
|
|
14339
|
+
function prepareToolsAndToolChoice(mode) {
|
|
14340
|
+
var _a;
|
|
14341
|
+
const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
|
|
14342
|
+
if (tools == null) {
|
|
14343
|
+
return { tools: void 0, tool_choice: void 0 };
|
|
14344
|
+
}
|
|
14345
|
+
const mappedTools = tools.map((tool) => {
|
|
14346
|
+
if (isFunctionTool(tool)) {
|
|
14347
|
+
return {
|
|
14348
|
+
type: "function",
|
|
14349
|
+
function: {
|
|
14350
|
+
name: tool.name,
|
|
14351
|
+
description: tool.description,
|
|
14352
|
+
parameters: tool.parameters
|
|
14353
|
+
}
|
|
14354
|
+
};
|
|
14355
|
+
} else {
|
|
14356
|
+
return {
|
|
14357
|
+
type: "function",
|
|
14358
|
+
function: {
|
|
14359
|
+
name: tool.name
|
|
14360
|
+
}
|
|
14361
|
+
};
|
|
14362
|
+
}
|
|
14363
|
+
});
|
|
14364
|
+
const toolChoice = mode.toolChoice;
|
|
14365
|
+
if (toolChoice == null) {
|
|
14366
|
+
return { tools: mappedTools, tool_choice: void 0 };
|
|
14367
|
+
}
|
|
14368
|
+
const type = toolChoice.type;
|
|
14369
|
+
switch (type) {
|
|
14370
|
+
case "auto":
|
|
14371
|
+
case "none":
|
|
14372
|
+
case "required":
|
|
14373
|
+
return { tools: mappedTools, tool_choice: type };
|
|
14374
|
+
case "tool":
|
|
14375
|
+
return {
|
|
14376
|
+
tools: mappedTools,
|
|
14377
|
+
tool_choice: {
|
|
14378
|
+
type: "function",
|
|
14379
|
+
function: {
|
|
14380
|
+
name: toolChoice.toolName
|
|
14381
|
+
}
|
|
14382
|
+
}
|
|
14383
|
+
};
|
|
14384
|
+
default: {
|
|
14385
|
+
const _exhaustiveCheck = type;
|
|
14386
|
+
throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
|
|
14387
|
+
}
|
|
14388
|
+
}
|
|
14389
|
+
}
|
|
14390
|
+
function convertToOpenRouterCompletionPrompt({
|
|
14391
|
+
prompt,
|
|
14392
|
+
inputFormat,
|
|
14393
|
+
user = "user",
|
|
14394
|
+
assistant = "assistant"
|
|
14395
|
+
}) {
|
|
14396
|
+
if (inputFormat === "prompt" && prompt.length === 1 && prompt[0] && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0] && prompt[0].content[0].type === "text") {
|
|
14397
|
+
return { prompt: prompt[0].content[0].text };
|
|
14398
|
+
}
|
|
14399
|
+
let text = "";
|
|
14400
|
+
if (prompt[0] && prompt[0].role === "system") {
|
|
14401
|
+
text += `${prompt[0].content}
|
|
14402
|
+
|
|
14403
|
+
`;
|
|
14404
|
+
prompt = prompt.slice(1);
|
|
14405
|
+
}
|
|
14406
|
+
for (const { role, content } of prompt) {
|
|
14407
|
+
switch (role) {
|
|
14408
|
+
case "system": {
|
|
14409
|
+
throw new InvalidPromptError({
|
|
14410
|
+
message: "Unexpected system message in prompt: ${content}",
|
|
14411
|
+
prompt
|
|
14412
|
+
});
|
|
14413
|
+
}
|
|
14414
|
+
case "user": {
|
|
14415
|
+
const userMessage = content.map((part) => {
|
|
14416
|
+
switch (part.type) {
|
|
14417
|
+
case "text": {
|
|
14418
|
+
return part.text;
|
|
14419
|
+
}
|
|
14420
|
+
case "image": {
|
|
14421
|
+
throw new UnsupportedFunctionalityError({
|
|
14422
|
+
functionality: "images"
|
|
14423
|
+
});
|
|
14424
|
+
}
|
|
14425
|
+
case "file": {
|
|
14426
|
+
throw new UnsupportedFunctionalityError({
|
|
14427
|
+
functionality: "file attachments"
|
|
14428
|
+
});
|
|
14429
|
+
}
|
|
14430
|
+
default: {
|
|
14431
|
+
const _exhaustiveCheck = part;
|
|
14432
|
+
throw new Error(
|
|
14433
|
+
`Unsupported content type: ${_exhaustiveCheck}`
|
|
14434
|
+
);
|
|
14435
|
+
}
|
|
14436
|
+
}
|
|
14437
|
+
}).join("");
|
|
14438
|
+
text += `${user}:
|
|
14439
|
+
${userMessage}
|
|
14440
|
+
|
|
14441
|
+
`;
|
|
14442
|
+
break;
|
|
14443
|
+
}
|
|
14444
|
+
case "assistant": {
|
|
14445
|
+
const assistantMessage = content.map((part) => {
|
|
14446
|
+
switch (part.type) {
|
|
14447
|
+
case "text": {
|
|
14448
|
+
return part.text;
|
|
14449
|
+
}
|
|
14450
|
+
case "tool-call": {
|
|
14451
|
+
throw new UnsupportedFunctionalityError({
|
|
14452
|
+
functionality: "tool-call messages"
|
|
14453
|
+
});
|
|
14454
|
+
}
|
|
14455
|
+
case "reasoning": {
|
|
14456
|
+
throw new UnsupportedFunctionalityError({
|
|
14457
|
+
functionality: "reasoning messages"
|
|
14458
|
+
});
|
|
14459
|
+
}
|
|
14460
|
+
case "redacted-reasoning": {
|
|
14461
|
+
throw new UnsupportedFunctionalityError({
|
|
14462
|
+
functionality: "redacted reasoning messages"
|
|
14463
|
+
});
|
|
14464
|
+
}
|
|
14465
|
+
default: {
|
|
14466
|
+
const _exhaustiveCheck = part;
|
|
14467
|
+
throw new Error(
|
|
14468
|
+
`Unsupported content type: ${_exhaustiveCheck}`
|
|
14469
|
+
);
|
|
14470
|
+
}
|
|
14471
|
+
}
|
|
14472
|
+
}).join("");
|
|
14473
|
+
text += `${assistant}:
|
|
14474
|
+
${assistantMessage}
|
|
14475
|
+
|
|
14476
|
+
`;
|
|
14477
|
+
break;
|
|
14478
|
+
}
|
|
14479
|
+
case "tool": {
|
|
14480
|
+
throw new UnsupportedFunctionalityError({
|
|
14481
|
+
functionality: "tool messages"
|
|
14482
|
+
});
|
|
14483
|
+
}
|
|
14484
|
+
default: {
|
|
14485
|
+
const _exhaustiveCheck = role;
|
|
14486
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
|
14487
|
+
}
|
|
14488
|
+
}
|
|
14489
|
+
}
|
|
14490
|
+
text += `${assistant}:
|
|
14491
|
+
`;
|
|
14492
|
+
return {
|
|
14493
|
+
prompt: text
|
|
14494
|
+
};
|
|
14495
|
+
}
|
|
14496
|
+
|
|
14497
|
+
// src/map-openrouter-completion-logprobs.ts
|
|
14498
|
+
function mapOpenRouterCompletionLogProbs(logprobs) {
|
|
14499
|
+
return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => {
|
|
14500
|
+
var _a, _b;
|
|
14501
|
+
return {
|
|
14502
|
+
token,
|
|
14503
|
+
logprob: (_a = logprobs.token_logprobs[index]) != null ? _a : 0,
|
|
14504
|
+
topLogprobs: logprobs.top_logprobs ? Object.entries((_b = logprobs.top_logprobs[index]) != null ? _b : {}).map(
|
|
14505
|
+
([token2, logprob]) => ({
|
|
14506
|
+
token: token2,
|
|
14507
|
+
logprob
|
|
14508
|
+
})
|
|
14509
|
+
) : []
|
|
14510
|
+
};
|
|
14511
|
+
});
|
|
14512
|
+
}
|
|
14513
|
+
|
|
14514
|
+
// src/openrouter-completion-language-model.ts
|
|
14515
|
+
var OpenRouterCompletionLanguageModel = class {
|
|
14516
|
+
constructor(modelId, settings, config) {
|
|
14517
|
+
this.specificationVersion = "v1";
|
|
14518
|
+
this.defaultObjectGenerationMode = void 0;
|
|
14519
|
+
this.modelId = modelId;
|
|
14520
|
+
this.settings = settings;
|
|
14521
|
+
this.config = config;
|
|
14522
|
+
}
|
|
14523
|
+
get provider() {
|
|
14524
|
+
return this.config.provider;
|
|
14525
|
+
}
|
|
14526
|
+
getArgs({
|
|
14527
|
+
mode,
|
|
14528
|
+
inputFormat,
|
|
14529
|
+
prompt,
|
|
14530
|
+
maxTokens,
|
|
14531
|
+
temperature,
|
|
14532
|
+
topP,
|
|
14533
|
+
frequencyPenalty,
|
|
14534
|
+
presencePenalty,
|
|
14535
|
+
seed,
|
|
14536
|
+
responseFormat,
|
|
14537
|
+
topK,
|
|
14538
|
+
stopSequences,
|
|
14539
|
+
providerMetadata
|
|
14540
|
+
}) {
|
|
14541
|
+
var _a, _b;
|
|
14542
|
+
const type = mode.type;
|
|
14543
|
+
const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
|
|
14544
|
+
const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
|
|
14545
|
+
prompt,
|
|
14546
|
+
inputFormat
|
|
14547
|
+
});
|
|
14548
|
+
const baseArgs = __spreadValues(__spreadValues(__spreadValues({
|
|
14549
|
+
// model id:
|
|
14550
|
+
model: this.modelId,
|
|
14551
|
+
models: this.settings.models,
|
|
14552
|
+
// model specific settings:
|
|
14553
|
+
logit_bias: this.settings.logitBias,
|
|
14554
|
+
logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
|
|
14555
|
+
suffix: this.settings.suffix,
|
|
14556
|
+
user: this.settings.user,
|
|
14557
|
+
// standardized settings:
|
|
14558
|
+
max_tokens: maxTokens,
|
|
14559
|
+
temperature,
|
|
14560
|
+
top_p: topP,
|
|
14561
|
+
frequency_penalty: frequencyPenalty,
|
|
14562
|
+
presence_penalty: presencePenalty,
|
|
14563
|
+
seed,
|
|
14564
|
+
stop: stopSequences,
|
|
14565
|
+
response_format: responseFormat,
|
|
14566
|
+
top_k: topK,
|
|
14567
|
+
// prompt:
|
|
14568
|
+
prompt: completionPrompt,
|
|
14569
|
+
// OpenRouter specific settings:
|
|
14570
|
+
include_reasoning: this.settings.includeReasoning,
|
|
14571
|
+
reasoning: this.settings.reasoning
|
|
14572
|
+
}, this.config.extraBody), this.settings.extraBody), extraCallingBody);
|
|
14573
|
+
switch (type) {
|
|
14574
|
+
case "regular": {
|
|
14575
|
+
if ((_b = mode.tools) == null ? void 0 : _b.length) {
|
|
14576
|
+
throw new UnsupportedFunctionalityError({
|
|
14577
|
+
functionality: "tools"
|
|
14578
|
+
});
|
|
14579
|
+
}
|
|
14580
|
+
if (mode.toolChoice) {
|
|
14581
|
+
throw new UnsupportedFunctionalityError({
|
|
14582
|
+
functionality: "toolChoice"
|
|
14583
|
+
});
|
|
14584
|
+
}
|
|
14585
|
+
return baseArgs;
|
|
14586
|
+
}
|
|
14587
|
+
case "object-json": {
|
|
14588
|
+
throw new UnsupportedFunctionalityError({
|
|
14589
|
+
functionality: "object-json mode"
|
|
14590
|
+
});
|
|
14591
|
+
}
|
|
14592
|
+
case "object-tool": {
|
|
14593
|
+
throw new UnsupportedFunctionalityError({
|
|
14594
|
+
functionality: "object-tool mode"
|
|
14595
|
+
});
|
|
14596
|
+
}
|
|
14597
|
+
// Handle all non-text types with a single default case
|
|
14598
|
+
default: {
|
|
14599
|
+
const _exhaustiveCheck = type;
|
|
14600
|
+
throw new UnsupportedFunctionalityError({
|
|
14601
|
+
functionality: `${_exhaustiveCheck} mode`
|
|
14602
|
+
});
|
|
14603
|
+
}
|
|
14604
|
+
}
|
|
14605
|
+
}
|
|
14606
|
+
async doGenerate(options) {
|
|
14607
|
+
var _b, _c, _d, _e, _f;
|
|
14608
|
+
const args = this.getArgs(options);
|
|
14609
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14610
|
+
url: this.config.url({
|
|
14611
|
+
path: "/completions",
|
|
14612
|
+
modelId: this.modelId
|
|
14613
|
+
}),
|
|
14614
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14615
|
+
body: args,
|
|
14616
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14617
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
14618
|
+
OpenRouterCompletionChunkSchema
|
|
14619
|
+
),
|
|
14620
|
+
abortSignal: options.abortSignal,
|
|
14621
|
+
fetch: this.config.fetch
|
|
14622
|
+
});
|
|
14623
|
+
const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
|
|
14624
|
+
if ("error" in response) {
|
|
14625
|
+
throw new Error(`${response.error.message}`);
|
|
14626
|
+
}
|
|
14627
|
+
const choice = response.choices[0];
|
|
14628
|
+
if (!choice) {
|
|
14629
|
+
throw new Error("No choice in OpenRouter completion response");
|
|
14630
|
+
}
|
|
14631
|
+
return {
|
|
14632
|
+
response: {
|
|
14633
|
+
id: response.id,
|
|
14634
|
+
modelId: response.model
|
|
14635
|
+
},
|
|
14636
|
+
text: (_b = choice.text) != null ? _b : "",
|
|
14637
|
+
reasoning: choice.reasoning || void 0,
|
|
14638
|
+
usage: {
|
|
14639
|
+
promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : 0,
|
|
14640
|
+
completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : 0
|
|
14641
|
+
},
|
|
14642
|
+
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
|
|
14643
|
+
logprobs: mapOpenRouterCompletionLogProbs(choice.logprobs),
|
|
14644
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14645
|
+
rawResponse: { headers: responseHeaders },
|
|
14646
|
+
warnings: []
|
|
14647
|
+
};
|
|
14648
|
+
}
|
|
14649
|
+
async doStream(options) {
|
|
14650
|
+
const args = this.getArgs(options);
|
|
14651
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14652
|
+
url: this.config.url({
|
|
14653
|
+
path: "/completions",
|
|
14654
|
+
modelId: this.modelId
|
|
14655
|
+
}),
|
|
14656
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14657
|
+
body: __spreadProps(__spreadValues({}, this.getArgs(options)), {
|
|
14658
|
+
stream: true,
|
|
14659
|
+
// only include stream_options when in strict compatibility mode:
|
|
14660
|
+
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
14661
|
+
}),
|
|
14662
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14663
|
+
successfulResponseHandler: createEventSourceResponseHandler(
|
|
14664
|
+
OpenRouterCompletionChunkSchema
|
|
14665
|
+
),
|
|
14666
|
+
abortSignal: options.abortSignal,
|
|
14667
|
+
fetch: this.config.fetch
|
|
14668
|
+
});
|
|
14669
|
+
const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
|
|
14670
|
+
let finishReason = "other";
|
|
14671
|
+
let usage = {
|
|
14672
|
+
promptTokens: Number.NaN,
|
|
14673
|
+
completionTokens: Number.NaN
|
|
14674
|
+
};
|
|
14675
|
+
let logprobs;
|
|
14676
|
+
return {
|
|
14677
|
+
stream: response.pipeThrough(
|
|
14678
|
+
new TransformStream({
|
|
14679
|
+
transform(chunk, controller) {
|
|
14680
|
+
if (!chunk.success) {
|
|
14681
|
+
finishReason = "error";
|
|
14682
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
|
14683
|
+
return;
|
|
14684
|
+
}
|
|
14685
|
+
const value = chunk.value;
|
|
14686
|
+
if ("error" in value) {
|
|
14687
|
+
finishReason = "error";
|
|
14688
|
+
controller.enqueue({ type: "error", error: value.error });
|
|
14689
|
+
return;
|
|
14690
|
+
}
|
|
14691
|
+
if (value.usage != null) {
|
|
14692
|
+
usage = {
|
|
14693
|
+
promptTokens: value.usage.prompt_tokens,
|
|
14694
|
+
completionTokens: value.usage.completion_tokens
|
|
14695
|
+
};
|
|
14696
|
+
}
|
|
14697
|
+
const choice = value.choices[0];
|
|
14698
|
+
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
14699
|
+
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
14700
|
+
}
|
|
14701
|
+
if ((choice == null ? void 0 : choice.text) != null) {
|
|
14702
|
+
controller.enqueue({
|
|
14703
|
+
type: "text-delta",
|
|
14704
|
+
textDelta: choice.text
|
|
14705
|
+
});
|
|
14706
|
+
}
|
|
14707
|
+
const mappedLogprobs = mapOpenRouterCompletionLogProbs(
|
|
14708
|
+
choice == null ? void 0 : choice.logprobs
|
|
14709
|
+
);
|
|
14710
|
+
if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
|
|
14711
|
+
if (logprobs === void 0) logprobs = [];
|
|
14712
|
+
logprobs.push(...mappedLogprobs);
|
|
14713
|
+
}
|
|
14714
|
+
},
|
|
14715
|
+
flush(controller) {
|
|
14716
|
+
controller.enqueue({
|
|
14717
|
+
type: "finish",
|
|
14718
|
+
finishReason,
|
|
14719
|
+
logprobs,
|
|
14720
|
+
usage
|
|
14721
|
+
});
|
|
14722
|
+
}
|
|
14723
|
+
})
|
|
14724
|
+
),
|
|
14725
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14726
|
+
rawResponse: { headers: responseHeaders },
|
|
14727
|
+
warnings: []
|
|
14728
|
+
};
|
|
14729
|
+
}
|
|
14730
|
+
};
|
|
14731
|
+
var OpenRouterCompletionChunkSchema = z.union([
|
|
14732
|
+
z.object({
|
|
14733
|
+
id: z.string().optional(),
|
|
14734
|
+
model: z.string().optional(),
|
|
14735
|
+
choices: z.array(
|
|
14736
|
+
z.object({
|
|
14737
|
+
text: z.string(),
|
|
14738
|
+
reasoning: z.string().nullish().optional(),
|
|
14739
|
+
finish_reason: z.string().nullish(),
|
|
14740
|
+
index: z.number(),
|
|
14741
|
+
logprobs: z.object({
|
|
14742
|
+
tokens: z.array(z.string()),
|
|
14743
|
+
token_logprobs: z.array(z.number()),
|
|
14744
|
+
top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
|
|
14745
|
+
}).nullable().optional()
|
|
14746
|
+
})
|
|
14747
|
+
),
|
|
14748
|
+
usage: z.object({
|
|
14749
|
+
prompt_tokens: z.number(),
|
|
14750
|
+
completion_tokens: z.number()
|
|
14751
|
+
}).optional().nullable()
|
|
14752
|
+
}),
|
|
14753
|
+
OpenRouterErrorResponseSchema
|
|
14754
|
+
]);
|
|
14755
|
+
function createOpenRouter(options = {}) {
|
|
14756
|
+
var _a, _b, _c;
|
|
14757
|
+
const baseURL = (_b = withoutTrailingSlash((_a = options.baseURL) != null ? _a : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
|
|
14758
|
+
const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
|
|
14759
|
+
const getHeaders = () => __spreadValues({
|
|
14760
|
+
Authorization: `Bearer ${loadApiKey({
|
|
14761
|
+
apiKey: options.apiKey,
|
|
14762
|
+
environmentVariableName: "OPENROUTER_API_KEY",
|
|
14763
|
+
description: "OpenRouter"
|
|
14764
|
+
})}`
|
|
14765
|
+
}, options.headers);
|
|
14766
|
+
const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
|
|
14767
|
+
provider: "openrouter.chat",
|
|
14768
|
+
url: ({ path }) => `${baseURL}${path}`,
|
|
14769
|
+
headers: getHeaders,
|
|
14770
|
+
compatibility,
|
|
14771
|
+
fetch: options.fetch,
|
|
14772
|
+
extraBody: options.extraBody
|
|
14773
|
+
});
|
|
14774
|
+
const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
|
|
14775
|
+
provider: "openrouter.completion",
|
|
14776
|
+
url: ({ path }) => `${baseURL}${path}`,
|
|
14777
|
+
headers: getHeaders,
|
|
14778
|
+
compatibility,
|
|
14779
|
+
fetch: options.fetch,
|
|
14780
|
+
extraBody: options.extraBody
|
|
14781
|
+
});
|
|
14782
|
+
const createLanguageModel = (modelId, settings) => {
|
|
14783
|
+
if (new.target) {
|
|
14784
|
+
throw new Error(
|
|
14785
|
+
"The OpenRouter model function cannot be called with the new keyword."
|
|
14786
|
+
);
|
|
14787
|
+
}
|
|
14788
|
+
if (modelId === "openai/gpt-3.5-turbo-instruct") {
|
|
14789
|
+
return createCompletionModel(
|
|
14790
|
+
modelId,
|
|
14791
|
+
settings
|
|
14792
|
+
);
|
|
14793
|
+
}
|
|
14794
|
+
return createChatModel(modelId, settings);
|
|
14795
|
+
};
|
|
14796
|
+
const provider = function(modelId, settings) {
|
|
14797
|
+
return createLanguageModel(modelId, settings);
|
|
14798
|
+
};
|
|
14799
|
+
provider.languageModel = createLanguageModel;
|
|
14800
|
+
provider.chat = createChatModel;
|
|
14801
|
+
provider.completion = createCompletionModel;
|
|
14802
|
+
return provider;
|
|
14803
|
+
}
|
|
14804
|
+
createOpenRouter({
|
|
14805
|
+
compatibility: "strict"
|
|
14806
|
+
// strict for OpenRouter API
|
|
14807
|
+
});
|
|
14808
|
+
|
|
14809
|
+
class RetryLanguageModel {
|
|
14810
|
+
constructor(llms, names, stream_first_timeout) {
|
|
14811
|
+
this.llms = llms;
|
|
14812
|
+
this.names = names || [];
|
|
14813
|
+
this.stream_first_timeout = stream_first_timeout || 30000;
|
|
14814
|
+
if (this.names.indexOf("default") == -1) {
|
|
14815
|
+
this.names.push("default");
|
|
14816
|
+
}
|
|
14817
|
+
}
|
|
14818
|
+
async call(request) {
|
|
14819
|
+
return await this.doGenerate({
|
|
14820
|
+
inputFormat: "messages",
|
|
14821
|
+
mode: {
|
|
14822
|
+
type: "regular",
|
|
14823
|
+
tools: request.tools,
|
|
14824
|
+
toolChoice: request.toolChoice,
|
|
14825
|
+
},
|
|
14826
|
+
prompt: request.messages,
|
|
14827
|
+
maxTokens: request.maxTokens || config.maxTokens,
|
|
14828
|
+
temperature: request.temperature,
|
|
14829
|
+
topP: request.topP,
|
|
14830
|
+
topK: request.topK,
|
|
14831
|
+
providerMetadata: {},
|
|
12795
14832
|
abortSignal: request.abortSignal,
|
|
12796
14833
|
});
|
|
12797
14834
|
}
|
|
@@ -12906,7 +14943,7 @@ class RetryLanguageModel {
|
|
|
12906
14943
|
baseURL: llm.config?.baseURL,
|
|
12907
14944
|
}).languageModel(llm.model, {
|
|
12908
14945
|
// disable_parallel_tool_use
|
|
12909
|
-
parallelToolCalls: false,
|
|
14946
|
+
parallelToolCalls: llm.config?.parallelToolCalls || false,
|
|
12910
14947
|
});
|
|
12911
14948
|
}
|
|
12912
14949
|
else if (llm.provider == "anthropic") {
|
|
@@ -12924,10 +14961,16 @@ class RetryLanguageModel {
|
|
|
12924
14961
|
else if (llm.provider == "aws") {
|
|
12925
14962
|
let keys = llm.apiKey.split("=");
|
|
12926
14963
|
return createAmazonBedrock({
|
|
12927
|
-
region: llm.config?.region || "us-east-2",
|
|
12928
|
-
baseURL: llm.config?.baseURL,
|
|
12929
14964
|
accessKeyId: keys[0],
|
|
12930
14965
|
secretAccessKey: keys[1],
|
|
14966
|
+
baseURL: llm.config?.baseURL,
|
|
14967
|
+
region: llm.config?.region || "us-east-1",
|
|
14968
|
+
}).languageModel(llm.model);
|
|
14969
|
+
}
|
|
14970
|
+
else if (llm.provider == "openrouter") {
|
|
14971
|
+
return createOpenRouter({
|
|
14972
|
+
apiKey: llm.apiKey,
|
|
14973
|
+
baseURL: llm.config?.baseURL,
|
|
12931
14974
|
}).languageModel(llm.model);
|
|
12932
14975
|
}
|
|
12933
14976
|
else {
|
|
@@ -15509,59 +17552,276 @@ function parseWorkflowNodes(nodes, xmlNodes) {
|
|
|
15509
17552
|
if (triggerNode.length > 0) {
|
|
15510
17553
|
parseWorkflowNodes(_nodes, triggerNode[0].childNodes);
|
|
15511
17554
|
}
|
|
15512
|
-
nodes.push(node);
|
|
15513
|
-
break;
|
|
17555
|
+
nodes.push(node);
|
|
17556
|
+
break;
|
|
17557
|
+
}
|
|
17558
|
+
}
|
|
17559
|
+
}
|
|
17560
|
+
}
|
|
17561
|
+
function buildAgentRootXml(agentXml, mainTaskPrompt, nodeCallback) {
|
|
17562
|
+
const parser = new domParserExports.DOMParser();
|
|
17563
|
+
const doc = parser.parseFromString(agentXml, "text/xml");
|
|
17564
|
+
let agentNode = doc.getElementsByTagName("agent");
|
|
17565
|
+
let nodesNode = doc.getElementsByTagName("nodes");
|
|
17566
|
+
if (nodesNode.length > 0) {
|
|
17567
|
+
let nodes = nodesNode[0].childNodes;
|
|
17568
|
+
let nodeId = 0;
|
|
17569
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
17570
|
+
let node = nodes[i];
|
|
17571
|
+
if (node.nodeType == 1) {
|
|
17572
|
+
node.setAttribute("id", nodeId + "");
|
|
17573
|
+
nodeCallback && nodeCallback(nodeId, node);
|
|
17574
|
+
nodeId++;
|
|
17575
|
+
}
|
|
17576
|
+
}
|
|
17577
|
+
}
|
|
17578
|
+
// <root><mainTask></mainTask><currentTask></currentTask><nodes><node id="0"></node></nodes></root>
|
|
17579
|
+
let agentInnerHTML = getInnerXML(agentNode[0]);
|
|
17580
|
+
let prefix = agentInnerHTML.substring(0, agentInnerHTML.indexOf("<task>"));
|
|
17581
|
+
agentInnerHTML = agentInnerHTML
|
|
17582
|
+
.replace("<task>", "<currentTask>")
|
|
17583
|
+
.replace("</task>", "</currentTask>");
|
|
17584
|
+
return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
|
|
17585
|
+
}
|
|
17586
|
+
function extractAgentXmlNode(agentXml, nodeId) {
|
|
17587
|
+
const parser = new domParserExports.DOMParser();
|
|
17588
|
+
const doc = parser.parseFromString(agentXml, "text/xml");
|
|
17589
|
+
let nodesNode = doc.getElementsByTagName("nodes");
|
|
17590
|
+
if (nodesNode.length > 0) {
|
|
17591
|
+
let nodes = nodesNode[0].childNodes;
|
|
17592
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
17593
|
+
let node = nodes[i];
|
|
17594
|
+
if (node.nodeType == 1 && node.getAttribute("id") == nodeId + "") {
|
|
17595
|
+
return node;
|
|
17596
|
+
}
|
|
17597
|
+
}
|
|
17598
|
+
}
|
|
17599
|
+
return null;
|
|
17600
|
+
}
|
|
17601
|
+
function getInnerXML(node) {
|
|
17602
|
+
let result = "";
|
|
17603
|
+
const serializer = new domParserExports.XMLSerializer();
|
|
17604
|
+
for (let i = 0; i < node.childNodes.length; i++) {
|
|
17605
|
+
result += serializer.serializeToString(node.childNodes[i]);
|
|
17606
|
+
}
|
|
17607
|
+
return result;
|
|
17608
|
+
}
|
|
17609
|
+
|
|
17610
|
+
const TOOL_NAME$5 = "task_snapshot";
|
|
17611
|
+
class TaskSnapshotTool {
|
|
17612
|
+
constructor() {
|
|
17613
|
+
this.name = TOOL_NAME$5;
|
|
17614
|
+
this.description = `Task snapshot archive, recording key information of the current task, updating task node status, facilitating subsequent continuation of operation.`;
|
|
17615
|
+
this.parameters = {
|
|
17616
|
+
type: "object",
|
|
17617
|
+
properties: {
|
|
17618
|
+
doneIds: {
|
|
17619
|
+
type: "array",
|
|
17620
|
+
description: "Update task node completion status, list of completed node IDs.",
|
|
17621
|
+
items: {
|
|
17622
|
+
type: "number",
|
|
17623
|
+
},
|
|
17624
|
+
},
|
|
17625
|
+
taskSnapshot: {
|
|
17626
|
+
type: "string",
|
|
17627
|
+
description: "Current task important information, as detailed as possible, ensure that the task progress can be restored through this information later, output records of completed task information, contextual information, variables used, pending tasks information, etc.",
|
|
17628
|
+
},
|
|
17629
|
+
},
|
|
17630
|
+
required: ["doneIds", "taskSnapshot"],
|
|
17631
|
+
};
|
|
17632
|
+
}
|
|
17633
|
+
async execute(args, agentContext) {
|
|
17634
|
+
let doneIds = args.doneIds;
|
|
17635
|
+
let taskSnapshot = args.taskSnapshot;
|
|
17636
|
+
let agentNode = agentContext.agentChain.agent;
|
|
17637
|
+
let taskPrompt = agentContext.context.chain.taskPrompt;
|
|
17638
|
+
let agentXml = buildAgentRootXml(agentNode.xml, taskPrompt, (nodeId, node) => {
|
|
17639
|
+
let done = doneIds.indexOf(nodeId) > -1;
|
|
17640
|
+
node.setAttribute("status", done ? "done" : "todo");
|
|
17641
|
+
});
|
|
17642
|
+
let text = "The current task has been interrupted. Below is a snapshot of the task execution history.\n" +
|
|
17643
|
+
"# Task Snapshot\n" +
|
|
17644
|
+
taskSnapshot.trim() +
|
|
17645
|
+
"\n\n# Task\n" +
|
|
17646
|
+
agentXml;
|
|
17647
|
+
return {
|
|
17648
|
+
content: [
|
|
17649
|
+
{
|
|
17650
|
+
type: "text",
|
|
17651
|
+
text: text,
|
|
17652
|
+
},
|
|
17653
|
+
],
|
|
17654
|
+
};
|
|
17655
|
+
}
|
|
17656
|
+
}
|
|
17657
|
+
|
|
17658
|
+
function handleMultiImageFileMessage(messages) {
|
|
17659
|
+
let imageNum = 0;
|
|
17660
|
+
let fileNum = 0;
|
|
17661
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
17662
|
+
let message = messages[i];
|
|
17663
|
+
if (message.role == "user") {
|
|
17664
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17665
|
+
let content = message.content[j];
|
|
17666
|
+
if (content.type == "image") {
|
|
17667
|
+
if (++imageNum == 1) {
|
|
17668
|
+
break;
|
|
17669
|
+
}
|
|
17670
|
+
content = {
|
|
17671
|
+
type: "text",
|
|
17672
|
+
text: "[image]",
|
|
17673
|
+
};
|
|
17674
|
+
message.content[j] = content;
|
|
17675
|
+
}
|
|
17676
|
+
else if (content.type == "file") {
|
|
17677
|
+
if (++fileNum == 1) {
|
|
17678
|
+
break;
|
|
17679
|
+
}
|
|
17680
|
+
content = {
|
|
17681
|
+
type: "text",
|
|
17682
|
+
text: "[file]",
|
|
17683
|
+
};
|
|
17684
|
+
message.content[j] = content;
|
|
17685
|
+
}
|
|
17686
|
+
}
|
|
17687
|
+
}
|
|
17688
|
+
else if (message.role == "tool") {
|
|
17689
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17690
|
+
let content = message.content[j];
|
|
17691
|
+
let tool_content = content.content;
|
|
17692
|
+
if (!tool_content || tool_content.length == 0) {
|
|
17693
|
+
continue;
|
|
17694
|
+
}
|
|
17695
|
+
for (let r = 0; r < tool_content.length; r++) {
|
|
17696
|
+
let _content = tool_content[r];
|
|
17697
|
+
if (_content.type == "image") {
|
|
17698
|
+
if (++imageNum == 1) {
|
|
17699
|
+
break;
|
|
17700
|
+
}
|
|
17701
|
+
_content = {
|
|
17702
|
+
type: "text",
|
|
17703
|
+
text: "[image]",
|
|
17704
|
+
};
|
|
17705
|
+
tool_content[r] = _content;
|
|
17706
|
+
}
|
|
17707
|
+
}
|
|
15514
17708
|
}
|
|
15515
17709
|
}
|
|
15516
17710
|
}
|
|
15517
17711
|
}
|
|
15518
|
-
function
|
|
15519
|
-
|
|
15520
|
-
|
|
15521
|
-
|
|
15522
|
-
|
|
15523
|
-
|
|
15524
|
-
|
|
15525
|
-
|
|
15526
|
-
|
|
15527
|
-
let
|
|
15528
|
-
|
|
15529
|
-
|
|
15530
|
-
|
|
15531
|
-
|
|
17712
|
+
function removeDuplicateToolUse(results) {
|
|
17713
|
+
if (results.length <= 1 ||
|
|
17714
|
+
results.filter((r) => r.type == "tool-call").length <= 1) {
|
|
17715
|
+
return results;
|
|
17716
|
+
}
|
|
17717
|
+
let _results = [];
|
|
17718
|
+
let tool_uniques = [];
|
|
17719
|
+
for (let i = 0; i < results.length; i++) {
|
|
17720
|
+
if (results[i].type === "tool-call") {
|
|
17721
|
+
let tool = results[i];
|
|
17722
|
+
let key = tool.toolName + tool.args;
|
|
17723
|
+
if (tool_uniques.indexOf(key) == -1) {
|
|
17724
|
+
_results.push(results[i]);
|
|
17725
|
+
tool_uniques.push(key);
|
|
15532
17726
|
}
|
|
15533
17727
|
}
|
|
17728
|
+
else {
|
|
17729
|
+
_results.push(results[i]);
|
|
17730
|
+
}
|
|
15534
17731
|
}
|
|
15535
|
-
|
|
15536
|
-
let agentInnerHTML = getInnerXML(agentNode[0]);
|
|
15537
|
-
let prefix = agentInnerHTML.substring(0, agentInnerHTML.indexOf("<task>"));
|
|
15538
|
-
agentInnerHTML = agentInnerHTML
|
|
15539
|
-
.replace("<task>", "<currentTask>")
|
|
15540
|
-
.replace("</task>", "</currentTask>");
|
|
15541
|
-
return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
|
|
17732
|
+
return _results;
|
|
15542
17733
|
}
|
|
15543
|
-
function
|
|
15544
|
-
|
|
15545
|
-
|
|
15546
|
-
let
|
|
15547
|
-
|
|
15548
|
-
|
|
15549
|
-
|
|
15550
|
-
|
|
15551
|
-
|
|
15552
|
-
|
|
17734
|
+
function extractUsedTool(messages, agentTools) {
|
|
17735
|
+
let tools = [];
|
|
17736
|
+
let toolNames = [];
|
|
17737
|
+
for (let i = 0; i < messages.length; i++) {
|
|
17738
|
+
let message = messages[i];
|
|
17739
|
+
if (message.role == "tool") {
|
|
17740
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17741
|
+
let toolName = message.content[j].toolName;
|
|
17742
|
+
if (toolNames.indexOf(toolName) > -1) {
|
|
17743
|
+
continue;
|
|
17744
|
+
}
|
|
17745
|
+
toolNames.push(toolName);
|
|
17746
|
+
let tool = agentTools.filter((tool) => tool.name === toolName)[0];
|
|
17747
|
+
if (tool) {
|
|
17748
|
+
tools.push(tool);
|
|
17749
|
+
}
|
|
15553
17750
|
}
|
|
15554
17751
|
}
|
|
15555
17752
|
}
|
|
15556
|
-
return
|
|
17753
|
+
return tools;
|
|
15557
17754
|
}
|
|
15558
|
-
function
|
|
15559
|
-
|
|
15560
|
-
|
|
15561
|
-
for (let i = 0; i < node.childNodes.length; i++) {
|
|
15562
|
-
result += serializer.serializeToString(node.childNodes[i]);
|
|
17755
|
+
async function compressAgentMessages(agentContext, rlm, messages, tools) {
|
|
17756
|
+
if (messages.length < 10) {
|
|
17757
|
+
return;
|
|
15563
17758
|
}
|
|
15564
|
-
|
|
17759
|
+
// extract used tool
|
|
17760
|
+
let usedTools = extractUsedTool(messages, tools);
|
|
17761
|
+
let snapshotTool = new TaskSnapshotTool();
|
|
17762
|
+
let newTools = mergeTools(usedTools, [
|
|
17763
|
+
{
|
|
17764
|
+
type: "function",
|
|
17765
|
+
name: snapshotTool.name,
|
|
17766
|
+
description: snapshotTool.description,
|
|
17767
|
+
parameters: snapshotTool.parameters,
|
|
17768
|
+
},
|
|
17769
|
+
]);
|
|
17770
|
+
// handle messages
|
|
17771
|
+
let lastToolIndex = messages.length - 1;
|
|
17772
|
+
let newMessages = messages;
|
|
17773
|
+
for (let r = newMessages.length - 1; r > 3; r--) {
|
|
17774
|
+
if (newMessages[r].role == "tool") {
|
|
17775
|
+
newMessages = newMessages.slice(0, r + 1);
|
|
17776
|
+
lastToolIndex = r;
|
|
17777
|
+
break;
|
|
17778
|
+
}
|
|
17779
|
+
}
|
|
17780
|
+
newMessages.push({
|
|
17781
|
+
role: "user",
|
|
17782
|
+
content: [
|
|
17783
|
+
{
|
|
17784
|
+
type: "text",
|
|
17785
|
+
text: "Please create a snapshot backup of the current task, keeping only key important information and node completion status.",
|
|
17786
|
+
},
|
|
17787
|
+
],
|
|
17788
|
+
});
|
|
17789
|
+
// compress snapshot
|
|
17790
|
+
let result = await callLLM(agentContext, rlm, newMessages, newTools, true, {
|
|
17791
|
+
type: "tool",
|
|
17792
|
+
toolName: snapshotTool.name,
|
|
17793
|
+
});
|
|
17794
|
+
let toolCall = result.filter((s) => s.type == "tool-call")[0];
|
|
17795
|
+
let args = typeof toolCall.args == "string"
|
|
17796
|
+
? JSON.parse(toolCall.args || "{}")
|
|
17797
|
+
: toolCall.args || {};
|
|
17798
|
+
let toolResult = await snapshotTool.execute(args, agentContext);
|
|
17799
|
+
let callback = agentContext.context.config.callback;
|
|
17800
|
+
if (callback) {
|
|
17801
|
+
await callback.onMessage({
|
|
17802
|
+
taskId: agentContext.context.taskId,
|
|
17803
|
+
agentName: toolCall.toolName,
|
|
17804
|
+
nodeId: agentContext.agentChain.agent.id,
|
|
17805
|
+
type: "tool_result",
|
|
17806
|
+
toolId: toolCall.toolCallId,
|
|
17807
|
+
toolName: toolCall.toolName,
|
|
17808
|
+
params: args,
|
|
17809
|
+
toolResult: toolResult,
|
|
17810
|
+
});
|
|
17811
|
+
}
|
|
17812
|
+
// handle original messages
|
|
17813
|
+
let firstToolIndex = 3;
|
|
17814
|
+
for (let i = 0; i < messages.length; i++) {
|
|
17815
|
+
if (messages[0].role == "tool") {
|
|
17816
|
+
firstToolIndex = i;
|
|
17817
|
+
break;
|
|
17818
|
+
}
|
|
17819
|
+
}
|
|
17820
|
+
// system, user, assistant, tool(first), [...], <user>, assistant, tool(last), ...
|
|
17821
|
+
messages.splice(firstToolIndex + 1, lastToolIndex - firstToolIndex - 2, {
|
|
17822
|
+
role: "user",
|
|
17823
|
+
content: toolResult.content.filter((s) => s.type == "text"),
|
|
17824
|
+
});
|
|
15565
17825
|
}
|
|
15566
17826
|
|
|
15567
17827
|
class ToolWrapper {
|
|
@@ -16084,13 +18344,13 @@ class Agent {
|
|
|
16084
18344
|
let controlMcp = await this.controlMcpTools(agentContext, messages, loopNum);
|
|
16085
18345
|
if (controlMcp.mcpTools) {
|
|
16086
18346
|
let mcpTools = await this.listTools(agentNode, context, mcpClient, controlMcp.mcpParams);
|
|
16087
|
-
let usedTools =
|
|
18347
|
+
let usedTools = extractUsedTool(messages, agentTools);
|
|
16088
18348
|
let _agentTools = mergeTools(tools, usedTools);
|
|
16089
18349
|
agentTools = mergeTools(_agentTools, mcpTools);
|
|
16090
18350
|
}
|
|
16091
18351
|
}
|
|
16092
18352
|
await this.handleMessages(agentContext, messages);
|
|
16093
|
-
let results = await
|
|
18353
|
+
let results = await callLLM(agentContext, rlm, messages, this.convertTools(agentTools));
|
|
16094
18354
|
let finalResult = await this.handleResult(agentContext, messages, agentTools, results);
|
|
16095
18355
|
if (finalResult) {
|
|
16096
18356
|
return finalResult;
|
|
@@ -16104,7 +18364,7 @@ class Agent {
|
|
|
16104
18364
|
let context = agentContext.context;
|
|
16105
18365
|
let user_messages = [];
|
|
16106
18366
|
let toolResults = [];
|
|
16107
|
-
results =
|
|
18367
|
+
results = removeDuplicateToolUse(results);
|
|
16108
18368
|
if (results.length == 0) {
|
|
16109
18369
|
return null;
|
|
16110
18370
|
}
|
|
@@ -16188,28 +18448,6 @@ class Agent {
|
|
|
16188
18448
|
let toolNames = this.tools.map((tool) => tool.name);
|
|
16189
18449
|
return tools.filter((tool) => toolNames.indexOf(tool.name) == -1);
|
|
16190
18450
|
}
|
|
16191
|
-
removeDuplicateToolUse(results) {
|
|
16192
|
-
if (results.length <= 1 ||
|
|
16193
|
-
results.filter((r) => r.type == "tool-call").length <= 1) {
|
|
16194
|
-
return results;
|
|
16195
|
-
}
|
|
16196
|
-
let _results = [];
|
|
16197
|
-
let tool_uniques = [];
|
|
16198
|
-
for (let i = 0; i < results.length; i++) {
|
|
16199
|
-
if (results[i].type === "tool-call") {
|
|
16200
|
-
let tool = results[i];
|
|
16201
|
-
let key = tool.toolName + tool.args;
|
|
16202
|
-
if (tool_uniques.indexOf(key) == -1) {
|
|
16203
|
-
_results.push(results[i]);
|
|
16204
|
-
tool_uniques.push(key);
|
|
16205
|
-
}
|
|
16206
|
-
}
|
|
16207
|
-
else {
|
|
16208
|
-
_results.push(results[i]);
|
|
16209
|
-
}
|
|
16210
|
-
}
|
|
16211
|
-
return _results;
|
|
16212
|
-
}
|
|
16213
18451
|
async initMessages(agentContext, tools) {
|
|
16214
18452
|
let messages = [
|
|
16215
18453
|
{
|
|
@@ -16287,27 +18525,6 @@ class Agent {
|
|
|
16287
18525
|
}
|
|
16288
18526
|
return null;
|
|
16289
18527
|
}
|
|
16290
|
-
extractUsedTool(messages, agentTools) {
|
|
16291
|
-
let tools = [];
|
|
16292
|
-
let toolNames = [];
|
|
16293
|
-
for (let i = 0; i < messages.length; i++) {
|
|
16294
|
-
let message = messages[i];
|
|
16295
|
-
if (message.role == "tool") {
|
|
16296
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16297
|
-
let toolName = message.content[j].toolName;
|
|
16298
|
-
if (toolNames.indexOf(toolName) > -1) {
|
|
16299
|
-
continue;
|
|
16300
|
-
}
|
|
16301
|
-
toolNames.push(toolName);
|
|
16302
|
-
let tool = agentTools.filter((tool) => tool.name === toolName)[0];
|
|
16303
|
-
if (tool) {
|
|
16304
|
-
tools.push(tool);
|
|
16305
|
-
}
|
|
16306
|
-
}
|
|
16307
|
-
}
|
|
16308
|
-
}
|
|
16309
|
-
return tools;
|
|
16310
|
-
}
|
|
16311
18528
|
convertToolResult(toolUse, toolResult, user_messages) {
|
|
16312
18529
|
let text = "";
|
|
16313
18530
|
for (let i = 0; i < toolResult.content.length; i++) {
|
|
@@ -16363,218 +18580,7 @@ class Agent {
|
|
|
16363
18580
|
}
|
|
16364
18581
|
async handleMessages(agentContext, messages) {
|
|
16365
18582
|
// Only keep the last image / file
|
|
16366
|
-
|
|
16367
|
-
let fileNum = 0;
|
|
16368
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
16369
|
-
let message = messages[i];
|
|
16370
|
-
if (message.role == "user") {
|
|
16371
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16372
|
-
let content = message.content[j];
|
|
16373
|
-
if (content.type == "image") {
|
|
16374
|
-
if (++imageNum == 1) {
|
|
16375
|
-
break;
|
|
16376
|
-
}
|
|
16377
|
-
content = {
|
|
16378
|
-
type: "text",
|
|
16379
|
-
text: "[image]",
|
|
16380
|
-
};
|
|
16381
|
-
message.content[j] = content;
|
|
16382
|
-
}
|
|
16383
|
-
else if (content.type == "file") {
|
|
16384
|
-
if (++fileNum == 1) {
|
|
16385
|
-
break;
|
|
16386
|
-
}
|
|
16387
|
-
content = {
|
|
16388
|
-
type: "text",
|
|
16389
|
-
text: "[file]",
|
|
16390
|
-
};
|
|
16391
|
-
message.content[j] = content;
|
|
16392
|
-
}
|
|
16393
|
-
}
|
|
16394
|
-
}
|
|
16395
|
-
else if (message.role == "tool") {
|
|
16396
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16397
|
-
let content = message.content[j];
|
|
16398
|
-
let tool_content = content.content;
|
|
16399
|
-
if (!tool_content || tool_content.length == 0) {
|
|
16400
|
-
continue;
|
|
16401
|
-
}
|
|
16402
|
-
for (let r = 0; r < tool_content.length; r++) {
|
|
16403
|
-
let _content = tool_content[r];
|
|
16404
|
-
if (_content.type == "image") {
|
|
16405
|
-
if (++imageNum == 1) {
|
|
16406
|
-
break;
|
|
16407
|
-
}
|
|
16408
|
-
_content = {
|
|
16409
|
-
type: "text",
|
|
16410
|
-
text: "[image]",
|
|
16411
|
-
};
|
|
16412
|
-
tool_content[r] = _content;
|
|
16413
|
-
}
|
|
16414
|
-
}
|
|
16415
|
-
}
|
|
16416
|
-
}
|
|
16417
|
-
}
|
|
16418
|
-
}
|
|
16419
|
-
async callLLM(agentContext, rlm, messages, tools) {
|
|
16420
|
-
let context = agentContext.context;
|
|
16421
|
-
let agentChain = agentContext.agentChain;
|
|
16422
|
-
let agentNode = agentChain.agent;
|
|
16423
|
-
let streamCallback = context.config.callback || {
|
|
16424
|
-
onMessage: async () => { },
|
|
16425
|
-
};
|
|
16426
|
-
let request = {
|
|
16427
|
-
tools: tools,
|
|
16428
|
-
messages: messages,
|
|
16429
|
-
abortSignal: context.controller.signal,
|
|
16430
|
-
};
|
|
16431
|
-
agentChain.agentRequest = request;
|
|
16432
|
-
let result = await rlm.callStream(request);
|
|
16433
|
-
let streamText = "";
|
|
16434
|
-
let thinkText = "";
|
|
16435
|
-
let toolArgsText = "";
|
|
16436
|
-
let streamId = uuidv4();
|
|
16437
|
-
let textStreamDone = false;
|
|
16438
|
-
let toolParts = [];
|
|
16439
|
-
const reader = result.stream.getReader();
|
|
16440
|
-
try {
|
|
16441
|
-
while (true) {
|
|
16442
|
-
context.checkAborted();
|
|
16443
|
-
const { done, value } = await reader.read();
|
|
16444
|
-
if (done) {
|
|
16445
|
-
break;
|
|
16446
|
-
}
|
|
16447
|
-
let chunk = value;
|
|
16448
|
-
switch (chunk.type) {
|
|
16449
|
-
case "text-delta": {
|
|
16450
|
-
streamText += chunk.textDelta || "";
|
|
16451
|
-
await streamCallback.onMessage({
|
|
16452
|
-
taskId: context.taskId,
|
|
16453
|
-
agentName: agentNode.name,
|
|
16454
|
-
nodeId: agentNode.id,
|
|
16455
|
-
type: "text",
|
|
16456
|
-
streamId,
|
|
16457
|
-
streamDone: false,
|
|
16458
|
-
text: streamText,
|
|
16459
|
-
});
|
|
16460
|
-
break;
|
|
16461
|
-
}
|
|
16462
|
-
case "reasoning": {
|
|
16463
|
-
thinkText += chunk.textDelta || "";
|
|
16464
|
-
await streamCallback.onMessage({
|
|
16465
|
-
taskId: context.taskId,
|
|
16466
|
-
agentName: agentNode.name,
|
|
16467
|
-
nodeId: agentNode.id,
|
|
16468
|
-
type: "thinking",
|
|
16469
|
-
streamId,
|
|
16470
|
-
streamDone: false,
|
|
16471
|
-
text: thinkText,
|
|
16472
|
-
});
|
|
16473
|
-
break;
|
|
16474
|
-
}
|
|
16475
|
-
case "tool-call-delta": {
|
|
16476
|
-
if (!textStreamDone) {
|
|
16477
|
-
textStreamDone = true;
|
|
16478
|
-
await streamCallback.onMessage({
|
|
16479
|
-
taskId: context.taskId,
|
|
16480
|
-
agentName: agentNode.name,
|
|
16481
|
-
nodeId: agentNode.id,
|
|
16482
|
-
type: "text",
|
|
16483
|
-
streamId,
|
|
16484
|
-
streamDone: true,
|
|
16485
|
-
text: streamText,
|
|
16486
|
-
});
|
|
16487
|
-
}
|
|
16488
|
-
toolArgsText += chunk.argsTextDelta || "";
|
|
16489
|
-
await streamCallback.onMessage({
|
|
16490
|
-
taskId: context.taskId,
|
|
16491
|
-
agentName: agentNode.name,
|
|
16492
|
-
nodeId: agentNode.id,
|
|
16493
|
-
type: "tool_streaming",
|
|
16494
|
-
toolId: chunk.toolCallId,
|
|
16495
|
-
toolName: chunk.toolName,
|
|
16496
|
-
paramsText: toolArgsText,
|
|
16497
|
-
});
|
|
16498
|
-
break;
|
|
16499
|
-
}
|
|
16500
|
-
case "tool-call": {
|
|
16501
|
-
toolArgsText = "";
|
|
16502
|
-
let args = chunk.args ? JSON.parse(chunk.args) : {};
|
|
16503
|
-
await streamCallback.onMessage({
|
|
16504
|
-
taskId: context.taskId,
|
|
16505
|
-
agentName: agentNode.name,
|
|
16506
|
-
nodeId: agentNode.id,
|
|
16507
|
-
type: "tool_use",
|
|
16508
|
-
toolId: chunk.toolCallId,
|
|
16509
|
-
toolName: chunk.toolName,
|
|
16510
|
-
params: args,
|
|
16511
|
-
});
|
|
16512
|
-
toolParts.push({
|
|
16513
|
-
type: "tool-call",
|
|
16514
|
-
toolCallId: chunk.toolCallId,
|
|
16515
|
-
toolName: chunk.toolName,
|
|
16516
|
-
args: args,
|
|
16517
|
-
});
|
|
16518
|
-
break;
|
|
16519
|
-
}
|
|
16520
|
-
case "file": {
|
|
16521
|
-
await streamCallback.onMessage({
|
|
16522
|
-
taskId: context.taskId,
|
|
16523
|
-
agentName: agentNode.name,
|
|
16524
|
-
nodeId: agentNode.id,
|
|
16525
|
-
type: "file",
|
|
16526
|
-
mimeType: chunk.mimeType,
|
|
16527
|
-
data: chunk.data,
|
|
16528
|
-
});
|
|
16529
|
-
break;
|
|
16530
|
-
}
|
|
16531
|
-
case "error": {
|
|
16532
|
-
Log.error(`${this.name} agent error: `, chunk);
|
|
16533
|
-
await streamCallback.onMessage({
|
|
16534
|
-
taskId: context.taskId,
|
|
16535
|
-
agentName: agentNode.name,
|
|
16536
|
-
nodeId: agentNode.id,
|
|
16537
|
-
type: "error",
|
|
16538
|
-
error: chunk.error,
|
|
16539
|
-
});
|
|
16540
|
-
throw new Error("Plan Error");
|
|
16541
|
-
}
|
|
16542
|
-
case "finish": {
|
|
16543
|
-
if (!textStreamDone) {
|
|
16544
|
-
textStreamDone = true;
|
|
16545
|
-
await streamCallback.onMessage({
|
|
16546
|
-
taskId: context.taskId,
|
|
16547
|
-
agentName: agentNode.name,
|
|
16548
|
-
nodeId: agentNode.id,
|
|
16549
|
-
type: "text",
|
|
16550
|
-
streamId,
|
|
16551
|
-
streamDone: true,
|
|
16552
|
-
text: streamText,
|
|
16553
|
-
});
|
|
16554
|
-
}
|
|
16555
|
-
await streamCallback.onMessage({
|
|
16556
|
-
taskId: context.taskId,
|
|
16557
|
-
agentName: agentNode.name,
|
|
16558
|
-
nodeId: agentNode.id,
|
|
16559
|
-
type: "finish",
|
|
16560
|
-
finishReason: chunk.finishReason,
|
|
16561
|
-
usage: chunk.usage,
|
|
16562
|
-
});
|
|
16563
|
-
break;
|
|
16564
|
-
}
|
|
16565
|
-
}
|
|
16566
|
-
}
|
|
16567
|
-
}
|
|
16568
|
-
finally {
|
|
16569
|
-
reader.releaseLock();
|
|
16570
|
-
}
|
|
16571
|
-
agentChain.agentResult = streamText;
|
|
16572
|
-
return streamText
|
|
16573
|
-
? [
|
|
16574
|
-
{ type: "text", text: streamText },
|
|
16575
|
-
...toolParts,
|
|
16576
|
-
]
|
|
16577
|
-
: toolParts;
|
|
18583
|
+
handleMultiImageFileMessage(messages);
|
|
16578
18584
|
}
|
|
16579
18585
|
async callInnerTool(fun) {
|
|
16580
18586
|
let result = await fun();
|
|
@@ -16607,6 +18613,170 @@ class Agent {
|
|
|
16607
18613
|
return this.mcpClient;
|
|
16608
18614
|
}
|
|
16609
18615
|
}
|
|
18616
|
+
async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoice) {
|
|
18617
|
+
if (messages.length >= config.compressThreshold && !noCompress) {
|
|
18618
|
+
await compressAgentMessages(agentContext, rlm, messages, tools);
|
|
18619
|
+
}
|
|
18620
|
+
let context = agentContext.context;
|
|
18621
|
+
let agentChain = agentContext.agentChain;
|
|
18622
|
+
let agentNode = agentChain.agent;
|
|
18623
|
+
let streamCallback = context.config.callback || {
|
|
18624
|
+
onMessage: async () => { },
|
|
18625
|
+
};
|
|
18626
|
+
let request = {
|
|
18627
|
+
tools: tools,
|
|
18628
|
+
toolChoice,
|
|
18629
|
+
messages: messages,
|
|
18630
|
+
abortSignal: context.controller.signal,
|
|
18631
|
+
};
|
|
18632
|
+
agentChain.agentRequest = request;
|
|
18633
|
+
let result = await rlm.callStream(request);
|
|
18634
|
+
let streamText = "";
|
|
18635
|
+
let thinkText = "";
|
|
18636
|
+
let toolArgsText = "";
|
|
18637
|
+
let streamId = uuidv4();
|
|
18638
|
+
let textStreamDone = false;
|
|
18639
|
+
let toolParts = [];
|
|
18640
|
+
const reader = result.stream.getReader();
|
|
18641
|
+
try {
|
|
18642
|
+
while (true) {
|
|
18643
|
+
context.checkAborted();
|
|
18644
|
+
const { done, value } = await reader.read();
|
|
18645
|
+
if (done) {
|
|
18646
|
+
break;
|
|
18647
|
+
}
|
|
18648
|
+
let chunk = value;
|
|
18649
|
+
switch (chunk.type) {
|
|
18650
|
+
case "text-delta": {
|
|
18651
|
+
streamText += chunk.textDelta || "";
|
|
18652
|
+
await streamCallback.onMessage({
|
|
18653
|
+
taskId: context.taskId,
|
|
18654
|
+
agentName: agentNode.name,
|
|
18655
|
+
nodeId: agentNode.id,
|
|
18656
|
+
type: "text",
|
|
18657
|
+
streamId,
|
|
18658
|
+
streamDone: false,
|
|
18659
|
+
text: streamText,
|
|
18660
|
+
});
|
|
18661
|
+
break;
|
|
18662
|
+
}
|
|
18663
|
+
case "reasoning": {
|
|
18664
|
+
thinkText += chunk.textDelta || "";
|
|
18665
|
+
await streamCallback.onMessage({
|
|
18666
|
+
taskId: context.taskId,
|
|
18667
|
+
agentName: agentNode.name,
|
|
18668
|
+
nodeId: agentNode.id,
|
|
18669
|
+
type: "thinking",
|
|
18670
|
+
streamId,
|
|
18671
|
+
streamDone: false,
|
|
18672
|
+
text: thinkText,
|
|
18673
|
+
});
|
|
18674
|
+
break;
|
|
18675
|
+
}
|
|
18676
|
+
case "tool-call-delta": {
|
|
18677
|
+
if (!textStreamDone) {
|
|
18678
|
+
textStreamDone = true;
|
|
18679
|
+
await streamCallback.onMessage({
|
|
18680
|
+
taskId: context.taskId,
|
|
18681
|
+
agentName: agentNode.name,
|
|
18682
|
+
nodeId: agentNode.id,
|
|
18683
|
+
type: "text",
|
|
18684
|
+
streamId,
|
|
18685
|
+
streamDone: true,
|
|
18686
|
+
text: streamText,
|
|
18687
|
+
});
|
|
18688
|
+
}
|
|
18689
|
+
toolArgsText += chunk.argsTextDelta || "";
|
|
18690
|
+
await streamCallback.onMessage({
|
|
18691
|
+
taskId: context.taskId,
|
|
18692
|
+
agentName: agentNode.name,
|
|
18693
|
+
nodeId: agentNode.id,
|
|
18694
|
+
type: "tool_streaming",
|
|
18695
|
+
toolId: chunk.toolCallId,
|
|
18696
|
+
toolName: chunk.toolName,
|
|
18697
|
+
paramsText: toolArgsText,
|
|
18698
|
+
});
|
|
18699
|
+
break;
|
|
18700
|
+
}
|
|
18701
|
+
case "tool-call": {
|
|
18702
|
+
toolArgsText = "";
|
|
18703
|
+
let args = chunk.args ? JSON.parse(chunk.args) : {};
|
|
18704
|
+
await streamCallback.onMessage({
|
|
18705
|
+
taskId: context.taskId,
|
|
18706
|
+
agentName: agentNode.name,
|
|
18707
|
+
nodeId: agentNode.id,
|
|
18708
|
+
type: "tool_use",
|
|
18709
|
+
toolId: chunk.toolCallId,
|
|
18710
|
+
toolName: chunk.toolName,
|
|
18711
|
+
params: args,
|
|
18712
|
+
});
|
|
18713
|
+
toolParts.push({
|
|
18714
|
+
type: "tool-call",
|
|
18715
|
+
toolCallId: chunk.toolCallId,
|
|
18716
|
+
toolName: chunk.toolName,
|
|
18717
|
+
args: args,
|
|
18718
|
+
});
|
|
18719
|
+
break;
|
|
18720
|
+
}
|
|
18721
|
+
case "file": {
|
|
18722
|
+
await streamCallback.onMessage({
|
|
18723
|
+
taskId: context.taskId,
|
|
18724
|
+
agentName: agentNode.name,
|
|
18725
|
+
nodeId: agentNode.id,
|
|
18726
|
+
type: "file",
|
|
18727
|
+
mimeType: chunk.mimeType,
|
|
18728
|
+
data: chunk.data,
|
|
18729
|
+
});
|
|
18730
|
+
break;
|
|
18731
|
+
}
|
|
18732
|
+
case "error": {
|
|
18733
|
+
Log.error(`${agentNode.name} agent error: `, chunk);
|
|
18734
|
+
await streamCallback.onMessage({
|
|
18735
|
+
taskId: context.taskId,
|
|
18736
|
+
agentName: agentNode.name,
|
|
18737
|
+
nodeId: agentNode.id,
|
|
18738
|
+
type: "error",
|
|
18739
|
+
error: chunk.error,
|
|
18740
|
+
});
|
|
18741
|
+
throw new Error("Plan Error");
|
|
18742
|
+
}
|
|
18743
|
+
case "finish": {
|
|
18744
|
+
if (!textStreamDone) {
|
|
18745
|
+
textStreamDone = true;
|
|
18746
|
+
await streamCallback.onMessage({
|
|
18747
|
+
taskId: context.taskId,
|
|
18748
|
+
agentName: agentNode.name,
|
|
18749
|
+
nodeId: agentNode.id,
|
|
18750
|
+
type: "text",
|
|
18751
|
+
streamId,
|
|
18752
|
+
streamDone: true,
|
|
18753
|
+
text: streamText,
|
|
18754
|
+
});
|
|
18755
|
+
}
|
|
18756
|
+
await streamCallback.onMessage({
|
|
18757
|
+
taskId: context.taskId,
|
|
18758
|
+
agentName: agentNode.name,
|
|
18759
|
+
nodeId: agentNode.id,
|
|
18760
|
+
type: "finish",
|
|
18761
|
+
finishReason: chunk.finishReason,
|
|
18762
|
+
usage: chunk.usage,
|
|
18763
|
+
});
|
|
18764
|
+
break;
|
|
18765
|
+
}
|
|
18766
|
+
}
|
|
18767
|
+
}
|
|
18768
|
+
}
|
|
18769
|
+
finally {
|
|
18770
|
+
reader.releaseLock();
|
|
18771
|
+
}
|
|
18772
|
+
agentChain.agentResult = streamText;
|
|
18773
|
+
return streamText
|
|
18774
|
+
? [
|
|
18775
|
+
{ type: "text", text: streamText },
|
|
18776
|
+
...toolParts,
|
|
18777
|
+
]
|
|
18778
|
+
: toolParts;
|
|
18779
|
+
}
|
|
16610
18780
|
|
|
16611
18781
|
const AGENT_NAME$4 = "Chat";
|
|
16612
18782
|
class BaseChatAgent extends Agent {
|