@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.esm.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
const config = {
|
|
2
2
|
name: "Fellou",
|
|
3
3
|
platform: "mac",
|
|
4
|
-
maxReactNum:
|
|
5
|
-
maxTokens: 16000
|
|
4
|
+
maxReactNum: 200,
|
|
5
|
+
maxTokens: 16000,
|
|
6
|
+
compressThreshold: 60,
|
|
6
7
|
};
|
|
7
8
|
|
|
8
9
|
var LogLevel;
|
|
@@ -159,10 +160,10 @@ class AgentContext {
|
|
|
159
160
|
}
|
|
160
161
|
|
|
161
162
|
// src/errors/ai-sdk-error.ts
|
|
162
|
-
var marker = "vercel.ai.error";
|
|
163
|
-
var symbol = Symbol.for(marker);
|
|
164
|
-
var _a;
|
|
165
|
-
var _AISDKError = class _AISDKError extends Error {
|
|
163
|
+
var marker$1 = "vercel.ai.error";
|
|
164
|
+
var symbol$1 = Symbol.for(marker$1);
|
|
165
|
+
var _a$1;
|
|
166
|
+
var _AISDKError$1 = class _AISDKError extends Error {
|
|
166
167
|
/**
|
|
167
168
|
* Creates an AI SDK Error.
|
|
168
169
|
*
|
|
@@ -177,7 +178,7 @@ var _AISDKError = class _AISDKError extends Error {
|
|
|
177
178
|
cause
|
|
178
179
|
}) {
|
|
179
180
|
super(message);
|
|
180
|
-
this[_a] = true;
|
|
181
|
+
this[_a$1] = true;
|
|
181
182
|
this.name = name14;
|
|
182
183
|
this.cause = cause;
|
|
183
184
|
}
|
|
@@ -187,22 +188,22 @@ var _AISDKError = class _AISDKError extends Error {
|
|
|
187
188
|
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
188
189
|
*/
|
|
189
190
|
static isInstance(error) {
|
|
190
|
-
return _AISDKError.hasMarker(error, marker);
|
|
191
|
+
return _AISDKError.hasMarker(error, marker$1);
|
|
191
192
|
}
|
|
192
193
|
static hasMarker(error, marker15) {
|
|
193
194
|
const markerSymbol = Symbol.for(marker15);
|
|
194
195
|
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
195
196
|
}
|
|
196
197
|
};
|
|
197
|
-
_a = symbol;
|
|
198
|
-
var AISDKError = _AISDKError;
|
|
198
|
+
_a$1 = symbol$1;
|
|
199
|
+
var AISDKError$1 = _AISDKError$1;
|
|
199
200
|
|
|
200
201
|
// src/errors/api-call-error.ts
|
|
201
|
-
var name = "AI_APICallError";
|
|
202
|
-
var marker2 = `vercel.ai.error.${name}`;
|
|
203
|
-
var symbol2 = Symbol.for(marker2);
|
|
204
|
-
var _a2;
|
|
205
|
-
var APICallError = class extends AISDKError {
|
|
202
|
+
var name$1 = "AI_APICallError";
|
|
203
|
+
var marker2$1 = `vercel.ai.error.${name$1}`;
|
|
204
|
+
var symbol2$1 = Symbol.for(marker2$1);
|
|
205
|
+
var _a2$1;
|
|
206
|
+
var APICallError$1 = class APICallError extends AISDKError$1 {
|
|
206
207
|
constructor({
|
|
207
208
|
message,
|
|
208
209
|
url,
|
|
@@ -218,8 +219,8 @@ var APICallError = class extends AISDKError {
|
|
|
218
219
|
// server error
|
|
219
220
|
data
|
|
220
221
|
}) {
|
|
221
|
-
super({ name, message, cause });
|
|
222
|
-
this[_a2] = true;
|
|
222
|
+
super({ name: name$1, message, cause });
|
|
223
|
+
this[_a2$1] = true;
|
|
223
224
|
this.url = url;
|
|
224
225
|
this.requestBodyValues = requestBodyValues;
|
|
225
226
|
this.statusCode = statusCode;
|
|
@@ -229,30 +230,30 @@ var APICallError = class extends AISDKError {
|
|
|
229
230
|
this.data = data;
|
|
230
231
|
}
|
|
231
232
|
static isInstance(error) {
|
|
232
|
-
return AISDKError.hasMarker(error, marker2);
|
|
233
|
+
return AISDKError$1.hasMarker(error, marker2$1);
|
|
233
234
|
}
|
|
234
235
|
};
|
|
235
|
-
_a2 = symbol2;
|
|
236
|
+
_a2$1 = symbol2$1;
|
|
236
237
|
|
|
237
238
|
// src/errors/empty-response-body-error.ts
|
|
238
|
-
var name2 = "AI_EmptyResponseBodyError";
|
|
239
|
-
var marker3 = `vercel.ai.error.${name2}`;
|
|
240
|
-
var symbol3 = Symbol.for(marker3);
|
|
241
|
-
var _a3;
|
|
242
|
-
var EmptyResponseBodyError = class extends AISDKError {
|
|
239
|
+
var name2$1 = "AI_EmptyResponseBodyError";
|
|
240
|
+
var marker3$1 = `vercel.ai.error.${name2$1}`;
|
|
241
|
+
var symbol3$1 = Symbol.for(marker3$1);
|
|
242
|
+
var _a3$1;
|
|
243
|
+
var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 {
|
|
243
244
|
// used in isInstance
|
|
244
245
|
constructor({ message = "Empty response body" } = {}) {
|
|
245
|
-
super({ name: name2, message });
|
|
246
|
-
this[_a3] = true;
|
|
246
|
+
super({ name: name2$1, message });
|
|
247
|
+
this[_a3$1] = true;
|
|
247
248
|
}
|
|
248
249
|
static isInstance(error) {
|
|
249
|
-
return AISDKError.hasMarker(error, marker3);
|
|
250
|
+
return AISDKError$1.hasMarker(error, marker3$1);
|
|
250
251
|
}
|
|
251
252
|
};
|
|
252
|
-
_a3 = symbol3;
|
|
253
|
+
_a3$1 = symbol3$1;
|
|
253
254
|
|
|
254
255
|
// src/errors/get-error-message.ts
|
|
255
|
-
function getErrorMessage(error) {
|
|
256
|
+
function getErrorMessage$1(error) {
|
|
256
257
|
if (error == null) {
|
|
257
258
|
return "unknown error";
|
|
258
259
|
}
|
|
@@ -266,119 +267,119 @@ function getErrorMessage(error) {
|
|
|
266
267
|
}
|
|
267
268
|
|
|
268
269
|
// src/errors/invalid-argument-error.ts
|
|
269
|
-
var name3 = "AI_InvalidArgumentError";
|
|
270
|
-
var marker4 = `vercel.ai.error.${name3}`;
|
|
271
|
-
var symbol4 = Symbol.for(marker4);
|
|
272
|
-
var _a4;
|
|
273
|
-
var InvalidArgumentError = class extends AISDKError {
|
|
270
|
+
var name3$1 = "AI_InvalidArgumentError";
|
|
271
|
+
var marker4$1 = `vercel.ai.error.${name3$1}`;
|
|
272
|
+
var symbol4$1 = Symbol.for(marker4$1);
|
|
273
|
+
var _a4$1;
|
|
274
|
+
var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
|
|
274
275
|
constructor({
|
|
275
276
|
message,
|
|
276
277
|
cause,
|
|
277
278
|
argument
|
|
278
279
|
}) {
|
|
279
|
-
super({ name: name3, message, cause });
|
|
280
|
-
this[_a4] = true;
|
|
280
|
+
super({ name: name3$1, message, cause });
|
|
281
|
+
this[_a4$1] = true;
|
|
281
282
|
this.argument = argument;
|
|
282
283
|
}
|
|
283
284
|
static isInstance(error) {
|
|
284
|
-
return AISDKError.hasMarker(error, marker4);
|
|
285
|
+
return AISDKError$1.hasMarker(error, marker4$1);
|
|
285
286
|
}
|
|
286
287
|
};
|
|
287
|
-
_a4 = symbol4;
|
|
288
|
+
_a4$1 = symbol4$1;
|
|
288
289
|
|
|
289
290
|
// src/errors/invalid-prompt-error.ts
|
|
290
|
-
var name4 = "AI_InvalidPromptError";
|
|
291
|
-
var marker5 = `vercel.ai.error.${name4}`;
|
|
292
|
-
var symbol5 = Symbol.for(marker5);
|
|
293
|
-
var _a5;
|
|
294
|
-
var InvalidPromptError = class extends AISDKError {
|
|
291
|
+
var name4$1 = "AI_InvalidPromptError";
|
|
292
|
+
var marker5$1 = `vercel.ai.error.${name4$1}`;
|
|
293
|
+
var symbol5$1 = Symbol.for(marker5$1);
|
|
294
|
+
var _a5$1;
|
|
295
|
+
var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 {
|
|
295
296
|
constructor({
|
|
296
297
|
prompt,
|
|
297
298
|
message,
|
|
298
299
|
cause
|
|
299
300
|
}) {
|
|
300
|
-
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
301
|
-
this[_a5] = true;
|
|
301
|
+
super({ name: name4$1, message: `Invalid prompt: ${message}`, cause });
|
|
302
|
+
this[_a5$1] = true;
|
|
302
303
|
this.prompt = prompt;
|
|
303
304
|
}
|
|
304
305
|
static isInstance(error) {
|
|
305
|
-
return AISDKError.hasMarker(error, marker5);
|
|
306
|
+
return AISDKError$1.hasMarker(error, marker5$1);
|
|
306
307
|
}
|
|
307
308
|
};
|
|
308
|
-
_a5 = symbol5;
|
|
309
|
+
_a5$1 = symbol5$1;
|
|
309
310
|
|
|
310
311
|
// src/errors/invalid-response-data-error.ts
|
|
311
|
-
var name5 = "AI_InvalidResponseDataError";
|
|
312
|
-
var marker6 = `vercel.ai.error.${name5}`;
|
|
313
|
-
var symbol6 = Symbol.for(marker6);
|
|
314
|
-
var _a6;
|
|
315
|
-
var InvalidResponseDataError = class extends AISDKError {
|
|
312
|
+
var name5$1 = "AI_InvalidResponseDataError";
|
|
313
|
+
var marker6$1 = `vercel.ai.error.${name5$1}`;
|
|
314
|
+
var symbol6$1 = Symbol.for(marker6$1);
|
|
315
|
+
var _a6$1;
|
|
316
|
+
var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 {
|
|
316
317
|
constructor({
|
|
317
318
|
data,
|
|
318
319
|
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
319
320
|
}) {
|
|
320
|
-
super({ name: name5, message });
|
|
321
|
-
this[_a6] = true;
|
|
321
|
+
super({ name: name5$1, message });
|
|
322
|
+
this[_a6$1] = true;
|
|
322
323
|
this.data = data;
|
|
323
324
|
}
|
|
324
325
|
static isInstance(error) {
|
|
325
|
-
return AISDKError.hasMarker(error, marker6);
|
|
326
|
+
return AISDKError$1.hasMarker(error, marker6$1);
|
|
326
327
|
}
|
|
327
328
|
};
|
|
328
|
-
_a6 = symbol6;
|
|
329
|
+
_a6$1 = symbol6$1;
|
|
329
330
|
|
|
330
331
|
// src/errors/json-parse-error.ts
|
|
331
|
-
var name6 = "AI_JSONParseError";
|
|
332
|
-
var marker7 = `vercel.ai.error.${name6}`;
|
|
333
|
-
var symbol7 = Symbol.for(marker7);
|
|
334
|
-
var _a7;
|
|
335
|
-
var JSONParseError = class extends AISDKError {
|
|
332
|
+
var name6$1 = "AI_JSONParseError";
|
|
333
|
+
var marker7$1 = `vercel.ai.error.${name6$1}`;
|
|
334
|
+
var symbol7$1 = Symbol.for(marker7$1);
|
|
335
|
+
var _a7$1;
|
|
336
|
+
var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
|
|
336
337
|
constructor({ text, cause }) {
|
|
337
338
|
super({
|
|
338
|
-
name: name6,
|
|
339
|
+
name: name6$1,
|
|
339
340
|
message: `JSON parsing failed: Text: ${text}.
|
|
340
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
341
|
+
Error message: ${getErrorMessage$1(cause)}`,
|
|
341
342
|
cause
|
|
342
343
|
});
|
|
343
|
-
this[_a7] = true;
|
|
344
|
+
this[_a7$1] = true;
|
|
344
345
|
this.text = text;
|
|
345
346
|
}
|
|
346
347
|
static isInstance(error) {
|
|
347
|
-
return AISDKError.hasMarker(error, marker7);
|
|
348
|
+
return AISDKError$1.hasMarker(error, marker7$1);
|
|
348
349
|
}
|
|
349
350
|
};
|
|
350
|
-
_a7 = symbol7;
|
|
351
|
+
_a7$1 = symbol7$1;
|
|
351
352
|
|
|
352
353
|
// src/errors/load-api-key-error.ts
|
|
353
|
-
var name7 = "AI_LoadAPIKeyError";
|
|
354
|
-
var marker8 = `vercel.ai.error.${name7}`;
|
|
355
|
-
var symbol8 = Symbol.for(marker8);
|
|
356
|
-
var _a8;
|
|
357
|
-
var LoadAPIKeyError = class extends AISDKError {
|
|
354
|
+
var name7$1 = "AI_LoadAPIKeyError";
|
|
355
|
+
var marker8$1 = `vercel.ai.error.${name7$1}`;
|
|
356
|
+
var symbol8$1 = Symbol.for(marker8$1);
|
|
357
|
+
var _a8$1;
|
|
358
|
+
var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 {
|
|
358
359
|
// used in isInstance
|
|
359
360
|
constructor({ message }) {
|
|
360
|
-
super({ name: name7, message });
|
|
361
|
-
this[_a8] = true;
|
|
361
|
+
super({ name: name7$1, message });
|
|
362
|
+
this[_a8$1] = true;
|
|
362
363
|
}
|
|
363
364
|
static isInstance(error) {
|
|
364
|
-
return AISDKError.hasMarker(error, marker8);
|
|
365
|
+
return AISDKError$1.hasMarker(error, marker8$1);
|
|
365
366
|
}
|
|
366
367
|
};
|
|
367
|
-
_a8 = symbol8;
|
|
368
|
+
_a8$1 = symbol8$1;
|
|
368
369
|
|
|
369
370
|
// src/errors/load-setting-error.ts
|
|
370
371
|
var name8 = "AI_LoadSettingError";
|
|
371
372
|
var marker9 = `vercel.ai.error.${name8}`;
|
|
372
373
|
var symbol9 = Symbol.for(marker9);
|
|
373
374
|
var _a9;
|
|
374
|
-
var LoadSettingError = class extends AISDKError {
|
|
375
|
+
var LoadSettingError = class extends AISDKError$1 {
|
|
375
376
|
// used in isInstance
|
|
376
377
|
constructor({ message }) {
|
|
377
378
|
super({ name: name8, message });
|
|
378
379
|
this[_a9] = true;
|
|
379
380
|
}
|
|
380
381
|
static isInstance(error) {
|
|
381
|
-
return AISDKError.hasMarker(error, marker9);
|
|
382
|
+
return AISDKError$1.hasMarker(error, marker9);
|
|
382
383
|
}
|
|
383
384
|
};
|
|
384
385
|
_a9 = symbol9;
|
|
@@ -388,7 +389,7 @@ var name10 = "AI_NoSuchModelError";
|
|
|
388
389
|
var marker11 = `vercel.ai.error.${name10}`;
|
|
389
390
|
var symbol11 = Symbol.for(marker11);
|
|
390
391
|
var _a11;
|
|
391
|
-
var NoSuchModelError = class extends AISDKError {
|
|
392
|
+
var NoSuchModelError = class extends AISDKError$1 {
|
|
392
393
|
constructor({
|
|
393
394
|
errorName = name10,
|
|
394
395
|
modelId,
|
|
@@ -401,7 +402,7 @@ var NoSuchModelError = class extends AISDKError {
|
|
|
401
402
|
this.modelType = modelType;
|
|
402
403
|
}
|
|
403
404
|
static isInstance(error) {
|
|
404
|
-
return AISDKError.hasMarker(error, marker11);
|
|
405
|
+
return AISDKError$1.hasMarker(error, marker11);
|
|
405
406
|
}
|
|
406
407
|
};
|
|
407
408
|
_a11 = symbol11;
|
|
@@ -411,7 +412,7 @@ var name11 = "AI_TooManyEmbeddingValuesForCallError";
|
|
|
411
412
|
var marker12 = `vercel.ai.error.${name11}`;
|
|
412
413
|
var symbol12 = Symbol.for(marker12);
|
|
413
414
|
var _a12;
|
|
414
|
-
var TooManyEmbeddingValuesForCallError = class extends AISDKError {
|
|
415
|
+
var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
|
|
415
416
|
constructor(options) {
|
|
416
417
|
super({
|
|
417
418
|
name: name11,
|
|
@@ -424,29 +425,29 @@ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
|
|
|
424
425
|
this.values = options.values;
|
|
425
426
|
}
|
|
426
427
|
static isInstance(error) {
|
|
427
|
-
return AISDKError.hasMarker(error, marker12);
|
|
428
|
+
return AISDKError$1.hasMarker(error, marker12);
|
|
428
429
|
}
|
|
429
430
|
};
|
|
430
431
|
_a12 = symbol12;
|
|
431
432
|
|
|
432
433
|
// src/errors/type-validation-error.ts
|
|
433
|
-
var name12 = "AI_TypeValidationError";
|
|
434
|
-
var marker13 = `vercel.ai.error.${name12}`;
|
|
435
|
-
var symbol13 = Symbol.for(marker13);
|
|
436
|
-
var _a13;
|
|
437
|
-
var _TypeValidationError = class _TypeValidationError extends AISDKError {
|
|
434
|
+
var name12$1 = "AI_TypeValidationError";
|
|
435
|
+
var marker13$1 = `vercel.ai.error.${name12$1}`;
|
|
436
|
+
var symbol13$1 = Symbol.for(marker13$1);
|
|
437
|
+
var _a13$1;
|
|
438
|
+
var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 {
|
|
438
439
|
constructor({ value, cause }) {
|
|
439
440
|
super({
|
|
440
|
-
name: name12,
|
|
441
|
+
name: name12$1,
|
|
441
442
|
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
442
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
443
|
+
Error message: ${getErrorMessage$1(cause)}`,
|
|
443
444
|
cause
|
|
444
445
|
});
|
|
445
|
-
this[_a13] = true;
|
|
446
|
+
this[_a13$1] = true;
|
|
446
447
|
this.value = value;
|
|
447
448
|
}
|
|
448
449
|
static isInstance(error) {
|
|
449
|
-
return AISDKError.hasMarker(error, marker13);
|
|
450
|
+
return AISDKError$1.hasMarker(error, marker13$1);
|
|
450
451
|
}
|
|
451
452
|
/**
|
|
452
453
|
* Wraps an error into a TypeValidationError.
|
|
@@ -465,28 +466,28 @@ Error message: ${getErrorMessage(cause)}`,
|
|
|
465
466
|
return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
|
|
466
467
|
}
|
|
467
468
|
};
|
|
468
|
-
_a13 = symbol13;
|
|
469
|
-
var TypeValidationError = _TypeValidationError;
|
|
469
|
+
_a13$1 = symbol13$1;
|
|
470
|
+
var TypeValidationError$1 = _TypeValidationError$1;
|
|
470
471
|
|
|
471
472
|
// src/errors/unsupported-functionality-error.ts
|
|
472
|
-
var name13 = "AI_UnsupportedFunctionalityError";
|
|
473
|
-
var marker14 = `vercel.ai.error.${name13}`;
|
|
474
|
-
var symbol14 = Symbol.for(marker14);
|
|
475
|
-
var _a14;
|
|
476
|
-
var UnsupportedFunctionalityError = class extends AISDKError {
|
|
473
|
+
var name13$1 = "AI_UnsupportedFunctionalityError";
|
|
474
|
+
var marker14$1 = `vercel.ai.error.${name13$1}`;
|
|
475
|
+
var symbol14$1 = Symbol.for(marker14$1);
|
|
476
|
+
var _a14$1;
|
|
477
|
+
var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 {
|
|
477
478
|
constructor({
|
|
478
479
|
functionality,
|
|
479
480
|
message = `'${functionality}' functionality not supported.`
|
|
480
481
|
}) {
|
|
481
|
-
super({ name: name13, message });
|
|
482
|
-
this[_a14] = true;
|
|
482
|
+
super({ name: name13$1, message });
|
|
483
|
+
this[_a14$1] = true;
|
|
483
484
|
this.functionality = functionality;
|
|
484
485
|
}
|
|
485
486
|
static isInstance(error) {
|
|
486
|
-
return AISDKError.hasMarker(error, marker14);
|
|
487
|
+
return AISDKError$1.hasMarker(error, marker14$1);
|
|
487
488
|
}
|
|
488
489
|
};
|
|
489
|
-
_a14 = symbol14;
|
|
490
|
+
_a14$1 = symbol14$1;
|
|
490
491
|
|
|
491
492
|
let customAlphabet = (alphabet, defaultSize = 21) => {
|
|
492
493
|
return (size = defaultSize) => {
|
|
@@ -503,13 +504,13 @@ function getDefaultExportFromCjs (x) {
|
|
|
503
504
|
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
504
505
|
}
|
|
505
506
|
|
|
506
|
-
var secureJsonParse = {exports: {}};
|
|
507
|
+
var secureJsonParse$1 = {exports: {}};
|
|
507
508
|
|
|
508
|
-
var hasRequiredSecureJsonParse;
|
|
509
|
+
var hasRequiredSecureJsonParse$1;
|
|
509
510
|
|
|
510
|
-
function requireSecureJsonParse () {
|
|
511
|
-
if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
|
|
512
|
-
hasRequiredSecureJsonParse = 1;
|
|
511
|
+
function requireSecureJsonParse$1 () {
|
|
512
|
+
if (hasRequiredSecureJsonParse$1) return secureJsonParse$1.exports;
|
|
513
|
+
hasRequiredSecureJsonParse$1 = 1;
|
|
513
514
|
|
|
514
515
|
const hasBuffer = typeof Buffer !== 'undefined';
|
|
515
516
|
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
@@ -630,19 +631,19 @@ function requireSecureJsonParse () {
|
|
|
630
631
|
}
|
|
631
632
|
}
|
|
632
633
|
|
|
633
|
-
secureJsonParse.exports = parse;
|
|
634
|
-
secureJsonParse.exports.default = parse;
|
|
635
|
-
secureJsonParse.exports.parse = parse;
|
|
636
|
-
secureJsonParse.exports.safeParse = safeParse;
|
|
637
|
-
secureJsonParse.exports.scan = filter;
|
|
638
|
-
return secureJsonParse.exports;
|
|
634
|
+
secureJsonParse$1.exports = parse;
|
|
635
|
+
secureJsonParse$1.exports.default = parse;
|
|
636
|
+
secureJsonParse$1.exports.parse = parse;
|
|
637
|
+
secureJsonParse$1.exports.safeParse = safeParse;
|
|
638
|
+
secureJsonParse$1.exports.scan = filter;
|
|
639
|
+
return secureJsonParse$1.exports;
|
|
639
640
|
}
|
|
640
641
|
|
|
641
|
-
var secureJsonParseExports = requireSecureJsonParse();
|
|
642
|
-
var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
|
|
642
|
+
var secureJsonParseExports$1 = requireSecureJsonParse$1();
|
|
643
|
+
var SecureJSON$1 = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports$1);
|
|
643
644
|
|
|
644
645
|
// src/combine-headers.ts
|
|
645
|
-
function combineHeaders(...headers) {
|
|
646
|
+
function combineHeaders$1(...headers) {
|
|
646
647
|
return headers.reduce(
|
|
647
648
|
(combinedHeaders, currentHeaders) => ({
|
|
648
649
|
...combinedHeaders,
|
|
@@ -711,7 +712,7 @@ function createEventSourceParserStream() {
|
|
|
711
712
|
}
|
|
712
713
|
return new TransformStream({
|
|
713
714
|
transform(chunk, controller) {
|
|
714
|
-
const { lines, incompleteLine } = splitLines(buffer, chunk);
|
|
715
|
+
const { lines, incompleteLine } = splitLines$1(buffer, chunk);
|
|
715
716
|
buffer = incompleteLine;
|
|
716
717
|
for (let i = 0; i < lines.length; i++) {
|
|
717
718
|
parseLine(lines[i], controller);
|
|
@@ -723,7 +724,7 @@ function createEventSourceParserStream() {
|
|
|
723
724
|
}
|
|
724
725
|
});
|
|
725
726
|
}
|
|
726
|
-
function splitLines(buffer, chunk) {
|
|
727
|
+
function splitLines$1(buffer, chunk) {
|
|
727
728
|
const lines = [];
|
|
728
729
|
let currentLine = buffer;
|
|
729
730
|
for (let i = 0; i < chunk.length; ) {
|
|
@@ -745,14 +746,14 @@ function splitLines(buffer, chunk) {
|
|
|
745
746
|
}
|
|
746
747
|
|
|
747
748
|
// src/extract-response-headers.ts
|
|
748
|
-
function extractResponseHeaders(response) {
|
|
749
|
+
function extractResponseHeaders$1(response) {
|
|
749
750
|
const headers = {};
|
|
750
751
|
response.headers.forEach((value, key) => {
|
|
751
752
|
headers[key] = value;
|
|
752
753
|
});
|
|
753
754
|
return headers;
|
|
754
755
|
}
|
|
755
|
-
var createIdGenerator = ({
|
|
756
|
+
var createIdGenerator$1 = ({
|
|
756
757
|
prefix,
|
|
757
758
|
size: defaultSize = 16,
|
|
758
759
|
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
@@ -763,27 +764,27 @@ var createIdGenerator = ({
|
|
|
763
764
|
return generator;
|
|
764
765
|
}
|
|
765
766
|
if (alphabet.includes(separator)) {
|
|
766
|
-
throw new InvalidArgumentError({
|
|
767
|
+
throw new InvalidArgumentError$1({
|
|
767
768
|
argument: "separator",
|
|
768
769
|
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
769
770
|
});
|
|
770
771
|
}
|
|
771
772
|
return (size) => `${prefix}${separator}${generator(size)}`;
|
|
772
773
|
};
|
|
773
|
-
var generateId = createIdGenerator();
|
|
774
|
+
var generateId$1 = createIdGenerator$1();
|
|
774
775
|
|
|
775
776
|
// src/remove-undefined-entries.ts
|
|
776
|
-
function removeUndefinedEntries(record) {
|
|
777
|
+
function removeUndefinedEntries$1(record) {
|
|
777
778
|
return Object.fromEntries(
|
|
778
779
|
Object.entries(record).filter(([_key, value]) => value != null)
|
|
779
780
|
);
|
|
780
781
|
}
|
|
781
782
|
|
|
782
783
|
// src/is-abort-error.ts
|
|
783
|
-
function isAbortError(error) {
|
|
784
|
+
function isAbortError$1(error) {
|
|
784
785
|
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
785
786
|
}
|
|
786
|
-
function loadApiKey({
|
|
787
|
+
function loadApiKey$1({
|
|
787
788
|
apiKey,
|
|
788
789
|
environmentVariableName,
|
|
789
790
|
apiKeyParameterName = "apiKey",
|
|
@@ -793,23 +794,23 @@ function loadApiKey({
|
|
|
793
794
|
return apiKey;
|
|
794
795
|
}
|
|
795
796
|
if (apiKey != null) {
|
|
796
|
-
throw new LoadAPIKeyError({
|
|
797
|
+
throw new LoadAPIKeyError$1({
|
|
797
798
|
message: `${description} API key must be a string.`
|
|
798
799
|
});
|
|
799
800
|
}
|
|
800
801
|
if (typeof process === "undefined") {
|
|
801
|
-
throw new LoadAPIKeyError({
|
|
802
|
+
throw new LoadAPIKeyError$1({
|
|
802
803
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
|
803
804
|
});
|
|
804
805
|
}
|
|
805
806
|
apiKey = process.env[environmentVariableName];
|
|
806
807
|
if (apiKey == null) {
|
|
807
|
-
throw new LoadAPIKeyError({
|
|
808
|
+
throw new LoadAPIKeyError$1({
|
|
808
809
|
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
|
809
810
|
});
|
|
810
811
|
}
|
|
811
812
|
if (typeof apiKey !== "string") {
|
|
812
|
-
throw new LoadAPIKeyError({
|
|
813
|
+
throw new LoadAPIKeyError$1({
|
|
813
814
|
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
|
814
815
|
});
|
|
815
816
|
}
|
|
@@ -867,39 +868,39 @@ function loadSetting({
|
|
|
867
868
|
}
|
|
868
869
|
|
|
869
870
|
// src/validator.ts
|
|
870
|
-
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
871
|
-
function validator(validate) {
|
|
872
|
-
return { [validatorSymbol]: true, validate };
|
|
871
|
+
var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
|
|
872
|
+
function validator$1(validate) {
|
|
873
|
+
return { [validatorSymbol$1]: true, validate };
|
|
873
874
|
}
|
|
874
|
-
function isValidator(value) {
|
|
875
|
-
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
875
|
+
function isValidator$1(value) {
|
|
876
|
+
return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
|
|
876
877
|
}
|
|
877
|
-
function asValidator(value) {
|
|
878
|
-
return isValidator(value) ? value : zodValidator(value);
|
|
878
|
+
function asValidator$1(value) {
|
|
879
|
+
return isValidator$1(value) ? value : zodValidator$1(value);
|
|
879
880
|
}
|
|
880
|
-
function zodValidator(zodSchema) {
|
|
881
|
-
return validator((value) => {
|
|
881
|
+
function zodValidator$1(zodSchema) {
|
|
882
|
+
return validator$1((value) => {
|
|
882
883
|
const result = zodSchema.safeParse(value);
|
|
883
884
|
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
884
885
|
});
|
|
885
886
|
}
|
|
886
887
|
|
|
887
888
|
// src/validate-types.ts
|
|
888
|
-
function validateTypes({
|
|
889
|
+
function validateTypes$1({
|
|
889
890
|
value,
|
|
890
891
|
schema: inputSchema
|
|
891
892
|
}) {
|
|
892
|
-
const result = safeValidateTypes({ value, schema: inputSchema });
|
|
893
|
+
const result = safeValidateTypes$1({ value, schema: inputSchema });
|
|
893
894
|
if (!result.success) {
|
|
894
|
-
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
895
|
+
throw TypeValidationError$1.wrap({ value, cause: result.error });
|
|
895
896
|
}
|
|
896
897
|
return result.value;
|
|
897
898
|
}
|
|
898
|
-
function safeValidateTypes({
|
|
899
|
+
function safeValidateTypes$1({
|
|
899
900
|
value,
|
|
900
901
|
schema
|
|
901
902
|
}) {
|
|
902
|
-
const validator2 = asValidator(schema);
|
|
903
|
+
const validator2 = asValidator$1(schema);
|
|
903
904
|
try {
|
|
904
905
|
if (validator2.validate == null) {
|
|
905
906
|
return { success: true, value };
|
|
@@ -910,55 +911,55 @@ function safeValidateTypes({
|
|
|
910
911
|
}
|
|
911
912
|
return {
|
|
912
913
|
success: false,
|
|
913
|
-
error: TypeValidationError.wrap({ value, cause: result.error })
|
|
914
|
+
error: TypeValidationError$1.wrap({ value, cause: result.error })
|
|
914
915
|
};
|
|
915
916
|
} catch (error) {
|
|
916
917
|
return {
|
|
917
918
|
success: false,
|
|
918
|
-
error: TypeValidationError.wrap({ value, cause: error })
|
|
919
|
+
error: TypeValidationError$1.wrap({ value, cause: error })
|
|
919
920
|
};
|
|
920
921
|
}
|
|
921
922
|
}
|
|
922
923
|
|
|
923
924
|
// src/parse-json.ts
|
|
924
|
-
function parseJSON({
|
|
925
|
+
function parseJSON$1({
|
|
925
926
|
text,
|
|
926
927
|
schema
|
|
927
928
|
}) {
|
|
928
929
|
try {
|
|
929
|
-
const value = SecureJSON.parse(text);
|
|
930
|
+
const value = SecureJSON$1.parse(text);
|
|
930
931
|
if (schema == null) {
|
|
931
932
|
return value;
|
|
932
933
|
}
|
|
933
|
-
return validateTypes({ value, schema });
|
|
934
|
+
return validateTypes$1({ value, schema });
|
|
934
935
|
} catch (error) {
|
|
935
|
-
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
|
|
936
|
+
if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) {
|
|
936
937
|
throw error;
|
|
937
938
|
}
|
|
938
|
-
throw new JSONParseError({ text, cause: error });
|
|
939
|
+
throw new JSONParseError$1({ text, cause: error });
|
|
939
940
|
}
|
|
940
941
|
}
|
|
941
|
-
function safeParseJSON({
|
|
942
|
+
function safeParseJSON$1({
|
|
942
943
|
text,
|
|
943
944
|
schema
|
|
944
945
|
}) {
|
|
945
946
|
try {
|
|
946
|
-
const value = SecureJSON.parse(text);
|
|
947
|
+
const value = SecureJSON$1.parse(text);
|
|
947
948
|
if (schema == null) {
|
|
948
949
|
return { success: true, value, rawValue: value };
|
|
949
950
|
}
|
|
950
|
-
const validationResult = safeValidateTypes({ value, schema });
|
|
951
|
+
const validationResult = safeValidateTypes$1({ value, schema });
|
|
951
952
|
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
|
|
952
953
|
} catch (error) {
|
|
953
954
|
return {
|
|
954
955
|
success: false,
|
|
955
|
-
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
|
|
956
|
+
error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
|
|
956
957
|
};
|
|
957
958
|
}
|
|
958
959
|
}
|
|
959
|
-
function isParsableJson(input) {
|
|
960
|
+
function isParsableJson$1(input) {
|
|
960
961
|
try {
|
|
961
|
-
SecureJSON.parse(input);
|
|
962
|
+
SecureJSON$1.parse(input);
|
|
962
963
|
return true;
|
|
963
964
|
} catch (e) {
|
|
964
965
|
return false;
|
|
@@ -972,12 +973,12 @@ function parseProviderOptions({
|
|
|
972
973
|
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
|
|
973
974
|
return void 0;
|
|
974
975
|
}
|
|
975
|
-
const parsedProviderOptions = safeValidateTypes({
|
|
976
|
+
const parsedProviderOptions = safeValidateTypes$1({
|
|
976
977
|
value: providerOptions[provider],
|
|
977
978
|
schema
|
|
978
979
|
});
|
|
979
980
|
if (!parsedProviderOptions.success) {
|
|
980
|
-
throw new InvalidArgumentError({
|
|
981
|
+
throw new InvalidArgumentError$1({
|
|
981
982
|
argument: "providerOptions",
|
|
982
983
|
message: `invalid ${provider} provider options`,
|
|
983
984
|
cause: parsedProviderOptions.error
|
|
@@ -985,8 +986,8 @@ function parseProviderOptions({
|
|
|
985
986
|
}
|
|
986
987
|
return parsedProviderOptions.value;
|
|
987
988
|
}
|
|
988
|
-
var getOriginalFetch2 = () => globalThis.fetch;
|
|
989
|
-
var postJsonToApi = async ({
|
|
989
|
+
var getOriginalFetch2$1 = () => globalThis.fetch;
|
|
990
|
+
var postJsonToApi$1 = async ({
|
|
990
991
|
url,
|
|
991
992
|
headers,
|
|
992
993
|
body,
|
|
@@ -994,7 +995,7 @@ var postJsonToApi = async ({
|
|
|
994
995
|
successfulResponseHandler,
|
|
995
996
|
abortSignal,
|
|
996
997
|
fetch
|
|
997
|
-
}) => postToApi({
|
|
998
|
+
}) => postToApi$1({
|
|
998
999
|
url,
|
|
999
1000
|
headers: {
|
|
1000
1001
|
"Content-Type": "application/json",
|
|
@@ -1017,7 +1018,7 @@ var postFormDataToApi = async ({
|
|
|
1017
1018
|
successfulResponseHandler,
|
|
1018
1019
|
abortSignal,
|
|
1019
1020
|
fetch
|
|
1020
|
-
}) => postToApi({
|
|
1021
|
+
}) => postToApi$1({
|
|
1021
1022
|
url,
|
|
1022
1023
|
headers,
|
|
1023
1024
|
body: {
|
|
@@ -1029,23 +1030,23 @@ var postFormDataToApi = async ({
|
|
|
1029
1030
|
abortSignal,
|
|
1030
1031
|
fetch
|
|
1031
1032
|
});
|
|
1032
|
-
var postToApi = async ({
|
|
1033
|
+
var postToApi$1 = async ({
|
|
1033
1034
|
url,
|
|
1034
1035
|
headers = {},
|
|
1035
1036
|
body,
|
|
1036
1037
|
successfulResponseHandler,
|
|
1037
1038
|
failedResponseHandler,
|
|
1038
1039
|
abortSignal,
|
|
1039
|
-
fetch = getOriginalFetch2()
|
|
1040
|
+
fetch = getOriginalFetch2$1()
|
|
1040
1041
|
}) => {
|
|
1041
1042
|
try {
|
|
1042
1043
|
const response = await fetch(url, {
|
|
1043
1044
|
method: "POST",
|
|
1044
|
-
headers: removeUndefinedEntries(headers),
|
|
1045
|
+
headers: removeUndefinedEntries$1(headers),
|
|
1045
1046
|
body: body.content,
|
|
1046
1047
|
signal: abortSignal
|
|
1047
1048
|
});
|
|
1048
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1049
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1049
1050
|
if (!response.ok) {
|
|
1050
1051
|
let errorInformation;
|
|
1051
1052
|
try {
|
|
@@ -1055,10 +1056,10 @@ var postToApi = async ({
|
|
|
1055
1056
|
requestBodyValues: body.values
|
|
1056
1057
|
});
|
|
1057
1058
|
} catch (error) {
|
|
1058
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
1059
|
+
if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
|
|
1059
1060
|
throw error;
|
|
1060
1061
|
}
|
|
1061
|
-
throw new APICallError({
|
|
1062
|
+
throw new APICallError$1({
|
|
1062
1063
|
message: "Failed to process error response",
|
|
1063
1064
|
cause: error,
|
|
1064
1065
|
statusCode: response.status,
|
|
@@ -1077,11 +1078,11 @@ var postToApi = async ({
|
|
|
1077
1078
|
});
|
|
1078
1079
|
} catch (error) {
|
|
1079
1080
|
if (error instanceof Error) {
|
|
1080
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
1081
|
+
if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
|
|
1081
1082
|
throw error;
|
|
1082
1083
|
}
|
|
1083
1084
|
}
|
|
1084
|
-
throw new APICallError({
|
|
1085
|
+
throw new APICallError$1({
|
|
1085
1086
|
message: "Failed to process successful response",
|
|
1086
1087
|
cause: error,
|
|
1087
1088
|
statusCode: response.status,
|
|
@@ -1091,13 +1092,13 @@ var postToApi = async ({
|
|
|
1091
1092
|
});
|
|
1092
1093
|
}
|
|
1093
1094
|
} catch (error) {
|
|
1094
|
-
if (isAbortError(error)) {
|
|
1095
|
+
if (isAbortError$1(error)) {
|
|
1095
1096
|
throw error;
|
|
1096
1097
|
}
|
|
1097
1098
|
if (error instanceof TypeError && error.message === "fetch failed") {
|
|
1098
1099
|
const cause = error.cause;
|
|
1099
1100
|
if (cause != null) {
|
|
1100
|
-
throw new APICallError({
|
|
1101
|
+
throw new APICallError$1({
|
|
1101
1102
|
message: `Cannot connect to API: ${cause.message}`,
|
|
1102
1103
|
cause,
|
|
1103
1104
|
url,
|
|
@@ -1118,17 +1119,17 @@ async function resolve(value) {
|
|
|
1118
1119
|
}
|
|
1119
1120
|
return Promise.resolve(value);
|
|
1120
1121
|
}
|
|
1121
|
-
var createJsonErrorResponseHandler = ({
|
|
1122
|
+
var createJsonErrorResponseHandler$1 = ({
|
|
1122
1123
|
errorSchema,
|
|
1123
1124
|
errorToMessage,
|
|
1124
1125
|
isRetryable
|
|
1125
1126
|
}) => async ({ response, url, requestBodyValues }) => {
|
|
1126
1127
|
const responseBody = await response.text();
|
|
1127
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1128
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1128
1129
|
if (responseBody.trim() === "") {
|
|
1129
1130
|
return {
|
|
1130
1131
|
responseHeaders,
|
|
1131
|
-
value: new APICallError({
|
|
1132
|
+
value: new APICallError$1({
|
|
1132
1133
|
message: response.statusText,
|
|
1133
1134
|
url,
|
|
1134
1135
|
requestBodyValues,
|
|
@@ -1140,13 +1141,13 @@ var createJsonErrorResponseHandler = ({
|
|
|
1140
1141
|
};
|
|
1141
1142
|
}
|
|
1142
1143
|
try {
|
|
1143
|
-
const parsedError = parseJSON({
|
|
1144
|
+
const parsedError = parseJSON$1({
|
|
1144
1145
|
text: responseBody,
|
|
1145
1146
|
schema: errorSchema
|
|
1146
1147
|
});
|
|
1147
1148
|
return {
|
|
1148
1149
|
responseHeaders,
|
|
1149
|
-
value: new APICallError({
|
|
1150
|
+
value: new APICallError$1({
|
|
1150
1151
|
message: errorToMessage(parsedError),
|
|
1151
1152
|
url,
|
|
1152
1153
|
requestBodyValues,
|
|
@@ -1160,7 +1161,7 @@ var createJsonErrorResponseHandler = ({
|
|
|
1160
1161
|
} catch (parseError) {
|
|
1161
1162
|
return {
|
|
1162
1163
|
responseHeaders,
|
|
1163
|
-
value: new APICallError({
|
|
1164
|
+
value: new APICallError$1({
|
|
1164
1165
|
message: response.statusText,
|
|
1165
1166
|
url,
|
|
1166
1167
|
requestBodyValues,
|
|
@@ -1172,10 +1173,10 @@ var createJsonErrorResponseHandler = ({
|
|
|
1172
1173
|
};
|
|
1173
1174
|
}
|
|
1174
1175
|
};
|
|
1175
|
-
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
1176
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1176
|
+
var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
|
|
1177
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1177
1178
|
if (response.body == null) {
|
|
1178
|
-
throw new EmptyResponseBodyError({});
|
|
1179
|
+
throw new EmptyResponseBodyError$1({});
|
|
1179
1180
|
}
|
|
1180
1181
|
return {
|
|
1181
1182
|
responseHeaders,
|
|
@@ -1186,7 +1187,7 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
|
|
|
1186
1187
|
return;
|
|
1187
1188
|
}
|
|
1188
1189
|
controller.enqueue(
|
|
1189
|
-
safeParseJSON({
|
|
1190
|
+
safeParseJSON$1({
|
|
1190
1191
|
text: data,
|
|
1191
1192
|
schema: chunkSchema
|
|
1192
1193
|
})
|
|
@@ -1196,15 +1197,15 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
|
|
|
1196
1197
|
)
|
|
1197
1198
|
};
|
|
1198
1199
|
};
|
|
1199
|
-
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
1200
|
+
var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
1200
1201
|
const responseBody = await response.text();
|
|
1201
|
-
const parsedResult = safeParseJSON({
|
|
1202
|
+
const parsedResult = safeParseJSON$1({
|
|
1202
1203
|
text: responseBody,
|
|
1203
1204
|
schema: responseSchema
|
|
1204
1205
|
});
|
|
1205
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1206
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1206
1207
|
if (!parsedResult.success) {
|
|
1207
|
-
throw new APICallError({
|
|
1208
|
+
throw new APICallError$1({
|
|
1208
1209
|
message: "Invalid JSON response",
|
|
1209
1210
|
cause: parsedResult.error,
|
|
1210
1211
|
statusCode: response.status,
|
|
@@ -1221,9 +1222,9 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
|
|
|
1221
1222
|
};
|
|
1222
1223
|
};
|
|
1223
1224
|
var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
|
|
1224
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
1225
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
1225
1226
|
if (!response.body) {
|
|
1226
|
-
throw new APICallError({
|
|
1227
|
+
throw new APICallError$1({
|
|
1227
1228
|
message: "Response body is empty",
|
|
1228
1229
|
url,
|
|
1229
1230
|
requestBodyValues,
|
|
@@ -1239,7 +1240,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
|
|
|
1239
1240
|
value: new Uint8Array(buffer)
|
|
1240
1241
|
};
|
|
1241
1242
|
} catch (error) {
|
|
1242
|
-
throw new APICallError({
|
|
1243
|
+
throw new APICallError$1({
|
|
1243
1244
|
message: "Failed to read response as array buffer",
|
|
1244
1245
|
url,
|
|
1245
1246
|
requestBodyValues,
|
|
@@ -1252,22 +1253,22 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
|
|
|
1252
1253
|
};
|
|
1253
1254
|
|
|
1254
1255
|
// src/uint8-utils.ts
|
|
1255
|
-
var { btoa, atob: atob$1 } = globalThis;
|
|
1256
|
+
var { btoa: btoa$1, atob: atob$1 } = globalThis;
|
|
1256
1257
|
function convertBase64ToUint8Array(base64String) {
|
|
1257
1258
|
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
|
|
1258
1259
|
const latin1string = atob$1(base64Url);
|
|
1259
1260
|
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
|
|
1260
1261
|
}
|
|
1261
|
-
function convertUint8ArrayToBase64(array) {
|
|
1262
|
+
function convertUint8ArrayToBase64$1(array) {
|
|
1262
1263
|
let latin1string = "";
|
|
1263
1264
|
for (let i = 0; i < array.length; i++) {
|
|
1264
1265
|
latin1string += String.fromCodePoint(array[i]);
|
|
1265
1266
|
}
|
|
1266
|
-
return btoa(latin1string);
|
|
1267
|
+
return btoa$1(latin1string);
|
|
1267
1268
|
}
|
|
1268
1269
|
|
|
1269
1270
|
// src/without-trailing-slash.ts
|
|
1270
|
-
function withoutTrailingSlash(url) {
|
|
1271
|
+
function withoutTrailingSlash$1(url) {
|
|
1271
1272
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
1272
1273
|
}
|
|
1273
1274
|
|
|
@@ -5725,7 +5726,7 @@ function convertToOpenAIChatMessages({
|
|
|
5725
5726
|
return {
|
|
5726
5727
|
type: "image_url",
|
|
5727
5728
|
image_url: {
|
|
5728
|
-
url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
|
|
5729
|
+
url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
|
|
5729
5730
|
// OpenAI specific extension: image detail
|
|
5730
5731
|
detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
|
|
5731
5732
|
}
|
|
@@ -5733,7 +5734,7 @@ function convertToOpenAIChatMessages({
|
|
|
5733
5734
|
}
|
|
5734
5735
|
case "file": {
|
|
5735
5736
|
if (part.data instanceof URL) {
|
|
5736
|
-
throw new UnsupportedFunctionalityError({
|
|
5737
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5737
5738
|
functionality: "'File content parts with URL data' functionality not supported."
|
|
5738
5739
|
});
|
|
5739
5740
|
}
|
|
@@ -5761,7 +5762,7 @@ function convertToOpenAIChatMessages({
|
|
|
5761
5762
|
};
|
|
5762
5763
|
}
|
|
5763
5764
|
default: {
|
|
5764
|
-
throw new UnsupportedFunctionalityError({
|
|
5765
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5765
5766
|
functionality: `File content part type ${part.mimeType} in user messages`
|
|
5766
5767
|
});
|
|
5767
5768
|
}
|
|
@@ -5796,7 +5797,7 @@ function convertToOpenAIChatMessages({
|
|
|
5796
5797
|
}
|
|
5797
5798
|
if (useLegacyFunctionCalling) {
|
|
5798
5799
|
if (toolCalls.length > 1) {
|
|
5799
|
-
throw new UnsupportedFunctionalityError({
|
|
5800
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5800
5801
|
functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
|
|
5801
5802
|
});
|
|
5802
5803
|
}
|
|
@@ -5881,7 +5882,7 @@ var openaiErrorDataSchema = z.object({
|
|
|
5881
5882
|
code: z.union([z.string(), z.number()]).nullish()
|
|
5882
5883
|
})
|
|
5883
5884
|
});
|
|
5884
|
-
var openaiFailedResponseHandler = createJsonErrorResponseHandler({
|
|
5885
|
+
var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
5885
5886
|
errorSchema: openaiErrorDataSchema,
|
|
5886
5887
|
errorToMessage: (data) => data.error.message
|
|
5887
5888
|
});
|
|
@@ -5941,7 +5942,7 @@ function prepareTools$3({
|
|
|
5941
5942
|
toolWarnings
|
|
5942
5943
|
};
|
|
5943
5944
|
case "required":
|
|
5944
|
-
throw new UnsupportedFunctionalityError({
|
|
5945
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5945
5946
|
functionality: "useLegacyFunctionCalling and toolChoice: required"
|
|
5946
5947
|
});
|
|
5947
5948
|
default:
|
|
@@ -5990,7 +5991,7 @@ function prepareTools$3({
|
|
|
5990
5991
|
};
|
|
5991
5992
|
default: {
|
|
5992
5993
|
const _exhaustiveCheck = type;
|
|
5993
|
-
throw new UnsupportedFunctionalityError({
|
|
5994
|
+
throw new UnsupportedFunctionalityError$1({
|
|
5994
5995
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
5995
5996
|
});
|
|
5996
5997
|
}
|
|
@@ -6053,12 +6054,12 @@ var OpenAIChatLanguageModel = class {
|
|
|
6053
6054
|
}
|
|
6054
6055
|
const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
|
|
6055
6056
|
if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
|
|
6056
|
-
throw new UnsupportedFunctionalityError({
|
|
6057
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6057
6058
|
functionality: "useLegacyFunctionCalling with parallelToolCalls"
|
|
6058
6059
|
});
|
|
6059
6060
|
}
|
|
6060
6061
|
if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
|
|
6061
|
-
throw new UnsupportedFunctionalityError({
|
|
6062
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6062
6063
|
functionality: "structuredOutputs with useLegacyFunctionCalling"
|
|
6063
6064
|
});
|
|
6064
6065
|
}
|
|
@@ -6259,15 +6260,15 @@ var OpenAIChatLanguageModel = class {
|
|
|
6259
6260
|
responseHeaders,
|
|
6260
6261
|
value: response,
|
|
6261
6262
|
rawValue: rawResponse
|
|
6262
|
-
} = await postJsonToApi({
|
|
6263
|
+
} = await postJsonToApi$1({
|
|
6263
6264
|
url: this.config.url({
|
|
6264
6265
|
path: "/chat/completions",
|
|
6265
6266
|
modelId: this.modelId
|
|
6266
6267
|
}),
|
|
6267
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6268
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6268
6269
|
body,
|
|
6269
6270
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6270
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
6271
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
6271
6272
|
openaiChatResponseSchema
|
|
6272
6273
|
),
|
|
6273
6274
|
abortSignal: options.abortSignal,
|
|
@@ -6295,7 +6296,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6295
6296
|
toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
|
|
6296
6297
|
{
|
|
6297
6298
|
toolCallType: "function",
|
|
6298
|
-
toolCallId: generateId(),
|
|
6299
|
+
toolCallId: generateId$1(),
|
|
6299
6300
|
toolName: choice.message.function_call.name,
|
|
6300
6301
|
args: choice.message.function_call.arguments
|
|
6301
6302
|
}
|
|
@@ -6303,7 +6304,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6303
6304
|
var _a2;
|
|
6304
6305
|
return {
|
|
6305
6306
|
toolCallType: "function",
|
|
6306
|
-
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
6307
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId$1(),
|
|
6307
6308
|
toolName: toolCall.function.name,
|
|
6308
6309
|
args: toolCall.function.arguments
|
|
6309
6310
|
};
|
|
@@ -6373,15 +6374,15 @@ var OpenAIChatLanguageModel = class {
|
|
|
6373
6374
|
// only include stream_options when in strict compatibility mode:
|
|
6374
6375
|
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
6375
6376
|
};
|
|
6376
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
6377
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
6377
6378
|
url: this.config.url({
|
|
6378
6379
|
path: "/chat/completions",
|
|
6379
6380
|
modelId: this.modelId
|
|
6380
6381
|
}),
|
|
6381
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6382
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6382
6383
|
body,
|
|
6383
6384
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6384
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
6385
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
6385
6386
|
openaiChatChunkSchema
|
|
6386
6387
|
),
|
|
6387
6388
|
abortSignal: options.abortSignal,
|
|
@@ -6469,7 +6470,7 @@ var OpenAIChatLanguageModel = class {
|
|
|
6469
6470
|
const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
|
|
6470
6471
|
{
|
|
6471
6472
|
type: "function",
|
|
6472
|
-
id: generateId(),
|
|
6473
|
+
id: generateId$1(),
|
|
6473
6474
|
function: delta.function_call,
|
|
6474
6475
|
index: 0
|
|
6475
6476
|
}
|
|
@@ -6479,19 +6480,19 @@ var OpenAIChatLanguageModel = class {
|
|
|
6479
6480
|
const index = toolCallDelta.index;
|
|
6480
6481
|
if (toolCalls[index] == null) {
|
|
6481
6482
|
if (toolCallDelta.type !== "function") {
|
|
6482
|
-
throw new InvalidResponseDataError({
|
|
6483
|
+
throw new InvalidResponseDataError$1({
|
|
6483
6484
|
data: toolCallDelta,
|
|
6484
6485
|
message: `Expected 'function' type.`
|
|
6485
6486
|
});
|
|
6486
6487
|
}
|
|
6487
6488
|
if (toolCallDelta.id == null) {
|
|
6488
|
-
throw new InvalidResponseDataError({
|
|
6489
|
+
throw new InvalidResponseDataError$1({
|
|
6489
6490
|
data: toolCallDelta,
|
|
6490
6491
|
message: `Expected 'id' to be a string.`
|
|
6491
6492
|
});
|
|
6492
6493
|
}
|
|
6493
6494
|
if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
|
|
6494
|
-
throw new InvalidResponseDataError({
|
|
6495
|
+
throw new InvalidResponseDataError$1({
|
|
6495
6496
|
data: toolCallDelta,
|
|
6496
6497
|
message: `Expected 'function.name' to be a string.`
|
|
6497
6498
|
});
|
|
@@ -6516,11 +6517,11 @@ var OpenAIChatLanguageModel = class {
|
|
|
6516
6517
|
argsTextDelta: toolCall2.function.arguments
|
|
6517
6518
|
});
|
|
6518
6519
|
}
|
|
6519
|
-
if (isParsableJson(toolCall2.function.arguments)) {
|
|
6520
|
+
if (isParsableJson$1(toolCall2.function.arguments)) {
|
|
6520
6521
|
controller.enqueue({
|
|
6521
6522
|
type: "tool-call",
|
|
6522
6523
|
toolCallType: "function",
|
|
6523
|
-
toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
|
|
6524
|
+
toolCallId: (_e = toolCall2.id) != null ? _e : generateId$1(),
|
|
6524
6525
|
toolName: toolCall2.function.name,
|
|
6525
6526
|
args: toolCall2.function.arguments
|
|
6526
6527
|
});
|
|
@@ -6543,11 +6544,11 @@ var OpenAIChatLanguageModel = class {
|
|
|
6543
6544
|
toolName: toolCall.function.name,
|
|
6544
6545
|
argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
|
|
6545
6546
|
});
|
|
6546
|
-
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
|
|
6547
|
+
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson$1(toolCall.function.arguments)) {
|
|
6547
6548
|
controller.enqueue({
|
|
6548
6549
|
type: "tool-call",
|
|
6549
6550
|
toolCallType: "function",
|
|
6550
|
-
toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
|
|
6551
|
+
toolCallId: (_l = toolCall.id) != null ? _l : generateId$1(),
|
|
6551
6552
|
toolName: toolCall.function.name,
|
|
6552
6553
|
args: toolCall.function.arguments
|
|
6553
6554
|
});
|
|
@@ -6734,7 +6735,7 @@ function convertToOpenAICompletionPrompt({
|
|
|
6734
6735
|
for (const { role, content } of prompt) {
|
|
6735
6736
|
switch (role) {
|
|
6736
6737
|
case "system": {
|
|
6737
|
-
throw new InvalidPromptError({
|
|
6738
|
+
throw new InvalidPromptError$1({
|
|
6738
6739
|
message: "Unexpected system message in prompt: ${content}",
|
|
6739
6740
|
prompt
|
|
6740
6741
|
});
|
|
@@ -6746,7 +6747,7 @@ function convertToOpenAICompletionPrompt({
|
|
|
6746
6747
|
return part.text;
|
|
6747
6748
|
}
|
|
6748
6749
|
case "image": {
|
|
6749
|
-
throw new UnsupportedFunctionalityError({
|
|
6750
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6750
6751
|
functionality: "images"
|
|
6751
6752
|
});
|
|
6752
6753
|
}
|
|
@@ -6765,7 +6766,7 @@ ${userMessage}
|
|
|
6765
6766
|
return part.text;
|
|
6766
6767
|
}
|
|
6767
6768
|
case "tool-call": {
|
|
6768
|
-
throw new UnsupportedFunctionalityError({
|
|
6769
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6769
6770
|
functionality: "tool-call messages"
|
|
6770
6771
|
});
|
|
6771
6772
|
}
|
|
@@ -6778,7 +6779,7 @@ ${assistantMessage}
|
|
|
6778
6779
|
break;
|
|
6779
6780
|
}
|
|
6780
6781
|
case "tool": {
|
|
6781
|
-
throw new UnsupportedFunctionalityError({
|
|
6782
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6782
6783
|
functionality: "tool messages"
|
|
6783
6784
|
});
|
|
6784
6785
|
}
|
|
@@ -6879,24 +6880,24 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6879
6880
|
switch (type) {
|
|
6880
6881
|
case "regular": {
|
|
6881
6882
|
if ((_a = mode.tools) == null ? void 0 : _a.length) {
|
|
6882
|
-
throw new UnsupportedFunctionalityError({
|
|
6883
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6883
6884
|
functionality: "tools"
|
|
6884
6885
|
});
|
|
6885
6886
|
}
|
|
6886
6887
|
if (mode.toolChoice) {
|
|
6887
|
-
throw new UnsupportedFunctionalityError({
|
|
6888
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6888
6889
|
functionality: "toolChoice"
|
|
6889
6890
|
});
|
|
6890
6891
|
}
|
|
6891
6892
|
return { args: baseArgs, warnings };
|
|
6892
6893
|
}
|
|
6893
6894
|
case "object-json": {
|
|
6894
|
-
throw new UnsupportedFunctionalityError({
|
|
6895
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6895
6896
|
functionality: "object-json mode"
|
|
6896
6897
|
});
|
|
6897
6898
|
}
|
|
6898
6899
|
case "object-tool": {
|
|
6899
|
-
throw new UnsupportedFunctionalityError({
|
|
6900
|
+
throw new UnsupportedFunctionalityError$1({
|
|
6900
6901
|
functionality: "object-tool mode"
|
|
6901
6902
|
});
|
|
6902
6903
|
}
|
|
@@ -6912,15 +6913,15 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6912
6913
|
responseHeaders,
|
|
6913
6914
|
value: response,
|
|
6914
6915
|
rawValue: rawResponse
|
|
6915
|
-
} = await postJsonToApi({
|
|
6916
|
+
} = await postJsonToApi$1({
|
|
6916
6917
|
url: this.config.url({
|
|
6917
6918
|
path: "/completions",
|
|
6918
6919
|
modelId: this.modelId
|
|
6919
6920
|
}),
|
|
6920
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6921
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6921
6922
|
body: args,
|
|
6922
6923
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6923
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
6924
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
6924
6925
|
openaiCompletionResponseSchema
|
|
6925
6926
|
),
|
|
6926
6927
|
abortSignal: options.abortSignal,
|
|
@@ -6951,15 +6952,15 @@ var OpenAICompletionLanguageModel = class {
|
|
|
6951
6952
|
// only include stream_options when in strict compatibility mode:
|
|
6952
6953
|
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
6953
6954
|
};
|
|
6954
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
6955
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
6955
6956
|
url: this.config.url({
|
|
6956
6957
|
path: "/completions",
|
|
6957
6958
|
modelId: this.modelId
|
|
6958
6959
|
}),
|
|
6959
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
6960
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
6960
6961
|
body,
|
|
6961
6962
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
6962
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
6963
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
6963
6964
|
openaiCompletionChunkSchema
|
|
6964
6965
|
),
|
|
6965
6966
|
abortSignal: options.abortSignal,
|
|
@@ -7111,12 +7112,12 @@ var OpenAIEmbeddingModel = class {
|
|
|
7111
7112
|
values
|
|
7112
7113
|
});
|
|
7113
7114
|
}
|
|
7114
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
7115
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
7115
7116
|
url: this.config.url({
|
|
7116
7117
|
path: "/embeddings",
|
|
7117
7118
|
modelId: this.modelId
|
|
7118
7119
|
}),
|
|
7119
|
-
headers: combineHeaders(this.config.headers(), headers),
|
|
7120
|
+
headers: combineHeaders$1(this.config.headers(), headers),
|
|
7120
7121
|
body: {
|
|
7121
7122
|
model: this.modelId,
|
|
7122
7123
|
input: values,
|
|
@@ -7125,7 +7126,7 @@ var OpenAIEmbeddingModel = class {
|
|
|
7125
7126
|
user: this.settings.user
|
|
7126
7127
|
},
|
|
7127
7128
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7128
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7129
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7129
7130
|
openaiTextEmbeddingResponseSchema
|
|
7130
7131
|
),
|
|
7131
7132
|
abortSignal,
|
|
@@ -7189,12 +7190,12 @@ var OpenAIImageModel = class {
|
|
|
7189
7190
|
warnings.push({ type: "unsupported-setting", setting: "seed" });
|
|
7190
7191
|
}
|
|
7191
7192
|
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
|
|
7192
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
7193
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
7193
7194
|
url: this.config.url({
|
|
7194
7195
|
path: "/images/generations",
|
|
7195
7196
|
modelId: this.modelId
|
|
7196
7197
|
}),
|
|
7197
|
-
headers: combineHeaders(this.config.headers(), headers),
|
|
7198
|
+
headers: combineHeaders$1(this.config.headers(), headers),
|
|
7198
7199
|
body: {
|
|
7199
7200
|
model: this.modelId,
|
|
7200
7201
|
prompt,
|
|
@@ -7204,7 +7205,7 @@ var OpenAIImageModel = class {
|
|
|
7204
7205
|
...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
|
|
7205
7206
|
},
|
|
7206
7207
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7207
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7208
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7208
7209
|
openaiImageResponseSchema
|
|
7209
7210
|
),
|
|
7210
7211
|
abortSignal,
|
|
@@ -7348,10 +7349,10 @@ var OpenAITranscriptionModel = class {
|
|
|
7348
7349
|
path: "/audio/transcriptions",
|
|
7349
7350
|
modelId: this.modelId
|
|
7350
7351
|
}),
|
|
7351
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7352
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7352
7353
|
formData,
|
|
7353
7354
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7354
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7355
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7355
7356
|
openaiTranscriptionResponseSchema
|
|
7356
7357
|
),
|
|
7357
7358
|
abortSignal: options.abortSignal,
|
|
@@ -7435,14 +7436,14 @@ function convertToOpenAIResponsesMessages({
|
|
|
7435
7436
|
case "image": {
|
|
7436
7437
|
return {
|
|
7437
7438
|
type: "input_image",
|
|
7438
|
-
image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
|
|
7439
|
+
image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
|
|
7439
7440
|
// OpenAI specific extension: image detail
|
|
7440
7441
|
detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
|
|
7441
7442
|
};
|
|
7442
7443
|
}
|
|
7443
7444
|
case "file": {
|
|
7444
7445
|
if (part.data instanceof URL) {
|
|
7445
|
-
throw new UnsupportedFunctionalityError({
|
|
7446
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7446
7447
|
functionality: "File URLs in user messages"
|
|
7447
7448
|
});
|
|
7448
7449
|
}
|
|
@@ -7455,7 +7456,7 @@ function convertToOpenAIResponsesMessages({
|
|
|
7455
7456
|
};
|
|
7456
7457
|
}
|
|
7457
7458
|
default: {
|
|
7458
|
-
throw new UnsupportedFunctionalityError({
|
|
7459
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7459
7460
|
functionality: "Only PDF files are supported in user messages"
|
|
7460
7461
|
});
|
|
7461
7462
|
}
|
|
@@ -7597,7 +7598,7 @@ function prepareResponsesTools({
|
|
|
7597
7598
|
}
|
|
7598
7599
|
default: {
|
|
7599
7600
|
const _exhaustiveCheck = type;
|
|
7600
|
-
throw new UnsupportedFunctionalityError({
|
|
7601
|
+
throw new UnsupportedFunctionalityError$1({
|
|
7601
7602
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
7602
7603
|
});
|
|
7603
7604
|
}
|
|
@@ -7796,15 +7797,15 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7796
7797
|
responseHeaders,
|
|
7797
7798
|
value: response,
|
|
7798
7799
|
rawValue: rawResponse
|
|
7799
|
-
} = await postJsonToApi({
|
|
7800
|
+
} = await postJsonToApi$1({
|
|
7800
7801
|
url: this.config.url({
|
|
7801
7802
|
path: "/responses",
|
|
7802
7803
|
modelId: this.modelId
|
|
7803
7804
|
}),
|
|
7804
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7805
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7805
7806
|
body,
|
|
7806
7807
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7807
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
7808
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
7808
7809
|
z.object({
|
|
7809
7810
|
id: z.string(),
|
|
7810
7811
|
created_at: z.number(),
|
|
@@ -7875,7 +7876,7 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7875
7876
|
var _a2, _b2, _c2;
|
|
7876
7877
|
return {
|
|
7877
7878
|
sourceType: "url",
|
|
7878
|
-
id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
|
|
7879
|
+
id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId$1(),
|
|
7879
7880
|
url: annotation.url,
|
|
7880
7881
|
title: annotation.title
|
|
7881
7882
|
};
|
|
@@ -7922,18 +7923,18 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
7922
7923
|
}
|
|
7923
7924
|
async doStream(options) {
|
|
7924
7925
|
const { args: body, warnings } = this.getArgs(options);
|
|
7925
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
7926
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
7926
7927
|
url: this.config.url({
|
|
7927
7928
|
path: "/responses",
|
|
7928
7929
|
modelId: this.modelId
|
|
7929
7930
|
}),
|
|
7930
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
7931
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
7931
7932
|
body: {
|
|
7932
7933
|
...body,
|
|
7933
7934
|
stream: true
|
|
7934
7935
|
},
|
|
7935
7936
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
7936
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
7937
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
7937
7938
|
openaiResponsesChunkSchema
|
|
7938
7939
|
),
|
|
7939
7940
|
abortSignal: options.abortSignal,
|
|
@@ -8026,7 +8027,7 @@ var OpenAIResponsesLanguageModel = class {
|
|
|
8026
8027
|
type: "source",
|
|
8027
8028
|
source: {
|
|
8028
8029
|
sourceType: "url",
|
|
8029
|
-
id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
|
|
8030
|
+
id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId$1(),
|
|
8030
8031
|
url: value.annotation.url,
|
|
8031
8032
|
title: value.annotation.title
|
|
8032
8033
|
}
|
|
@@ -8294,12 +8295,12 @@ var OpenAISpeechModel = class {
|
|
|
8294
8295
|
value: audio,
|
|
8295
8296
|
responseHeaders,
|
|
8296
8297
|
rawValue: rawResponse
|
|
8297
|
-
} = await postJsonToApi({
|
|
8298
|
+
} = await postJsonToApi$1({
|
|
8298
8299
|
url: this.config.url({
|
|
8299
8300
|
path: "/audio/speech",
|
|
8300
8301
|
modelId: this.modelId
|
|
8301
8302
|
}),
|
|
8302
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
8303
|
+
headers: combineHeaders$1(this.config.headers(), options.headers),
|
|
8303
8304
|
body: requestBody,
|
|
8304
8305
|
failedResponseHandler: openaiFailedResponseHandler,
|
|
8305
8306
|
successfulResponseHandler: createBinaryResponseHandler(),
|
|
@@ -8325,11 +8326,11 @@ var OpenAISpeechModel = class {
|
|
|
8325
8326
|
// src/openai-provider.ts
|
|
8326
8327
|
function createOpenAI(options = {}) {
|
|
8327
8328
|
var _a, _b, _c;
|
|
8328
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
|
|
8329
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
|
|
8329
8330
|
const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
|
|
8330
8331
|
const providerName = (_c = options.name) != null ? _c : "openai";
|
|
8331
8332
|
const getHeaders = () => ({
|
|
8332
|
-
Authorization: `Bearer ${loadApiKey({
|
|
8333
|
+
Authorization: `Bearer ${loadApiKey$1({
|
|
8333
8334
|
apiKey: options.apiKey,
|
|
8334
8335
|
environmentVariableName: "OPENAI_API_KEY",
|
|
8335
8336
|
description: "OpenAI"
|
|
@@ -8657,7 +8658,7 @@ var anthropicErrorDataSchema = z.object({
|
|
|
8657
8658
|
message: z.string()
|
|
8658
8659
|
})
|
|
8659
8660
|
});
|
|
8660
|
-
var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
|
|
8661
|
+
var anthropicFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
8661
8662
|
errorSchema: anthropicErrorDataSchema,
|
|
8662
8663
|
errorToMessage: (data) => data.error.message
|
|
8663
8664
|
});
|
|
@@ -8775,7 +8776,7 @@ function prepareTools$2(mode) {
|
|
|
8775
8776
|
};
|
|
8776
8777
|
default: {
|
|
8777
8778
|
const _exhaustiveCheck = type;
|
|
8778
|
-
throw new UnsupportedFunctionalityError({
|
|
8779
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8779
8780
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
8780
8781
|
});
|
|
8781
8782
|
}
|
|
@@ -8804,7 +8805,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8804
8805
|
switch (type) {
|
|
8805
8806
|
case "system": {
|
|
8806
8807
|
if (system != null) {
|
|
8807
|
-
throw new UnsupportedFunctionalityError({
|
|
8808
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8808
8809
|
functionality: "Multiple system messages that are separated by user/assistant messages"
|
|
8809
8810
|
});
|
|
8810
8811
|
}
|
|
@@ -8843,7 +8844,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8843
8844
|
} : {
|
|
8844
8845
|
type: "base64",
|
|
8845
8846
|
media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
|
|
8846
|
-
data: convertUint8ArrayToBase64(part.image)
|
|
8847
|
+
data: convertUint8ArrayToBase64$1(part.image)
|
|
8847
8848
|
},
|
|
8848
8849
|
cache_control: cacheControl
|
|
8849
8850
|
});
|
|
@@ -8851,7 +8852,7 @@ function convertToAnthropicMessagesPrompt({
|
|
|
8851
8852
|
}
|
|
8852
8853
|
case "file": {
|
|
8853
8854
|
if (part.mimeType !== "application/pdf") {
|
|
8854
|
-
throw new UnsupportedFunctionalityError({
|
|
8855
|
+
throw new UnsupportedFunctionalityError$1({
|
|
8855
8856
|
functionality: "Non-PDF files in user messages"
|
|
8856
8857
|
});
|
|
8857
8858
|
}
|
|
@@ -9148,7 +9149,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9148
9149
|
};
|
|
9149
9150
|
if (isThinking) {
|
|
9150
9151
|
if (thinkingBudget == null) {
|
|
9151
|
-
throw new UnsupportedFunctionalityError({
|
|
9152
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9152
9153
|
functionality: "thinking requires a budget"
|
|
9153
9154
|
});
|
|
9154
9155
|
}
|
|
@@ -9193,7 +9194,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9193
9194
|
};
|
|
9194
9195
|
}
|
|
9195
9196
|
case "object-json": {
|
|
9196
|
-
throw new UnsupportedFunctionalityError({
|
|
9197
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9197
9198
|
functionality: "json-mode object generation"
|
|
9198
9199
|
});
|
|
9199
9200
|
}
|
|
@@ -9219,7 +9220,7 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9219
9220
|
betas,
|
|
9220
9221
|
headers
|
|
9221
9222
|
}) {
|
|
9222
|
-
return combineHeaders(
|
|
9223
|
+
return combineHeaders$1(
|
|
9223
9224
|
await resolve(this.config.headers),
|
|
9224
9225
|
betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
|
|
9225
9226
|
headers
|
|
@@ -9240,12 +9241,12 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9240
9241
|
responseHeaders,
|
|
9241
9242
|
value: response,
|
|
9242
9243
|
rawValue: rawResponse
|
|
9243
|
-
} = await postJsonToApi({
|
|
9244
|
+
} = await postJsonToApi$1({
|
|
9244
9245
|
url: this.buildRequestUrl(false),
|
|
9245
9246
|
headers: await this.getHeaders({ betas, headers: options.headers }),
|
|
9246
9247
|
body: this.transformRequestBody(args),
|
|
9247
9248
|
failedResponseHandler: anthropicFailedResponseHandler,
|
|
9248
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
9249
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
9249
9250
|
anthropicMessagesResponseSchema
|
|
9250
9251
|
),
|
|
9251
9252
|
abortSignal: options.abortSignal,
|
|
@@ -9315,12 +9316,12 @@ var AnthropicMessagesLanguageModel = class {
|
|
|
9315
9316
|
async doStream(options) {
|
|
9316
9317
|
const { args, warnings, betas } = await this.getArgs(options);
|
|
9317
9318
|
const body = { ...args, stream: true };
|
|
9318
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
9319
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
9319
9320
|
url: this.buildRequestUrl(true),
|
|
9320
9321
|
headers: await this.getHeaders({ betas, headers: options.headers }),
|
|
9321
9322
|
body: this.transformRequestBody(body),
|
|
9322
9323
|
failedResponseHandler: anthropicFailedResponseHandler,
|
|
9323
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
9324
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(
|
|
9324
9325
|
anthropicMessagesChunkSchema
|
|
9325
9326
|
),
|
|
9326
9327
|
abortSignal: options.abortSignal,
|
|
@@ -9761,10 +9762,10 @@ var anthropicTools = {
|
|
|
9761
9762
|
// src/anthropic-provider.ts
|
|
9762
9763
|
function createAnthropic(options = {}) {
|
|
9763
9764
|
var _a;
|
|
9764
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
|
|
9765
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
|
|
9765
9766
|
const getHeaders = () => ({
|
|
9766
9767
|
"anthropic-version": "2023-06-01",
|
|
9767
|
-
"x-api-key": loadApiKey({
|
|
9768
|
+
"x-api-key": loadApiKey$1({
|
|
9768
9769
|
apiKey: options.apiKey,
|
|
9769
9770
|
environmentVariableName: "ANTHROPIC_API_KEY",
|
|
9770
9771
|
description: "Anthropic"
|
|
@@ -9904,7 +9905,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9904
9905
|
switch (role) {
|
|
9905
9906
|
case "system": {
|
|
9906
9907
|
if (!systemMessagesAllowed) {
|
|
9907
|
-
throw new UnsupportedFunctionalityError({
|
|
9908
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9908
9909
|
functionality: "system messages are only supported at the beginning of the conversation"
|
|
9909
9910
|
});
|
|
9910
9911
|
}
|
|
@@ -9930,7 +9931,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9930
9931
|
} : {
|
|
9931
9932
|
inlineData: {
|
|
9932
9933
|
mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
|
|
9933
|
-
data: convertUint8ArrayToBase64(part.image)
|
|
9934
|
+
data: convertUint8ArrayToBase64$1(part.image)
|
|
9934
9935
|
}
|
|
9935
9936
|
}
|
|
9936
9937
|
);
|
|
@@ -9968,12 +9969,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
|
|
|
9968
9969
|
}
|
|
9969
9970
|
case "file": {
|
|
9970
9971
|
if (part.mimeType !== "image/png") {
|
|
9971
|
-
throw new UnsupportedFunctionalityError({
|
|
9972
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9972
9973
|
functionality: "Only PNG images are supported in assistant messages"
|
|
9973
9974
|
});
|
|
9974
9975
|
}
|
|
9975
9976
|
if (part.data instanceof URL) {
|
|
9976
|
-
throw new UnsupportedFunctionalityError({
|
|
9977
|
+
throw new UnsupportedFunctionalityError$1({
|
|
9977
9978
|
functionality: "File data URLs in assistant messages are not supported"
|
|
9978
9979
|
});
|
|
9979
9980
|
}
|
|
@@ -10032,7 +10033,7 @@ var googleErrorDataSchema = z.object({
|
|
|
10032
10033
|
status: z.string()
|
|
10033
10034
|
})
|
|
10034
10035
|
});
|
|
10035
|
-
var googleFailedResponseHandler = createJsonErrorResponseHandler({
|
|
10036
|
+
var googleFailedResponseHandler = createJsonErrorResponseHandler$1({
|
|
10036
10037
|
errorSchema: googleErrorDataSchema,
|
|
10037
10038
|
errorToMessage: (data) => data.error.message
|
|
10038
10039
|
});
|
|
@@ -10107,7 +10108,7 @@ function prepareTools$1(mode, useSearchGrounding, dynamicRetrievalConfig, modelI
|
|
|
10107
10108
|
};
|
|
10108
10109
|
default: {
|
|
10109
10110
|
const _exhaustiveCheck = type;
|
|
10110
|
-
throw new UnsupportedFunctionalityError({
|
|
10111
|
+
throw new UnsupportedFunctionalityError$1({
|
|
10111
10112
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
10112
10113
|
});
|
|
10113
10114
|
}
|
|
@@ -10278,7 +10279,7 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10278
10279
|
var _a, _b, _c, _d, _e;
|
|
10279
10280
|
const { args, warnings } = await this.getArgs(options);
|
|
10280
10281
|
const body = JSON.stringify(args);
|
|
10281
|
-
const mergedHeaders = combineHeaders(
|
|
10282
|
+
const mergedHeaders = combineHeaders$1(
|
|
10282
10283
|
await resolve(this.config.headers),
|
|
10283
10284
|
options.headers
|
|
10284
10285
|
);
|
|
@@ -10286,14 +10287,14 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10286
10287
|
responseHeaders,
|
|
10287
10288
|
value: response,
|
|
10288
10289
|
rawValue: rawResponse
|
|
10289
|
-
} = await postJsonToApi({
|
|
10290
|
+
} = await postJsonToApi$1({
|
|
10290
10291
|
url: `${this.config.baseURL}/${getModelPath(
|
|
10291
10292
|
this.modelId
|
|
10292
10293
|
)}:generateContent`,
|
|
10293
10294
|
headers: mergedHeaders,
|
|
10294
10295
|
body: args,
|
|
10295
10296
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10296
|
-
successfulResponseHandler: createJsonResponseHandler(responseSchema),
|
|
10297
|
+
successfulResponseHandler: createJsonResponseHandler$1(responseSchema),
|
|
10297
10298
|
abortSignal: options.abortSignal,
|
|
10298
10299
|
fetch: this.config.fetch
|
|
10299
10300
|
});
|
|
@@ -10339,18 +10340,18 @@ var GoogleGenerativeAILanguageModel = class {
|
|
|
10339
10340
|
async doStream(options) {
|
|
10340
10341
|
const { args, warnings } = await this.getArgs(options);
|
|
10341
10342
|
const body = JSON.stringify(args);
|
|
10342
|
-
const headers = combineHeaders(
|
|
10343
|
+
const headers = combineHeaders$1(
|
|
10343
10344
|
await resolve(this.config.headers),
|
|
10344
10345
|
options.headers
|
|
10345
10346
|
);
|
|
10346
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
10347
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
10347
10348
|
url: `${this.config.baseURL}/${getModelPath(
|
|
10348
10349
|
this.modelId
|
|
10349
10350
|
)}:streamGenerateContent?alt=sse`,
|
|
10350
10351
|
headers,
|
|
10351
10352
|
body: args,
|
|
10352
10353
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10353
|
-
successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
|
|
10354
|
+
successfulResponseHandler: createEventSourceResponseHandler$1(chunkSchema),
|
|
10354
10355
|
abortSignal: options.abortSignal,
|
|
10355
10356
|
fetch: this.config.fetch
|
|
10356
10357
|
});
|
|
@@ -10626,11 +10627,11 @@ var GoogleGenerativeAIEmbeddingModel = class {
|
|
|
10626
10627
|
values
|
|
10627
10628
|
});
|
|
10628
10629
|
}
|
|
10629
|
-
const mergedHeaders = combineHeaders(
|
|
10630
|
+
const mergedHeaders = combineHeaders$1(
|
|
10630
10631
|
await resolve(this.config.headers),
|
|
10631
10632
|
headers
|
|
10632
10633
|
);
|
|
10633
|
-
const { responseHeaders, value: response } = await postJsonToApi({
|
|
10634
|
+
const { responseHeaders, value: response } = await postJsonToApi$1({
|
|
10634
10635
|
url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
|
|
10635
10636
|
headers: mergedHeaders,
|
|
10636
10637
|
body: {
|
|
@@ -10642,7 +10643,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
|
|
|
10642
10643
|
}))
|
|
10643
10644
|
},
|
|
10644
10645
|
failedResponseHandler: googleFailedResponseHandler,
|
|
10645
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
10646
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
10646
10647
|
googleGenerativeAITextEmbeddingResponseSchema
|
|
10647
10648
|
),
|
|
10648
10649
|
abortSignal,
|
|
@@ -10667,9 +10668,9 @@ function isSupportedFileUrl(url) {
|
|
|
10667
10668
|
// src/google-provider.ts
|
|
10668
10669
|
function createGoogleGenerativeAI(options = {}) {
|
|
10669
10670
|
var _a;
|
|
10670
|
-
const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
|
|
10671
|
+
const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
|
|
10671
10672
|
const getHeaders = () => ({
|
|
10672
|
-
"x-goog-api-key": loadApiKey({
|
|
10673
|
+
"x-goog-api-key": loadApiKey$1({
|
|
10673
10674
|
apiKey: options.apiKey,
|
|
10674
10675
|
environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
|
|
10675
10676
|
description: "Google Generative AI"
|
|
@@ -10682,7 +10683,7 @@ function createGoogleGenerativeAI(options = {}) {
|
|
|
10682
10683
|
provider: "google.generative-ai",
|
|
10683
10684
|
baseURL,
|
|
10684
10685
|
headers: getHeaders,
|
|
10685
|
-
generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
|
|
10686
|
+
generateId: (_a2 = options.generateId) != null ? _a2 : generateId$1,
|
|
10686
10687
|
isSupportedUrl: isSupportedFileUrl,
|
|
10687
10688
|
fetch: options.fetch
|
|
10688
10689
|
});
|
|
@@ -11491,9 +11492,9 @@ var BedrockErrorSchema = z.object({
|
|
|
11491
11492
|
type: z.string().nullish()
|
|
11492
11493
|
});
|
|
11493
11494
|
var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
11494
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
11495
|
+
const responseHeaders = extractResponseHeaders$1(response);
|
|
11495
11496
|
if (response.body == null) {
|
|
11496
|
-
throw new EmptyResponseBodyError({});
|
|
11497
|
+
throw new EmptyResponseBodyError$1({});
|
|
11497
11498
|
}
|
|
11498
11499
|
const codec = new EventStreamCodec(toUtf8, fromUtf8);
|
|
11499
11500
|
let buffer = new Uint8Array(0);
|
|
@@ -11523,7 +11524,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
|
|
|
11523
11524
|
buffer = buffer.slice(totalLength);
|
|
11524
11525
|
if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
|
|
11525
11526
|
const data = textDecoder.decode(decoded.body);
|
|
11526
|
-
const parsedDataResult = safeParseJSON({ text: data });
|
|
11527
|
+
const parsedDataResult = safeParseJSON$1({ text: data });
|
|
11527
11528
|
if (!parsedDataResult.success) {
|
|
11528
11529
|
controller.enqueue(parsedDataResult);
|
|
11529
11530
|
break;
|
|
@@ -11532,7 +11533,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
|
|
|
11532
11533
|
let wrappedData = {
|
|
11533
11534
|
[(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
|
|
11534
11535
|
};
|
|
11535
|
-
const validatedWrappedData = safeValidateTypes({
|
|
11536
|
+
const validatedWrappedData = safeValidateTypes$1({
|
|
11536
11537
|
value: wrappedData,
|
|
11537
11538
|
schema: chunkSchema
|
|
11538
11539
|
});
|
|
@@ -11615,13 +11616,13 @@ function prepareTools(mode) {
|
|
|
11615
11616
|
};
|
|
11616
11617
|
default: {
|
|
11617
11618
|
const _exhaustiveCheck = type;
|
|
11618
|
-
throw new UnsupportedFunctionalityError({
|
|
11619
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11619
11620
|
functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
|
|
11620
11621
|
});
|
|
11621
11622
|
}
|
|
11622
11623
|
}
|
|
11623
11624
|
}
|
|
11624
|
-
var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
|
|
11625
|
+
var generateFileId = createIdGenerator$1({ prefix: "file", size: 16 });
|
|
11625
11626
|
function getCachePoint(providerMetadata) {
|
|
11626
11627
|
var _a;
|
|
11627
11628
|
return (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.cachePoint;
|
|
@@ -11638,7 +11639,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11638
11639
|
switch (type) {
|
|
11639
11640
|
case "system": {
|
|
11640
11641
|
if (messages.length > 0) {
|
|
11641
|
-
throw new UnsupportedFunctionalityError({
|
|
11642
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11642
11643
|
functionality: "Multiple system messages that are separated by user/assistant messages"
|
|
11643
11644
|
});
|
|
11644
11645
|
}
|
|
@@ -11667,7 +11668,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11667
11668
|
}
|
|
11668
11669
|
case "image": {
|
|
11669
11670
|
if (part.image instanceof URL) {
|
|
11670
|
-
throw new UnsupportedFunctionalityError({
|
|
11671
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11671
11672
|
functionality: "Image URLs in user messages"
|
|
11672
11673
|
});
|
|
11673
11674
|
}
|
|
@@ -11677,7 +11678,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11677
11678
|
"/"
|
|
11678
11679
|
)) == null ? void 0 : _b[1],
|
|
11679
11680
|
source: {
|
|
11680
|
-
bytes: convertUint8ArrayToBase64(
|
|
11681
|
+
bytes: convertUint8ArrayToBase64$1(
|
|
11681
11682
|
(_c = part.image) != null ? _c : part.image
|
|
11682
11683
|
)
|
|
11683
11684
|
}
|
|
@@ -11687,7 +11688,7 @@ function convertToBedrockChatMessages(prompt) {
|
|
|
11687
11688
|
}
|
|
11688
11689
|
case "file": {
|
|
11689
11690
|
if (part.data instanceof URL) {
|
|
11690
|
-
throw new UnsupportedFunctionalityError({
|
|
11691
|
+
throw new UnsupportedFunctionalityError$1({
|
|
11691
11692
|
functionality: "File URLs in user messages"
|
|
11692
11693
|
});
|
|
11693
11694
|
}
|
|
@@ -11977,7 +11978,7 @@ var BedrockChatLanguageModel = class {
|
|
|
11977
11978
|
(_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.reasoning_config
|
|
11978
11979
|
);
|
|
11979
11980
|
if (!reasoningConfigOptions.success) {
|
|
11980
|
-
throw new InvalidArgumentError({
|
|
11981
|
+
throw new InvalidArgumentError$1({
|
|
11981
11982
|
argument: "providerOptions.bedrock.reasoning_config",
|
|
11982
11983
|
message: "invalid reasoning configuration options",
|
|
11983
11984
|
cause: reasoningConfigOptions.error
|
|
@@ -12042,7 +12043,7 @@ var BedrockChatLanguageModel = class {
|
|
|
12042
12043
|
};
|
|
12043
12044
|
}
|
|
12044
12045
|
case "object-json": {
|
|
12045
|
-
throw new UnsupportedFunctionalityError({
|
|
12046
|
+
throw new UnsupportedFunctionalityError$1({
|
|
12046
12047
|
functionality: "json-mode object generation"
|
|
12047
12048
|
});
|
|
12048
12049
|
}
|
|
@@ -12078,21 +12079,21 @@ var BedrockChatLanguageModel = class {
|
|
|
12078
12079
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
|
|
12079
12080
|
const { command: args, warnings } = this.getArgs(options);
|
|
12080
12081
|
const url = `${this.getUrl(this.modelId)}/converse`;
|
|
12081
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12082
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12082
12083
|
url,
|
|
12083
|
-
headers: combineHeaders(
|
|
12084
|
+
headers: combineHeaders$1(
|
|
12084
12085
|
await resolve(this.config.headers),
|
|
12085
12086
|
options.headers
|
|
12086
12087
|
),
|
|
12087
12088
|
body: args,
|
|
12088
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12089
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12089
12090
|
errorSchema: BedrockErrorSchema,
|
|
12090
12091
|
errorToMessage: (error) => {
|
|
12091
12092
|
var _a2;
|
|
12092
12093
|
return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
|
|
12093
12094
|
}
|
|
12094
12095
|
}),
|
|
12095
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12096
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12096
12097
|
BedrockResponseSchema
|
|
12097
12098
|
),
|
|
12098
12099
|
abortSignal: options.abortSignal,
|
|
@@ -12160,14 +12161,14 @@ var BedrockChatLanguageModel = class {
|
|
|
12160
12161
|
async doStream(options) {
|
|
12161
12162
|
const { command: args, warnings } = this.getArgs(options);
|
|
12162
12163
|
const url = `${this.getUrl(this.modelId)}/converse-stream`;
|
|
12163
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12164
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12164
12165
|
url,
|
|
12165
|
-
headers: combineHeaders(
|
|
12166
|
+
headers: combineHeaders$1(
|
|
12166
12167
|
await resolve(this.config.headers),
|
|
12167
12168
|
options.headers
|
|
12168
12169
|
),
|
|
12169
12170
|
body: args,
|
|
12170
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12171
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12171
12172
|
errorSchema: BedrockErrorSchema,
|
|
12172
12173
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12173
12174
|
}),
|
|
@@ -12450,17 +12451,17 @@ var BedrockEmbeddingModel = class {
|
|
|
12450
12451
|
normalize: this.settings.normalize
|
|
12451
12452
|
};
|
|
12452
12453
|
const url = this.getUrl(this.modelId);
|
|
12453
|
-
const { value: response } = await postJsonToApi({
|
|
12454
|
+
const { value: response } = await postJsonToApi$1({
|
|
12454
12455
|
url,
|
|
12455
12456
|
headers: await resolve(
|
|
12456
|
-
combineHeaders(await resolve(this.config.headers), headers)
|
|
12457
|
+
combineHeaders$1(await resolve(this.config.headers), headers)
|
|
12457
12458
|
),
|
|
12458
12459
|
body: args,
|
|
12459
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12460
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12460
12461
|
errorSchema: BedrockErrorSchema,
|
|
12461
12462
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12462
12463
|
}),
|
|
12463
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12464
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12464
12465
|
BedrockEmbeddingResponseSchema
|
|
12465
12466
|
),
|
|
12466
12467
|
fetch: this.config.fetch,
|
|
@@ -12545,17 +12546,17 @@ var BedrockImageModel = class {
|
|
|
12545
12546
|
});
|
|
12546
12547
|
}
|
|
12547
12548
|
const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
|
|
12548
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
12549
|
+
const { value: response, responseHeaders } = await postJsonToApi$1({
|
|
12549
12550
|
url: this.getUrl(this.modelId),
|
|
12550
12551
|
headers: await resolve(
|
|
12551
|
-
combineHeaders(await resolve(this.config.headers), headers)
|
|
12552
|
+
combineHeaders$1(await resolve(this.config.headers), headers)
|
|
12552
12553
|
),
|
|
12553
12554
|
body: args,
|
|
12554
|
-
failedResponseHandler: createJsonErrorResponseHandler({
|
|
12555
|
+
failedResponseHandler: createJsonErrorResponseHandler$1({
|
|
12555
12556
|
errorSchema: BedrockErrorSchema,
|
|
12556
12557
|
errorToMessage: (error) => `${error.type}: ${error.message}`
|
|
12557
12558
|
}),
|
|
12558
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
12559
|
+
successfulResponseHandler: createJsonResponseHandler$1(
|
|
12559
12560
|
bedrockImageResponseSchema
|
|
12560
12561
|
),
|
|
12561
12562
|
abortSignal,
|
|
@@ -12614,7 +12615,7 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
|
|
|
12614
12615
|
const signer = new AwsV4Signer({
|
|
12615
12616
|
url,
|
|
12616
12617
|
method: "POST",
|
|
12617
|
-
headers: Object.entries(removeUndefinedEntries(originalHeaders)),
|
|
12618
|
+
headers: Object.entries(removeUndefinedEntries$1(originalHeaders)),
|
|
12618
12619
|
body,
|
|
12619
12620
|
region: credentials.region,
|
|
12620
12621
|
accessKeyId: credentials.accessKeyId,
|
|
@@ -12627,8 +12628,8 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
|
|
|
12627
12628
|
return fetch(input, {
|
|
12628
12629
|
...init,
|
|
12629
12630
|
body,
|
|
12630
|
-
headers: removeUndefinedEntries(
|
|
12631
|
-
combineHeaders(originalHeaders, signedHeaders)
|
|
12631
|
+
headers: removeUndefinedEntries$1(
|
|
12632
|
+
combineHeaders$1(originalHeaders, signedHeaders)
|
|
12632
12633
|
)
|
|
12633
12634
|
});
|
|
12634
12635
|
};
|
|
@@ -12682,7 +12683,7 @@ function createAmazonBedrock(options = {}) {
|
|
|
12682
12683
|
}, options.fetch);
|
|
12683
12684
|
const getBaseUrl = () => {
|
|
12684
12685
|
var _a, _b;
|
|
12685
|
-
return (_b = withoutTrailingSlash(
|
|
12686
|
+
return (_b = withoutTrailingSlash$1(
|
|
12686
12687
|
(_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
|
|
12687
12688
|
settingValue: options.region,
|
|
12688
12689
|
settingName: "region",
|
|
@@ -12697,7 +12698,7 @@ function createAmazonBedrock(options = {}) {
|
|
|
12697
12698
|
baseUrl: getBaseUrl,
|
|
12698
12699
|
headers: (_a = options.headers) != null ? _a : {},
|
|
12699
12700
|
fetch: sigv4Fetch,
|
|
12700
|
-
generateId
|
|
12701
|
+
generateId: generateId$1
|
|
12701
12702
|
});
|
|
12702
12703
|
};
|
|
12703
12704
|
const provider = function(modelId, settings) {
|
|
@@ -12734,29 +12735,2065 @@ function createAmazonBedrock(options = {}) {
|
|
|
12734
12735
|
}
|
|
12735
12736
|
createAmazonBedrock();
|
|
12736
12737
|
|
|
12737
|
-
|
|
12738
|
-
|
|
12739
|
-
|
|
12740
|
-
|
|
12741
|
-
|
|
12742
|
-
|
|
12743
|
-
|
|
12744
|
-
|
|
12745
|
-
|
|
12746
|
-
|
|
12747
|
-
|
|
12748
|
-
|
|
12749
|
-
|
|
12750
|
-
|
|
12751
|
-
|
|
12752
|
-
|
|
12753
|
-
|
|
12754
|
-
|
|
12755
|
-
|
|
12756
|
-
|
|
12757
|
-
|
|
12758
|
-
|
|
12759
|
-
|
|
12738
|
+
// src/errors/ai-sdk-error.ts
|
|
12739
|
+
var marker = "vercel.ai.error";
|
|
12740
|
+
var symbol = Symbol.for(marker);
|
|
12741
|
+
var _a;
|
|
12742
|
+
var _AISDKError = class _AISDKError extends Error {
|
|
12743
|
+
/**
|
|
12744
|
+
* Creates an AI SDK Error.
|
|
12745
|
+
*
|
|
12746
|
+
* @param {Object} params - The parameters for creating the error.
|
|
12747
|
+
* @param {string} params.name - The name of the error.
|
|
12748
|
+
* @param {string} params.message - The error message.
|
|
12749
|
+
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
12750
|
+
*/
|
|
12751
|
+
constructor({
|
|
12752
|
+
name: name14,
|
|
12753
|
+
message,
|
|
12754
|
+
cause
|
|
12755
|
+
}) {
|
|
12756
|
+
super(message);
|
|
12757
|
+
this[_a] = true;
|
|
12758
|
+
this.name = name14;
|
|
12759
|
+
this.cause = cause;
|
|
12760
|
+
}
|
|
12761
|
+
/**
|
|
12762
|
+
* Checks if the given error is an AI SDK Error.
|
|
12763
|
+
* @param {unknown} error - The error to check.
|
|
12764
|
+
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
12765
|
+
*/
|
|
12766
|
+
static isInstance(error) {
|
|
12767
|
+
return _AISDKError.hasMarker(error, marker);
|
|
12768
|
+
}
|
|
12769
|
+
static hasMarker(error, marker15) {
|
|
12770
|
+
const markerSymbol = Symbol.for(marker15);
|
|
12771
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
12772
|
+
}
|
|
12773
|
+
};
|
|
12774
|
+
_a = symbol;
|
|
12775
|
+
var AISDKError = _AISDKError;
|
|
12776
|
+
|
|
12777
|
+
// src/errors/api-call-error.ts
|
|
12778
|
+
var name = "AI_APICallError";
|
|
12779
|
+
var marker2 = `vercel.ai.error.${name}`;
|
|
12780
|
+
var symbol2 = Symbol.for(marker2);
|
|
12781
|
+
var _a2;
|
|
12782
|
+
var APICallError = class extends AISDKError {
|
|
12783
|
+
constructor({
|
|
12784
|
+
message,
|
|
12785
|
+
url,
|
|
12786
|
+
requestBodyValues,
|
|
12787
|
+
statusCode,
|
|
12788
|
+
responseHeaders,
|
|
12789
|
+
responseBody,
|
|
12790
|
+
cause,
|
|
12791
|
+
isRetryable = statusCode != null && (statusCode === 408 || // request timeout
|
|
12792
|
+
statusCode === 409 || // conflict
|
|
12793
|
+
statusCode === 429 || // too many requests
|
|
12794
|
+
statusCode >= 500),
|
|
12795
|
+
// server error
|
|
12796
|
+
data
|
|
12797
|
+
}) {
|
|
12798
|
+
super({ name, message, cause });
|
|
12799
|
+
this[_a2] = true;
|
|
12800
|
+
this.url = url;
|
|
12801
|
+
this.requestBodyValues = requestBodyValues;
|
|
12802
|
+
this.statusCode = statusCode;
|
|
12803
|
+
this.responseHeaders = responseHeaders;
|
|
12804
|
+
this.responseBody = responseBody;
|
|
12805
|
+
this.isRetryable = isRetryable;
|
|
12806
|
+
this.data = data;
|
|
12807
|
+
}
|
|
12808
|
+
static isInstance(error) {
|
|
12809
|
+
return AISDKError.hasMarker(error, marker2);
|
|
12810
|
+
}
|
|
12811
|
+
};
|
|
12812
|
+
_a2 = symbol2;
|
|
12813
|
+
|
|
12814
|
+
// src/errors/empty-response-body-error.ts
|
|
12815
|
+
var name2 = "AI_EmptyResponseBodyError";
|
|
12816
|
+
var marker3 = `vercel.ai.error.${name2}`;
|
|
12817
|
+
var symbol3 = Symbol.for(marker3);
|
|
12818
|
+
var _a3;
|
|
12819
|
+
var EmptyResponseBodyError = class extends AISDKError {
|
|
12820
|
+
// used in isInstance
|
|
12821
|
+
constructor({ message = "Empty response body" } = {}) {
|
|
12822
|
+
super({ name: name2, message });
|
|
12823
|
+
this[_a3] = true;
|
|
12824
|
+
}
|
|
12825
|
+
static isInstance(error) {
|
|
12826
|
+
return AISDKError.hasMarker(error, marker3);
|
|
12827
|
+
}
|
|
12828
|
+
};
|
|
12829
|
+
_a3 = symbol3;
|
|
12830
|
+
|
|
12831
|
+
// src/errors/get-error-message.ts
|
|
12832
|
+
function getErrorMessage(error) {
|
|
12833
|
+
if (error == null) {
|
|
12834
|
+
return "unknown error";
|
|
12835
|
+
}
|
|
12836
|
+
if (typeof error === "string") {
|
|
12837
|
+
return error;
|
|
12838
|
+
}
|
|
12839
|
+
if (error instanceof Error) {
|
|
12840
|
+
return error.message;
|
|
12841
|
+
}
|
|
12842
|
+
return JSON.stringify(error);
|
|
12843
|
+
}
|
|
12844
|
+
|
|
12845
|
+
// src/errors/invalid-argument-error.ts
|
|
12846
|
+
var name3 = "AI_InvalidArgumentError";
|
|
12847
|
+
var marker4 = `vercel.ai.error.${name3}`;
|
|
12848
|
+
var symbol4 = Symbol.for(marker4);
|
|
12849
|
+
var _a4;
|
|
12850
|
+
var InvalidArgumentError = class extends AISDKError {
|
|
12851
|
+
constructor({
|
|
12852
|
+
message,
|
|
12853
|
+
cause,
|
|
12854
|
+
argument
|
|
12855
|
+
}) {
|
|
12856
|
+
super({ name: name3, message, cause });
|
|
12857
|
+
this[_a4] = true;
|
|
12858
|
+
this.argument = argument;
|
|
12859
|
+
}
|
|
12860
|
+
static isInstance(error) {
|
|
12861
|
+
return AISDKError.hasMarker(error, marker4);
|
|
12862
|
+
}
|
|
12863
|
+
};
|
|
12864
|
+
_a4 = symbol4;
|
|
12865
|
+
|
|
12866
|
+
// src/errors/invalid-prompt-error.ts
|
|
12867
|
+
var name4 = "AI_InvalidPromptError";
|
|
12868
|
+
var marker5 = `vercel.ai.error.${name4}`;
|
|
12869
|
+
var symbol5 = Symbol.for(marker5);
|
|
12870
|
+
var _a5;
|
|
12871
|
+
var InvalidPromptError = class extends AISDKError {
|
|
12872
|
+
constructor({
|
|
12873
|
+
prompt,
|
|
12874
|
+
message,
|
|
12875
|
+
cause
|
|
12876
|
+
}) {
|
|
12877
|
+
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
12878
|
+
this[_a5] = true;
|
|
12879
|
+
this.prompt = prompt;
|
|
12880
|
+
}
|
|
12881
|
+
static isInstance(error) {
|
|
12882
|
+
return AISDKError.hasMarker(error, marker5);
|
|
12883
|
+
}
|
|
12884
|
+
};
|
|
12885
|
+
_a5 = symbol5;
|
|
12886
|
+
|
|
12887
|
+
// src/errors/invalid-response-data-error.ts
|
|
12888
|
+
var name5 = "AI_InvalidResponseDataError";
|
|
12889
|
+
var marker6 = `vercel.ai.error.${name5}`;
|
|
12890
|
+
var symbol6 = Symbol.for(marker6);
|
|
12891
|
+
var _a6;
|
|
12892
|
+
var InvalidResponseDataError = class extends AISDKError {
|
|
12893
|
+
constructor({
|
|
12894
|
+
data,
|
|
12895
|
+
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
12896
|
+
}) {
|
|
12897
|
+
super({ name: name5, message });
|
|
12898
|
+
this[_a6] = true;
|
|
12899
|
+
this.data = data;
|
|
12900
|
+
}
|
|
12901
|
+
static isInstance(error) {
|
|
12902
|
+
return AISDKError.hasMarker(error, marker6);
|
|
12903
|
+
}
|
|
12904
|
+
};
|
|
12905
|
+
_a6 = symbol6;
|
|
12906
|
+
|
|
12907
|
+
// src/errors/json-parse-error.ts
|
|
12908
|
+
var name6 = "AI_JSONParseError";
|
|
12909
|
+
var marker7 = `vercel.ai.error.${name6}`;
|
|
12910
|
+
var symbol7 = Symbol.for(marker7);
|
|
12911
|
+
var _a7;
|
|
12912
|
+
var JSONParseError = class extends AISDKError {
|
|
12913
|
+
constructor({ text, cause }) {
|
|
12914
|
+
super({
|
|
12915
|
+
name: name6,
|
|
12916
|
+
message: `JSON parsing failed: Text: ${text}.
|
|
12917
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
12918
|
+
cause
|
|
12919
|
+
});
|
|
12920
|
+
this[_a7] = true;
|
|
12921
|
+
this.text = text;
|
|
12922
|
+
}
|
|
12923
|
+
static isInstance(error) {
|
|
12924
|
+
return AISDKError.hasMarker(error, marker7);
|
|
12925
|
+
}
|
|
12926
|
+
};
|
|
12927
|
+
_a7 = symbol7;
|
|
12928
|
+
|
|
12929
|
+
// src/errors/load-api-key-error.ts
|
|
12930
|
+
var name7 = "AI_LoadAPIKeyError";
|
|
12931
|
+
var marker8 = `vercel.ai.error.${name7}`;
|
|
12932
|
+
var symbol8 = Symbol.for(marker8);
|
|
12933
|
+
var _a8;
|
|
12934
|
+
var LoadAPIKeyError = class extends AISDKError {
|
|
12935
|
+
// used in isInstance
|
|
12936
|
+
constructor({ message }) {
|
|
12937
|
+
super({ name: name7, message });
|
|
12938
|
+
this[_a8] = true;
|
|
12939
|
+
}
|
|
12940
|
+
static isInstance(error) {
|
|
12941
|
+
return AISDKError.hasMarker(error, marker8);
|
|
12942
|
+
}
|
|
12943
|
+
};
|
|
12944
|
+
_a8 = symbol8;
|
|
12945
|
+
|
|
12946
|
+
// src/errors/type-validation-error.ts
|
|
12947
|
+
var name12 = "AI_TypeValidationError";
|
|
12948
|
+
var marker13 = `vercel.ai.error.${name12}`;
|
|
12949
|
+
var symbol13 = Symbol.for(marker13);
|
|
12950
|
+
var _a13;
|
|
12951
|
+
var _TypeValidationError = class _TypeValidationError extends AISDKError {
|
|
12952
|
+
constructor({ value, cause }) {
|
|
12953
|
+
super({
|
|
12954
|
+
name: name12,
|
|
12955
|
+
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
12956
|
+
Error message: ${getErrorMessage(cause)}`,
|
|
12957
|
+
cause
|
|
12958
|
+
});
|
|
12959
|
+
this[_a13] = true;
|
|
12960
|
+
this.value = value;
|
|
12961
|
+
}
|
|
12962
|
+
static isInstance(error) {
|
|
12963
|
+
return AISDKError.hasMarker(error, marker13);
|
|
12964
|
+
}
|
|
12965
|
+
/**
|
|
12966
|
+
* Wraps an error into a TypeValidationError.
|
|
12967
|
+
* If the cause is already a TypeValidationError with the same value, it returns the cause.
|
|
12968
|
+
* Otherwise, it creates a new TypeValidationError.
|
|
12969
|
+
*
|
|
12970
|
+
* @param {Object} params - The parameters for wrapping the error.
|
|
12971
|
+
* @param {unknown} params.value - The value that failed validation.
|
|
12972
|
+
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
12973
|
+
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
12974
|
+
*/
|
|
12975
|
+
static wrap({
|
|
12976
|
+
value,
|
|
12977
|
+
cause
|
|
12978
|
+
}) {
|
|
12979
|
+
return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
|
|
12980
|
+
}
|
|
12981
|
+
};
|
|
12982
|
+
_a13 = symbol13;
|
|
12983
|
+
var TypeValidationError = _TypeValidationError;
|
|
12984
|
+
|
|
12985
|
+
// src/errors/unsupported-functionality-error.ts
|
|
12986
|
+
var name13 = "AI_UnsupportedFunctionalityError";
|
|
12987
|
+
var marker14 = `vercel.ai.error.${name13}`;
|
|
12988
|
+
var symbol14 = Symbol.for(marker14);
|
|
12989
|
+
var _a14;
|
|
12990
|
+
var UnsupportedFunctionalityError = class extends AISDKError {
|
|
12991
|
+
constructor({
|
|
12992
|
+
functionality,
|
|
12993
|
+
message = `'${functionality}' functionality not supported.`
|
|
12994
|
+
}) {
|
|
12995
|
+
super({ name: name13, message });
|
|
12996
|
+
this[_a14] = true;
|
|
12997
|
+
this.functionality = functionality;
|
|
12998
|
+
}
|
|
12999
|
+
static isInstance(error) {
|
|
13000
|
+
return AISDKError.hasMarker(error, marker14);
|
|
13001
|
+
}
|
|
13002
|
+
};
|
|
13003
|
+
_a14 = symbol14;
|
|
13004
|
+
|
|
13005
|
+
var secureJsonParse = {exports: {}};
|
|
13006
|
+
|
|
13007
|
+
var hasRequiredSecureJsonParse;
|
|
13008
|
+
|
|
13009
|
+
function requireSecureJsonParse () {
|
|
13010
|
+
if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
|
|
13011
|
+
hasRequiredSecureJsonParse = 1;
|
|
13012
|
+
|
|
13013
|
+
const hasBuffer = typeof Buffer !== 'undefined';
|
|
13014
|
+
const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
13015
|
+
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*:/;
|
|
13016
|
+
|
|
13017
|
+
function _parse (text, reviver, options) {
|
|
13018
|
+
// Normalize arguments
|
|
13019
|
+
if (options == null) {
|
|
13020
|
+
if (reviver !== null && typeof reviver === 'object') {
|
|
13021
|
+
options = reviver;
|
|
13022
|
+
reviver = undefined;
|
|
13023
|
+
}
|
|
13024
|
+
}
|
|
13025
|
+
|
|
13026
|
+
if (hasBuffer && Buffer.isBuffer(text)) {
|
|
13027
|
+
text = text.toString();
|
|
13028
|
+
}
|
|
13029
|
+
|
|
13030
|
+
// BOM checker
|
|
13031
|
+
if (text && text.charCodeAt(0) === 0xFEFF) {
|
|
13032
|
+
text = text.slice(1);
|
|
13033
|
+
}
|
|
13034
|
+
|
|
13035
|
+
// Parse normally, allowing exceptions
|
|
13036
|
+
const obj = JSON.parse(text, reviver);
|
|
13037
|
+
|
|
13038
|
+
// Ignore null and non-objects
|
|
13039
|
+
if (obj === null || typeof obj !== 'object') {
|
|
13040
|
+
return obj
|
|
13041
|
+
}
|
|
13042
|
+
|
|
13043
|
+
const protoAction = (options && options.protoAction) || 'error';
|
|
13044
|
+
const constructorAction = (options && options.constructorAction) || 'error';
|
|
13045
|
+
|
|
13046
|
+
// options: 'error' (default) / 'remove' / 'ignore'
|
|
13047
|
+
if (protoAction === 'ignore' && constructorAction === 'ignore') {
|
|
13048
|
+
return obj
|
|
13049
|
+
}
|
|
13050
|
+
|
|
13051
|
+
if (protoAction !== 'ignore' && constructorAction !== 'ignore') {
|
|
13052
|
+
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
|
|
13053
|
+
return obj
|
|
13054
|
+
}
|
|
13055
|
+
} else if (protoAction !== 'ignore' && constructorAction === 'ignore') {
|
|
13056
|
+
if (suspectProtoRx.test(text) === false) {
|
|
13057
|
+
return obj
|
|
13058
|
+
}
|
|
13059
|
+
} else {
|
|
13060
|
+
if (suspectConstructorRx.test(text) === false) {
|
|
13061
|
+
return obj
|
|
13062
|
+
}
|
|
13063
|
+
}
|
|
13064
|
+
|
|
13065
|
+
// Scan result for proto keys
|
|
13066
|
+
return filter(obj, { protoAction, constructorAction, safe: options && options.safe })
|
|
13067
|
+
}
|
|
13068
|
+
|
|
13069
|
+
function filter (obj, { protoAction = 'error', constructorAction = 'error', safe } = {}) {
|
|
13070
|
+
let next = [obj];
|
|
13071
|
+
|
|
13072
|
+
while (next.length) {
|
|
13073
|
+
const nodes = next;
|
|
13074
|
+
next = [];
|
|
13075
|
+
|
|
13076
|
+
for (const node of nodes) {
|
|
13077
|
+
if (protoAction !== 'ignore' && Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
|
|
13078
|
+
if (safe === true) {
|
|
13079
|
+
return null
|
|
13080
|
+
} else if (protoAction === 'error') {
|
|
13081
|
+
throw new SyntaxError('Object contains forbidden prototype property')
|
|
13082
|
+
}
|
|
13083
|
+
|
|
13084
|
+
delete node.__proto__; // eslint-disable-line no-proto
|
|
13085
|
+
}
|
|
13086
|
+
|
|
13087
|
+
if (constructorAction !== 'ignore' &&
|
|
13088
|
+
Object.prototype.hasOwnProperty.call(node, 'constructor') &&
|
|
13089
|
+
Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')) { // Avoid calling node.hasOwnProperty directly
|
|
13090
|
+
if (safe === true) {
|
|
13091
|
+
return null
|
|
13092
|
+
} else if (constructorAction === 'error') {
|
|
13093
|
+
throw new SyntaxError('Object contains forbidden prototype property')
|
|
13094
|
+
}
|
|
13095
|
+
|
|
13096
|
+
delete node.constructor;
|
|
13097
|
+
}
|
|
13098
|
+
|
|
13099
|
+
for (const key in node) {
|
|
13100
|
+
const value = node[key];
|
|
13101
|
+
if (value && typeof value === 'object') {
|
|
13102
|
+
next.push(value);
|
|
13103
|
+
}
|
|
13104
|
+
}
|
|
13105
|
+
}
|
|
13106
|
+
}
|
|
13107
|
+
return obj
|
|
13108
|
+
}
|
|
13109
|
+
|
|
13110
|
+
function parse (text, reviver, options) {
|
|
13111
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
13112
|
+
Error.stackTraceLimit = 0;
|
|
13113
|
+
try {
|
|
13114
|
+
return _parse(text, reviver, options)
|
|
13115
|
+
} finally {
|
|
13116
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
13117
|
+
}
|
|
13118
|
+
}
|
|
13119
|
+
|
|
13120
|
+
function safeParse (text, reviver) {
|
|
13121
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
13122
|
+
Error.stackTraceLimit = 0;
|
|
13123
|
+
try {
|
|
13124
|
+
return _parse(text, reviver, { safe: true })
|
|
13125
|
+
} catch (_e) {
|
|
13126
|
+
return null
|
|
13127
|
+
} finally {
|
|
13128
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
13129
|
+
}
|
|
13130
|
+
}
|
|
13131
|
+
|
|
13132
|
+
secureJsonParse.exports = parse;
|
|
13133
|
+
secureJsonParse.exports.default = parse;
|
|
13134
|
+
secureJsonParse.exports.parse = parse;
|
|
13135
|
+
secureJsonParse.exports.safeParse = safeParse;
|
|
13136
|
+
secureJsonParse.exports.scan = filter;
|
|
13137
|
+
return secureJsonParse.exports;
|
|
13138
|
+
}
|
|
13139
|
+
|
|
13140
|
+
var secureJsonParseExports = requireSecureJsonParse();
|
|
13141
|
+
var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
|
|
13142
|
+
|
|
13143
|
+
class ParseError extends Error {
|
|
13144
|
+
constructor(message, options) {
|
|
13145
|
+
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
|
|
13146
|
+
}
|
|
13147
|
+
}
|
|
13148
|
+
function noop(_arg) {
|
|
13149
|
+
}
|
|
13150
|
+
function createParser(callbacks) {
|
|
13151
|
+
if (typeof callbacks == "function")
|
|
13152
|
+
throw new TypeError(
|
|
13153
|
+
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
13154
|
+
);
|
|
13155
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
13156
|
+
let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
|
|
13157
|
+
function feed(newChunk) {
|
|
13158
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
13159
|
+
for (const line of complete)
|
|
13160
|
+
parseLine(line);
|
|
13161
|
+
incompleteLine = incomplete, isFirstChunk = false;
|
|
13162
|
+
}
|
|
13163
|
+
function parseLine(line) {
|
|
13164
|
+
if (line === "") {
|
|
13165
|
+
dispatchEvent();
|
|
13166
|
+
return;
|
|
13167
|
+
}
|
|
13168
|
+
if (line.startsWith(":")) {
|
|
13169
|
+
onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
13170
|
+
return;
|
|
13171
|
+
}
|
|
13172
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
13173
|
+
if (fieldSeparatorIndex !== -1) {
|
|
13174
|
+
const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
|
|
13175
|
+
processField(field, value, line);
|
|
13176
|
+
return;
|
|
13177
|
+
}
|
|
13178
|
+
processField(line, "", line);
|
|
13179
|
+
}
|
|
13180
|
+
function processField(field, value, line) {
|
|
13181
|
+
switch (field) {
|
|
13182
|
+
case "event":
|
|
13183
|
+
eventType = value;
|
|
13184
|
+
break;
|
|
13185
|
+
case "data":
|
|
13186
|
+
data = `${data}${value}
|
|
13187
|
+
`;
|
|
13188
|
+
break;
|
|
13189
|
+
case "id":
|
|
13190
|
+
id = value.includes("\0") ? void 0 : value;
|
|
13191
|
+
break;
|
|
13192
|
+
case "retry":
|
|
13193
|
+
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
13194
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
13195
|
+
type: "invalid-retry",
|
|
13196
|
+
value,
|
|
13197
|
+
line
|
|
13198
|
+
})
|
|
13199
|
+
);
|
|
13200
|
+
break;
|
|
13201
|
+
default:
|
|
13202
|
+
onError(
|
|
13203
|
+
new ParseError(
|
|
13204
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
13205
|
+
{ type: "unknown-field", field, value, line }
|
|
13206
|
+
)
|
|
13207
|
+
);
|
|
13208
|
+
break;
|
|
13209
|
+
}
|
|
13210
|
+
}
|
|
13211
|
+
function dispatchEvent() {
|
|
13212
|
+
data.length > 0 && onEvent({
|
|
13213
|
+
id,
|
|
13214
|
+
event: eventType || void 0,
|
|
13215
|
+
// If the data buffer's last character is a U+000A LINE FEED (LF) character,
|
|
13216
|
+
// then remove the last character from the data buffer.
|
|
13217
|
+
data: data.endsWith(`
|
|
13218
|
+
`) ? data.slice(0, -1) : data
|
|
13219
|
+
}), id = void 0, data = "", eventType = "";
|
|
13220
|
+
}
|
|
13221
|
+
function reset(options = {}) {
|
|
13222
|
+
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
|
|
13223
|
+
}
|
|
13224
|
+
return { feed, reset };
|
|
13225
|
+
}
|
|
13226
|
+
function splitLines(chunk) {
|
|
13227
|
+
const lines = [];
|
|
13228
|
+
let incompleteLine = "", searchIndex = 0;
|
|
13229
|
+
for (; searchIndex < chunk.length; ) {
|
|
13230
|
+
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
13231
|
+
`, searchIndex);
|
|
13232
|
+
let lineEnd = -1;
|
|
13233
|
+
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
|
|
13234
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
13235
|
+
break;
|
|
13236
|
+
} else {
|
|
13237
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
13238
|
+
lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
|
|
13239
|
+
` && searchIndex++;
|
|
13240
|
+
}
|
|
13241
|
+
}
|
|
13242
|
+
return [lines, incompleteLine];
|
|
13243
|
+
}
|
|
13244
|
+
|
|
13245
|
+
class EventSourceParserStream extends TransformStream {
|
|
13246
|
+
constructor({ onError, onRetry, onComment } = {}) {
|
|
13247
|
+
let parser;
|
|
13248
|
+
super({
|
|
13249
|
+
start(controller) {
|
|
13250
|
+
parser = createParser({
|
|
13251
|
+
onEvent: (event) => {
|
|
13252
|
+
controller.enqueue(event);
|
|
13253
|
+
},
|
|
13254
|
+
onError(error) {
|
|
13255
|
+
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
|
|
13256
|
+
},
|
|
13257
|
+
onRetry,
|
|
13258
|
+
onComment
|
|
13259
|
+
});
|
|
13260
|
+
},
|
|
13261
|
+
transform(chunk) {
|
|
13262
|
+
parser.feed(chunk);
|
|
13263
|
+
}
|
|
13264
|
+
});
|
|
13265
|
+
}
|
|
13266
|
+
}
|
|
13267
|
+
|
|
13268
|
+
// src/combine-headers.ts
|
|
13269
|
+
function combineHeaders(...headers) {
|
|
13270
|
+
return headers.reduce(
|
|
13271
|
+
(combinedHeaders, currentHeaders) => ({
|
|
13272
|
+
...combinedHeaders,
|
|
13273
|
+
...currentHeaders != null ? currentHeaders : {}
|
|
13274
|
+
}),
|
|
13275
|
+
{}
|
|
13276
|
+
);
|
|
13277
|
+
}
|
|
13278
|
+
|
|
13279
|
+
// src/extract-response-headers.ts
|
|
13280
|
+
function extractResponseHeaders(response) {
|
|
13281
|
+
const headers = {};
|
|
13282
|
+
response.headers.forEach((value, key) => {
|
|
13283
|
+
headers[key] = value;
|
|
13284
|
+
});
|
|
13285
|
+
return headers;
|
|
13286
|
+
}
|
|
13287
|
+
var createIdGenerator = ({
|
|
13288
|
+
prefix,
|
|
13289
|
+
size: defaultSize = 16,
|
|
13290
|
+
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
|
13291
|
+
separator = "-"
|
|
13292
|
+
} = {}) => {
|
|
13293
|
+
const generator = customAlphabet(alphabet, defaultSize);
|
|
13294
|
+
if (prefix == null) {
|
|
13295
|
+
return generator;
|
|
13296
|
+
}
|
|
13297
|
+
if (alphabet.includes(separator)) {
|
|
13298
|
+
throw new InvalidArgumentError({
|
|
13299
|
+
argument: "separator",
|
|
13300
|
+
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
13301
|
+
});
|
|
13302
|
+
}
|
|
13303
|
+
return (size) => `${prefix}${separator}${generator(size)}`;
|
|
13304
|
+
};
|
|
13305
|
+
var generateId = createIdGenerator();
|
|
13306
|
+
|
|
13307
|
+
// src/remove-undefined-entries.ts
|
|
13308
|
+
function removeUndefinedEntries(record) {
|
|
13309
|
+
return Object.fromEntries(
|
|
13310
|
+
Object.entries(record).filter(([_key, value]) => value != null)
|
|
13311
|
+
);
|
|
13312
|
+
}
|
|
13313
|
+
|
|
13314
|
+
// src/is-abort-error.ts
|
|
13315
|
+
function isAbortError(error) {
|
|
13316
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
13317
|
+
}
|
|
13318
|
+
function loadApiKey({
|
|
13319
|
+
apiKey,
|
|
13320
|
+
environmentVariableName,
|
|
13321
|
+
apiKeyParameterName = "apiKey",
|
|
13322
|
+
description
|
|
13323
|
+
}) {
|
|
13324
|
+
if (typeof apiKey === "string") {
|
|
13325
|
+
return apiKey;
|
|
13326
|
+
}
|
|
13327
|
+
if (apiKey != null) {
|
|
13328
|
+
throw new LoadAPIKeyError({
|
|
13329
|
+
message: `${description} API key must be a string.`
|
|
13330
|
+
});
|
|
13331
|
+
}
|
|
13332
|
+
if (typeof process === "undefined") {
|
|
13333
|
+
throw new LoadAPIKeyError({
|
|
13334
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
|
13335
|
+
});
|
|
13336
|
+
}
|
|
13337
|
+
apiKey = process.env[environmentVariableName];
|
|
13338
|
+
if (apiKey == null) {
|
|
13339
|
+
throw new LoadAPIKeyError({
|
|
13340
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
|
13341
|
+
});
|
|
13342
|
+
}
|
|
13343
|
+
if (typeof apiKey !== "string") {
|
|
13344
|
+
throw new LoadAPIKeyError({
|
|
13345
|
+
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
|
13346
|
+
});
|
|
13347
|
+
}
|
|
13348
|
+
return apiKey;
|
|
13349
|
+
}
|
|
13350
|
+
|
|
13351
|
+
// src/validator.ts
|
|
13352
|
+
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
13353
|
+
function validator(validate) {
|
|
13354
|
+
return { [validatorSymbol]: true, validate };
|
|
13355
|
+
}
|
|
13356
|
+
function isValidator(value) {
|
|
13357
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
13358
|
+
}
|
|
13359
|
+
function asValidator(value) {
|
|
13360
|
+
return isValidator(value) ? value : zodValidator(value);
|
|
13361
|
+
}
|
|
13362
|
+
function zodValidator(zodSchema) {
|
|
13363
|
+
return validator((value) => {
|
|
13364
|
+
const result = zodSchema.safeParse(value);
|
|
13365
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
13366
|
+
});
|
|
13367
|
+
}
|
|
13368
|
+
|
|
13369
|
+
// src/validate-types.ts
|
|
13370
|
+
function validateTypes({
|
|
13371
|
+
value,
|
|
13372
|
+
schema: inputSchema
|
|
13373
|
+
}) {
|
|
13374
|
+
const result = safeValidateTypes({ value, schema: inputSchema });
|
|
13375
|
+
if (!result.success) {
|
|
13376
|
+
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
13377
|
+
}
|
|
13378
|
+
return result.value;
|
|
13379
|
+
}
|
|
13380
|
+
function safeValidateTypes({
|
|
13381
|
+
value,
|
|
13382
|
+
schema
|
|
13383
|
+
}) {
|
|
13384
|
+
const validator2 = asValidator(schema);
|
|
13385
|
+
try {
|
|
13386
|
+
if (validator2.validate == null) {
|
|
13387
|
+
return { success: true, value };
|
|
13388
|
+
}
|
|
13389
|
+
const result = validator2.validate(value);
|
|
13390
|
+
if (result.success) {
|
|
13391
|
+
return result;
|
|
13392
|
+
}
|
|
13393
|
+
return {
|
|
13394
|
+
success: false,
|
|
13395
|
+
error: TypeValidationError.wrap({ value, cause: result.error })
|
|
13396
|
+
};
|
|
13397
|
+
} catch (error) {
|
|
13398
|
+
return {
|
|
13399
|
+
success: false,
|
|
13400
|
+
error: TypeValidationError.wrap({ value, cause: error })
|
|
13401
|
+
};
|
|
13402
|
+
}
|
|
13403
|
+
}
|
|
13404
|
+
|
|
13405
|
+
// src/parse-json.ts
|
|
13406
|
+
function parseJSON({
|
|
13407
|
+
text,
|
|
13408
|
+
schema
|
|
13409
|
+
}) {
|
|
13410
|
+
try {
|
|
13411
|
+
const value = SecureJSON.parse(text);
|
|
13412
|
+
if (schema == null) {
|
|
13413
|
+
return value;
|
|
13414
|
+
}
|
|
13415
|
+
return validateTypes({ value, schema });
|
|
13416
|
+
} catch (error) {
|
|
13417
|
+
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
|
|
13418
|
+
throw error;
|
|
13419
|
+
}
|
|
13420
|
+
throw new JSONParseError({ text, cause: error });
|
|
13421
|
+
}
|
|
13422
|
+
}
|
|
13423
|
+
function safeParseJSON({
|
|
13424
|
+
text,
|
|
13425
|
+
schema
|
|
13426
|
+
}) {
|
|
13427
|
+
try {
|
|
13428
|
+
const value = SecureJSON.parse(text);
|
|
13429
|
+
if (schema == null) {
|
|
13430
|
+
return { success: true, value, rawValue: value };
|
|
13431
|
+
}
|
|
13432
|
+
const validationResult = safeValidateTypes({ value, schema });
|
|
13433
|
+
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
|
|
13434
|
+
} catch (error) {
|
|
13435
|
+
return {
|
|
13436
|
+
success: false,
|
|
13437
|
+
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
|
|
13438
|
+
};
|
|
13439
|
+
}
|
|
13440
|
+
}
|
|
13441
|
+
function isParsableJson(input) {
|
|
13442
|
+
try {
|
|
13443
|
+
SecureJSON.parse(input);
|
|
13444
|
+
return true;
|
|
13445
|
+
} catch (e) {
|
|
13446
|
+
return false;
|
|
13447
|
+
}
|
|
13448
|
+
}
|
|
13449
|
+
var getOriginalFetch2 = () => globalThis.fetch;
|
|
13450
|
+
var postJsonToApi = async ({
|
|
13451
|
+
url,
|
|
13452
|
+
headers,
|
|
13453
|
+
body,
|
|
13454
|
+
failedResponseHandler,
|
|
13455
|
+
successfulResponseHandler,
|
|
13456
|
+
abortSignal,
|
|
13457
|
+
fetch
|
|
13458
|
+
}) => postToApi({
|
|
13459
|
+
url,
|
|
13460
|
+
headers: {
|
|
13461
|
+
"Content-Type": "application/json",
|
|
13462
|
+
...headers
|
|
13463
|
+
},
|
|
13464
|
+
body: {
|
|
13465
|
+
content: JSON.stringify(body),
|
|
13466
|
+
values: body
|
|
13467
|
+
},
|
|
13468
|
+
failedResponseHandler,
|
|
13469
|
+
successfulResponseHandler,
|
|
13470
|
+
abortSignal,
|
|
13471
|
+
fetch
|
|
13472
|
+
});
|
|
13473
|
+
var postToApi = async ({
|
|
13474
|
+
url,
|
|
13475
|
+
headers = {},
|
|
13476
|
+
body,
|
|
13477
|
+
successfulResponseHandler,
|
|
13478
|
+
failedResponseHandler,
|
|
13479
|
+
abortSignal,
|
|
13480
|
+
fetch = getOriginalFetch2()
|
|
13481
|
+
}) => {
|
|
13482
|
+
try {
|
|
13483
|
+
const response = await fetch(url, {
|
|
13484
|
+
method: "POST",
|
|
13485
|
+
headers: removeUndefinedEntries(headers),
|
|
13486
|
+
body: body.content,
|
|
13487
|
+
signal: abortSignal
|
|
13488
|
+
});
|
|
13489
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13490
|
+
if (!response.ok) {
|
|
13491
|
+
let errorInformation;
|
|
13492
|
+
try {
|
|
13493
|
+
errorInformation = await failedResponseHandler({
|
|
13494
|
+
response,
|
|
13495
|
+
url,
|
|
13496
|
+
requestBodyValues: body.values
|
|
13497
|
+
});
|
|
13498
|
+
} catch (error) {
|
|
13499
|
+
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
13500
|
+
throw error;
|
|
13501
|
+
}
|
|
13502
|
+
throw new APICallError({
|
|
13503
|
+
message: "Failed to process error response",
|
|
13504
|
+
cause: error,
|
|
13505
|
+
statusCode: response.status,
|
|
13506
|
+
url,
|
|
13507
|
+
responseHeaders,
|
|
13508
|
+
requestBodyValues: body.values
|
|
13509
|
+
});
|
|
13510
|
+
}
|
|
13511
|
+
throw errorInformation.value;
|
|
13512
|
+
}
|
|
13513
|
+
try {
|
|
13514
|
+
return await successfulResponseHandler({
|
|
13515
|
+
response,
|
|
13516
|
+
url,
|
|
13517
|
+
requestBodyValues: body.values
|
|
13518
|
+
});
|
|
13519
|
+
} catch (error) {
|
|
13520
|
+
if (error instanceof Error) {
|
|
13521
|
+
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
13522
|
+
throw error;
|
|
13523
|
+
}
|
|
13524
|
+
}
|
|
13525
|
+
throw new APICallError({
|
|
13526
|
+
message: "Failed to process successful response",
|
|
13527
|
+
cause: error,
|
|
13528
|
+
statusCode: response.status,
|
|
13529
|
+
url,
|
|
13530
|
+
responseHeaders,
|
|
13531
|
+
requestBodyValues: body.values
|
|
13532
|
+
});
|
|
13533
|
+
}
|
|
13534
|
+
} catch (error) {
|
|
13535
|
+
if (isAbortError(error)) {
|
|
13536
|
+
throw error;
|
|
13537
|
+
}
|
|
13538
|
+
if (error instanceof TypeError && error.message === "fetch failed") {
|
|
13539
|
+
const cause = error.cause;
|
|
13540
|
+
if (cause != null) {
|
|
13541
|
+
throw new APICallError({
|
|
13542
|
+
message: `Cannot connect to API: ${cause.message}`,
|
|
13543
|
+
cause,
|
|
13544
|
+
url,
|
|
13545
|
+
requestBodyValues: body.values,
|
|
13546
|
+
isRetryable: true
|
|
13547
|
+
// retry when network error
|
|
13548
|
+
});
|
|
13549
|
+
}
|
|
13550
|
+
}
|
|
13551
|
+
throw error;
|
|
13552
|
+
}
|
|
13553
|
+
};
|
|
13554
|
+
var createJsonErrorResponseHandler = ({
|
|
13555
|
+
errorSchema,
|
|
13556
|
+
errorToMessage,
|
|
13557
|
+
isRetryable
|
|
13558
|
+
}) => async ({ response, url, requestBodyValues }) => {
|
|
13559
|
+
const responseBody = await response.text();
|
|
13560
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13561
|
+
if (responseBody.trim() === "") {
|
|
13562
|
+
return {
|
|
13563
|
+
responseHeaders,
|
|
13564
|
+
value: new APICallError({
|
|
13565
|
+
message: response.statusText,
|
|
13566
|
+
url,
|
|
13567
|
+
requestBodyValues,
|
|
13568
|
+
statusCode: response.status,
|
|
13569
|
+
responseHeaders,
|
|
13570
|
+
responseBody,
|
|
13571
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
13572
|
+
})
|
|
13573
|
+
};
|
|
13574
|
+
}
|
|
13575
|
+
try {
|
|
13576
|
+
const parsedError = parseJSON({
|
|
13577
|
+
text: responseBody,
|
|
13578
|
+
schema: errorSchema
|
|
13579
|
+
});
|
|
13580
|
+
return {
|
|
13581
|
+
responseHeaders,
|
|
13582
|
+
value: new APICallError({
|
|
13583
|
+
message: errorToMessage(parsedError),
|
|
13584
|
+
url,
|
|
13585
|
+
requestBodyValues,
|
|
13586
|
+
statusCode: response.status,
|
|
13587
|
+
responseHeaders,
|
|
13588
|
+
responseBody,
|
|
13589
|
+
data: parsedError,
|
|
13590
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
|
|
13591
|
+
})
|
|
13592
|
+
};
|
|
13593
|
+
} catch (parseError) {
|
|
13594
|
+
return {
|
|
13595
|
+
responseHeaders,
|
|
13596
|
+
value: new APICallError({
|
|
13597
|
+
message: response.statusText,
|
|
13598
|
+
url,
|
|
13599
|
+
requestBodyValues,
|
|
13600
|
+
statusCode: response.status,
|
|
13601
|
+
responseHeaders,
|
|
13602
|
+
responseBody,
|
|
13603
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
13604
|
+
})
|
|
13605
|
+
};
|
|
13606
|
+
}
|
|
13607
|
+
};
|
|
13608
|
+
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
13609
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13610
|
+
if (response.body == null) {
|
|
13611
|
+
throw new EmptyResponseBodyError({});
|
|
13612
|
+
}
|
|
13613
|
+
return {
|
|
13614
|
+
responseHeaders,
|
|
13615
|
+
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
|
|
13616
|
+
new TransformStream({
|
|
13617
|
+
transform({ data }, controller) {
|
|
13618
|
+
if (data === "[DONE]") {
|
|
13619
|
+
return;
|
|
13620
|
+
}
|
|
13621
|
+
controller.enqueue(
|
|
13622
|
+
safeParseJSON({
|
|
13623
|
+
text: data,
|
|
13624
|
+
schema: chunkSchema
|
|
13625
|
+
})
|
|
13626
|
+
);
|
|
13627
|
+
}
|
|
13628
|
+
})
|
|
13629
|
+
)
|
|
13630
|
+
};
|
|
13631
|
+
};
|
|
13632
|
+
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
13633
|
+
const responseBody = await response.text();
|
|
13634
|
+
const parsedResult = safeParseJSON({
|
|
13635
|
+
text: responseBody,
|
|
13636
|
+
schema: responseSchema
|
|
13637
|
+
});
|
|
13638
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
13639
|
+
if (!parsedResult.success) {
|
|
13640
|
+
throw new APICallError({
|
|
13641
|
+
message: "Invalid JSON response",
|
|
13642
|
+
cause: parsedResult.error,
|
|
13643
|
+
statusCode: response.status,
|
|
13644
|
+
responseHeaders,
|
|
13645
|
+
responseBody,
|
|
13646
|
+
url,
|
|
13647
|
+
requestBodyValues
|
|
13648
|
+
});
|
|
13649
|
+
}
|
|
13650
|
+
return {
|
|
13651
|
+
responseHeaders,
|
|
13652
|
+
value: parsedResult.value,
|
|
13653
|
+
rawValue: parsedResult.rawValue
|
|
13654
|
+
};
|
|
13655
|
+
};
|
|
13656
|
+
|
|
13657
|
+
// src/uint8-utils.ts
|
|
13658
|
+
var { btoa} = globalThis;
|
|
13659
|
+
function convertUint8ArrayToBase64(array) {
|
|
13660
|
+
let latin1string = "";
|
|
13661
|
+
for (let i = 0; i < array.length; i++) {
|
|
13662
|
+
latin1string += String.fromCodePoint(array[i]);
|
|
13663
|
+
}
|
|
13664
|
+
return btoa(latin1string);
|
|
13665
|
+
}
|
|
13666
|
+
|
|
13667
|
+
// src/without-trailing-slash.ts
|
|
13668
|
+
function withoutTrailingSlash(url) {
|
|
13669
|
+
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
13670
|
+
}
|
|
13671
|
+
|
|
13672
|
+
var __defProp = Object.defineProperty;
|
|
13673
|
+
var __defProps = Object.defineProperties;
|
|
13674
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
13675
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
13676
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
13677
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
13678
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
13679
|
+
var __spreadValues = (a, b) => {
|
|
13680
|
+
for (var prop in b || (b = {}))
|
|
13681
|
+
if (__hasOwnProp.call(b, prop))
|
|
13682
|
+
__defNormalProp(a, prop, b[prop]);
|
|
13683
|
+
if (__getOwnPropSymbols)
|
|
13684
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
13685
|
+
if (__propIsEnum.call(b, prop))
|
|
13686
|
+
__defNormalProp(a, prop, b[prop]);
|
|
13687
|
+
}
|
|
13688
|
+
return a;
|
|
13689
|
+
};
|
|
13690
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
13691
|
+
var __objRest = (source, exclude) => {
|
|
13692
|
+
var target = {};
|
|
13693
|
+
for (var prop in source)
|
|
13694
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
13695
|
+
target[prop] = source[prop];
|
|
13696
|
+
if (source != null && __getOwnPropSymbols)
|
|
13697
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
13698
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
13699
|
+
target[prop] = source[prop];
|
|
13700
|
+
}
|
|
13701
|
+
return target;
|
|
13702
|
+
};
|
|
13703
|
+
function getCacheControl(providerMetadata) {
|
|
13704
|
+
var _a, _b, _c;
|
|
13705
|
+
const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
|
|
13706
|
+
const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
|
|
13707
|
+
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;
|
|
13708
|
+
}
|
|
13709
|
+
function convertToOpenRouterChatMessages(prompt) {
|
|
13710
|
+
var _a, _b, _c;
|
|
13711
|
+
const messages = [];
|
|
13712
|
+
for (const { role, content, providerMetadata } of prompt) {
|
|
13713
|
+
switch (role) {
|
|
13714
|
+
case "system": {
|
|
13715
|
+
messages.push({
|
|
13716
|
+
role: "system",
|
|
13717
|
+
content,
|
|
13718
|
+
cache_control: getCacheControl(providerMetadata)
|
|
13719
|
+
});
|
|
13720
|
+
break;
|
|
13721
|
+
}
|
|
13722
|
+
case "user": {
|
|
13723
|
+
if (content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
|
|
13724
|
+
messages.push({
|
|
13725
|
+
role: "user",
|
|
13726
|
+
content: content[0].text,
|
|
13727
|
+
cache_control: (_b = getCacheControl(providerMetadata)) != null ? _b : getCacheControl(content[0].providerMetadata)
|
|
13728
|
+
});
|
|
13729
|
+
break;
|
|
13730
|
+
}
|
|
13731
|
+
const messageCacheControl = getCacheControl(providerMetadata);
|
|
13732
|
+
const contentParts = content.map(
|
|
13733
|
+
(part) => {
|
|
13734
|
+
var _a2, _b2, _c2, _d;
|
|
13735
|
+
switch (part.type) {
|
|
13736
|
+
case "text":
|
|
13737
|
+
return {
|
|
13738
|
+
type: "text",
|
|
13739
|
+
text: part.text,
|
|
13740
|
+
// For text parts, only use part-specific cache control
|
|
13741
|
+
cache_control: (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl
|
|
13742
|
+
};
|
|
13743
|
+
case "image":
|
|
13744
|
+
return {
|
|
13745
|
+
type: "image_url",
|
|
13746
|
+
image_url: {
|
|
13747
|
+
url: part.image instanceof URL ? part.image.toString() : `data:${(_b2 = part.mimeType) != null ? _b2 : "image/jpeg"};base64,${convertUint8ArrayToBase64(
|
|
13748
|
+
part.image
|
|
13749
|
+
)}`
|
|
13750
|
+
},
|
|
13751
|
+
// For image parts, use part-specific or message-level cache control
|
|
13752
|
+
cache_control: (_c2 = getCacheControl(part.providerMetadata)) != null ? _c2 : messageCacheControl
|
|
13753
|
+
};
|
|
13754
|
+
case "file":
|
|
13755
|
+
return {
|
|
13756
|
+
type: "text",
|
|
13757
|
+
text: part.data instanceof URL ? part.data.toString() : part.data,
|
|
13758
|
+
cache_control: (_d = getCacheControl(part.providerMetadata)) != null ? _d : messageCacheControl
|
|
13759
|
+
};
|
|
13760
|
+
default: {
|
|
13761
|
+
const _exhaustiveCheck = part;
|
|
13762
|
+
throw new Error(
|
|
13763
|
+
`Unsupported content part type: ${_exhaustiveCheck}`
|
|
13764
|
+
);
|
|
13765
|
+
}
|
|
13766
|
+
}
|
|
13767
|
+
}
|
|
13768
|
+
);
|
|
13769
|
+
messages.push({
|
|
13770
|
+
role: "user",
|
|
13771
|
+
content: contentParts
|
|
13772
|
+
});
|
|
13773
|
+
break;
|
|
13774
|
+
}
|
|
13775
|
+
case "assistant": {
|
|
13776
|
+
let text = "";
|
|
13777
|
+
const toolCalls = [];
|
|
13778
|
+
for (const part of content) {
|
|
13779
|
+
switch (part.type) {
|
|
13780
|
+
case "text": {
|
|
13781
|
+
text += part.text;
|
|
13782
|
+
break;
|
|
13783
|
+
}
|
|
13784
|
+
case "tool-call": {
|
|
13785
|
+
toolCalls.push({
|
|
13786
|
+
id: part.toolCallId,
|
|
13787
|
+
type: "function",
|
|
13788
|
+
function: {
|
|
13789
|
+
name: part.toolName,
|
|
13790
|
+
arguments: JSON.stringify(part.args)
|
|
13791
|
+
}
|
|
13792
|
+
});
|
|
13793
|
+
break;
|
|
13794
|
+
}
|
|
13795
|
+
// TODO: Handle reasoning and redacted-reasoning
|
|
13796
|
+
case "reasoning":
|
|
13797
|
+
case "redacted-reasoning":
|
|
13798
|
+
break;
|
|
13799
|
+
default: {
|
|
13800
|
+
const _exhaustiveCheck = part;
|
|
13801
|
+
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
|
13802
|
+
}
|
|
13803
|
+
}
|
|
13804
|
+
}
|
|
13805
|
+
messages.push({
|
|
13806
|
+
role: "assistant",
|
|
13807
|
+
content: text,
|
|
13808
|
+
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
|
|
13809
|
+
cache_control: getCacheControl(providerMetadata)
|
|
13810
|
+
});
|
|
13811
|
+
break;
|
|
13812
|
+
}
|
|
13813
|
+
case "tool": {
|
|
13814
|
+
for (const toolResponse of content) {
|
|
13815
|
+
messages.push({
|
|
13816
|
+
role: "tool",
|
|
13817
|
+
tool_call_id: toolResponse.toolCallId,
|
|
13818
|
+
content: JSON.stringify(toolResponse.result),
|
|
13819
|
+
cache_control: (_c = getCacheControl(providerMetadata)) != null ? _c : getCacheControl(toolResponse.providerMetadata)
|
|
13820
|
+
});
|
|
13821
|
+
}
|
|
13822
|
+
break;
|
|
13823
|
+
}
|
|
13824
|
+
default: {
|
|
13825
|
+
const _exhaustiveCheck = role;
|
|
13826
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
|
13827
|
+
}
|
|
13828
|
+
}
|
|
13829
|
+
}
|
|
13830
|
+
return messages;
|
|
13831
|
+
}
|
|
13832
|
+
|
|
13833
|
+
// src/map-openrouter-chat-logprobs.ts
|
|
13834
|
+
function mapOpenRouterChatLogProbsOutput(logprobs) {
|
|
13835
|
+
var _a, _b;
|
|
13836
|
+
return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
|
|
13837
|
+
token,
|
|
13838
|
+
logprob,
|
|
13839
|
+
topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
|
|
13840
|
+
token: token2,
|
|
13841
|
+
logprob: logprob2
|
|
13842
|
+
})) : []
|
|
13843
|
+
}))) != null ? _b : void 0;
|
|
13844
|
+
}
|
|
13845
|
+
|
|
13846
|
+
// src/map-openrouter-finish-reason.ts
|
|
13847
|
+
function mapOpenRouterFinishReason(finishReason) {
|
|
13848
|
+
switch (finishReason) {
|
|
13849
|
+
case "stop":
|
|
13850
|
+
return "stop";
|
|
13851
|
+
case "length":
|
|
13852
|
+
return "length";
|
|
13853
|
+
case "content_filter":
|
|
13854
|
+
return "content-filter";
|
|
13855
|
+
case "function_call":
|
|
13856
|
+
case "tool_calls":
|
|
13857
|
+
return "tool-calls";
|
|
13858
|
+
default:
|
|
13859
|
+
return "unknown";
|
|
13860
|
+
}
|
|
13861
|
+
}
|
|
13862
|
+
var OpenRouterErrorResponseSchema = z.object({
|
|
13863
|
+
error: z.object({
|
|
13864
|
+
message: z.string(),
|
|
13865
|
+
type: z.string(),
|
|
13866
|
+
param: z.any().nullable(),
|
|
13867
|
+
code: z.string().nullable()
|
|
13868
|
+
})
|
|
13869
|
+
});
|
|
13870
|
+
var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
|
|
13871
|
+
errorSchema: OpenRouterErrorResponseSchema,
|
|
13872
|
+
errorToMessage: (data) => data.error.message
|
|
13873
|
+
});
|
|
13874
|
+
|
|
13875
|
+
// src/openrouter-chat-language-model.ts
|
|
13876
|
+
function isFunctionTool(tool) {
|
|
13877
|
+
return "parameters" in tool;
|
|
13878
|
+
}
|
|
13879
|
+
var OpenRouterChatLanguageModel = class {
|
|
13880
|
+
constructor(modelId, settings, config) {
|
|
13881
|
+
this.specificationVersion = "v1";
|
|
13882
|
+
this.defaultObjectGenerationMode = "tool";
|
|
13883
|
+
this.modelId = modelId;
|
|
13884
|
+
this.settings = settings;
|
|
13885
|
+
this.config = config;
|
|
13886
|
+
}
|
|
13887
|
+
get provider() {
|
|
13888
|
+
return this.config.provider;
|
|
13889
|
+
}
|
|
13890
|
+
getArgs({
|
|
13891
|
+
mode,
|
|
13892
|
+
prompt,
|
|
13893
|
+
maxTokens,
|
|
13894
|
+
temperature,
|
|
13895
|
+
topP,
|
|
13896
|
+
frequencyPenalty,
|
|
13897
|
+
presencePenalty,
|
|
13898
|
+
seed,
|
|
13899
|
+
stopSequences,
|
|
13900
|
+
responseFormat,
|
|
13901
|
+
topK,
|
|
13902
|
+
providerMetadata
|
|
13903
|
+
}) {
|
|
13904
|
+
var _a;
|
|
13905
|
+
const type = mode.type;
|
|
13906
|
+
const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
|
|
13907
|
+
const baseArgs = __spreadValues(__spreadValues(__spreadValues({
|
|
13908
|
+
// model id:
|
|
13909
|
+
model: this.modelId,
|
|
13910
|
+
models: this.settings.models,
|
|
13911
|
+
// model specific settings:
|
|
13912
|
+
logit_bias: this.settings.logitBias,
|
|
13913
|
+
logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
|
|
13914
|
+
top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
|
|
13915
|
+
user: this.settings.user,
|
|
13916
|
+
parallel_tool_calls: this.settings.parallelToolCalls,
|
|
13917
|
+
// standardized settings:
|
|
13918
|
+
max_tokens: maxTokens,
|
|
13919
|
+
temperature,
|
|
13920
|
+
top_p: topP,
|
|
13921
|
+
frequency_penalty: frequencyPenalty,
|
|
13922
|
+
presence_penalty: presencePenalty,
|
|
13923
|
+
seed,
|
|
13924
|
+
stop: stopSequences,
|
|
13925
|
+
response_format: responseFormat,
|
|
13926
|
+
top_k: topK,
|
|
13927
|
+
// messages:
|
|
13928
|
+
messages: convertToOpenRouterChatMessages(prompt),
|
|
13929
|
+
// OpenRouter specific settings:
|
|
13930
|
+
include_reasoning: this.settings.includeReasoning,
|
|
13931
|
+
reasoning: this.settings.reasoning
|
|
13932
|
+
}, this.config.extraBody), this.settings.extraBody), extraCallingBody);
|
|
13933
|
+
switch (type) {
|
|
13934
|
+
case "regular": {
|
|
13935
|
+
return __spreadValues(__spreadValues({}, baseArgs), prepareToolsAndToolChoice(mode));
|
|
13936
|
+
}
|
|
13937
|
+
case "object-json": {
|
|
13938
|
+
return __spreadProps(__spreadValues({}, baseArgs), {
|
|
13939
|
+
response_format: { type: "json_object" }
|
|
13940
|
+
});
|
|
13941
|
+
}
|
|
13942
|
+
case "object-tool": {
|
|
13943
|
+
return __spreadProps(__spreadValues({}, baseArgs), {
|
|
13944
|
+
tool_choice: { type: "function", function: { name: mode.tool.name } },
|
|
13945
|
+
tools: [
|
|
13946
|
+
{
|
|
13947
|
+
type: "function",
|
|
13948
|
+
function: {
|
|
13949
|
+
name: mode.tool.name,
|
|
13950
|
+
description: mode.tool.description,
|
|
13951
|
+
parameters: mode.tool.parameters
|
|
13952
|
+
}
|
|
13953
|
+
}
|
|
13954
|
+
]
|
|
13955
|
+
});
|
|
13956
|
+
}
|
|
13957
|
+
// Handle all non-text types with a single default case
|
|
13958
|
+
default: {
|
|
13959
|
+
const _exhaustiveCheck = type;
|
|
13960
|
+
throw new UnsupportedFunctionalityError({
|
|
13961
|
+
functionality: `${_exhaustiveCheck} mode`
|
|
13962
|
+
});
|
|
13963
|
+
}
|
|
13964
|
+
}
|
|
13965
|
+
}
|
|
13966
|
+
async doGenerate(options) {
|
|
13967
|
+
var _b, _c, _d, _e, _f, _g, _h;
|
|
13968
|
+
const args = this.getArgs(options);
|
|
13969
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
13970
|
+
url: this.config.url({
|
|
13971
|
+
path: "/chat/completions",
|
|
13972
|
+
modelId: this.modelId
|
|
13973
|
+
}),
|
|
13974
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
13975
|
+
body: args,
|
|
13976
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
13977
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
13978
|
+
OpenRouterNonStreamChatCompletionResponseSchema
|
|
13979
|
+
),
|
|
13980
|
+
abortSignal: options.abortSignal,
|
|
13981
|
+
fetch: this.config.fetch
|
|
13982
|
+
});
|
|
13983
|
+
const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
|
|
13984
|
+
const choice = response.choices[0];
|
|
13985
|
+
if (!choice) {
|
|
13986
|
+
throw new Error("No choice in response");
|
|
13987
|
+
}
|
|
13988
|
+
return {
|
|
13989
|
+
response: {
|
|
13990
|
+
id: response.id,
|
|
13991
|
+
modelId: response.model
|
|
13992
|
+
},
|
|
13993
|
+
text: (_b = choice.message.content) != null ? _b : void 0,
|
|
13994
|
+
reasoning: (_c = choice.message.reasoning) != null ? _c : void 0,
|
|
13995
|
+
toolCalls: (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
|
|
13996
|
+
var _a2;
|
|
13997
|
+
return {
|
|
13998
|
+
toolCallType: "function",
|
|
13999
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
14000
|
+
toolName: toolCall.function.name,
|
|
14001
|
+
args: toolCall.function.arguments
|
|
14002
|
+
};
|
|
14003
|
+
}),
|
|
14004
|
+
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
|
|
14005
|
+
usage: {
|
|
14006
|
+
promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : 0,
|
|
14007
|
+
completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0
|
|
14008
|
+
},
|
|
14009
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14010
|
+
rawResponse: { headers: responseHeaders },
|
|
14011
|
+
warnings: [],
|
|
14012
|
+
logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
|
|
14013
|
+
};
|
|
14014
|
+
}
|
|
14015
|
+
async doStream(options) {
|
|
14016
|
+
const args = this.getArgs(options);
|
|
14017
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14018
|
+
url: this.config.url({
|
|
14019
|
+
path: "/chat/completions",
|
|
14020
|
+
modelId: this.modelId
|
|
14021
|
+
}),
|
|
14022
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14023
|
+
body: __spreadProps(__spreadValues({}, args), {
|
|
14024
|
+
stream: true,
|
|
14025
|
+
// only include stream_options when in strict compatibility mode:
|
|
14026
|
+
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
14027
|
+
}),
|
|
14028
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14029
|
+
successfulResponseHandler: createEventSourceResponseHandler(
|
|
14030
|
+
OpenRouterStreamChatCompletionChunkSchema
|
|
14031
|
+
),
|
|
14032
|
+
abortSignal: options.abortSignal,
|
|
14033
|
+
fetch: this.config.fetch
|
|
14034
|
+
});
|
|
14035
|
+
const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
|
|
14036
|
+
const toolCalls = [];
|
|
14037
|
+
let finishReason = "other";
|
|
14038
|
+
let usage = {
|
|
14039
|
+
promptTokens: Number.NaN,
|
|
14040
|
+
completionTokens: Number.NaN
|
|
14041
|
+
};
|
|
14042
|
+
let logprobs;
|
|
14043
|
+
return {
|
|
14044
|
+
stream: response.pipeThrough(
|
|
14045
|
+
new TransformStream({
|
|
14046
|
+
transform(chunk, controller) {
|
|
14047
|
+
var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
|
|
14048
|
+
if (!chunk.success) {
|
|
14049
|
+
finishReason = "error";
|
|
14050
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
|
14051
|
+
return;
|
|
14052
|
+
}
|
|
14053
|
+
const value = chunk.value;
|
|
14054
|
+
if ("error" in value) {
|
|
14055
|
+
finishReason = "error";
|
|
14056
|
+
controller.enqueue({ type: "error", error: value.error });
|
|
14057
|
+
return;
|
|
14058
|
+
}
|
|
14059
|
+
if (value.id) {
|
|
14060
|
+
controller.enqueue({
|
|
14061
|
+
type: "response-metadata",
|
|
14062
|
+
id: value.id
|
|
14063
|
+
});
|
|
14064
|
+
}
|
|
14065
|
+
if (value.model) {
|
|
14066
|
+
controller.enqueue({
|
|
14067
|
+
type: "response-metadata",
|
|
14068
|
+
modelId: value.model
|
|
14069
|
+
});
|
|
14070
|
+
}
|
|
14071
|
+
if (value.usage != null) {
|
|
14072
|
+
usage = {
|
|
14073
|
+
promptTokens: value.usage.prompt_tokens,
|
|
14074
|
+
completionTokens: value.usage.completion_tokens
|
|
14075
|
+
};
|
|
14076
|
+
}
|
|
14077
|
+
const choice = value.choices[0];
|
|
14078
|
+
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
14079
|
+
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
14080
|
+
}
|
|
14081
|
+
if ((choice == null ? void 0 : choice.delta) == null) {
|
|
14082
|
+
return;
|
|
14083
|
+
}
|
|
14084
|
+
const delta = choice.delta;
|
|
14085
|
+
if (delta.content != null) {
|
|
14086
|
+
controller.enqueue({
|
|
14087
|
+
type: "text-delta",
|
|
14088
|
+
textDelta: delta.content
|
|
14089
|
+
});
|
|
14090
|
+
}
|
|
14091
|
+
if (delta.reasoning != null) {
|
|
14092
|
+
controller.enqueue({
|
|
14093
|
+
type: "reasoning",
|
|
14094
|
+
textDelta: delta.reasoning
|
|
14095
|
+
});
|
|
14096
|
+
}
|
|
14097
|
+
const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
|
|
14098
|
+
choice == null ? void 0 : choice.logprobs
|
|
14099
|
+
);
|
|
14100
|
+
if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
|
|
14101
|
+
if (logprobs === void 0) logprobs = [];
|
|
14102
|
+
logprobs.push(...mappedLogprobs);
|
|
14103
|
+
}
|
|
14104
|
+
if (delta.tool_calls != null) {
|
|
14105
|
+
for (const toolCallDelta of delta.tool_calls) {
|
|
14106
|
+
const index = toolCallDelta.index;
|
|
14107
|
+
if (toolCalls[index] == null) {
|
|
14108
|
+
if (toolCallDelta.type !== "function") {
|
|
14109
|
+
throw new InvalidResponseDataError({
|
|
14110
|
+
data: toolCallDelta,
|
|
14111
|
+
message: `Expected 'function' type.`
|
|
14112
|
+
});
|
|
14113
|
+
}
|
|
14114
|
+
if (toolCallDelta.id == null) {
|
|
14115
|
+
throw new InvalidResponseDataError({
|
|
14116
|
+
data: toolCallDelta,
|
|
14117
|
+
message: `Expected 'id' to be a string.`
|
|
14118
|
+
});
|
|
14119
|
+
}
|
|
14120
|
+
if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
|
|
14121
|
+
throw new InvalidResponseDataError({
|
|
14122
|
+
data: toolCallDelta,
|
|
14123
|
+
message: `Expected 'function.name' to be a string.`
|
|
14124
|
+
});
|
|
14125
|
+
}
|
|
14126
|
+
toolCalls[index] = {
|
|
14127
|
+
id: toolCallDelta.id,
|
|
14128
|
+
type: "function",
|
|
14129
|
+
function: {
|
|
14130
|
+
name: toolCallDelta.function.name,
|
|
14131
|
+
arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
|
|
14132
|
+
},
|
|
14133
|
+
sent: false
|
|
14134
|
+
};
|
|
14135
|
+
const toolCall2 = toolCalls[index];
|
|
14136
|
+
if (toolCall2 == null) {
|
|
14137
|
+
throw new Error("Tool call is missing");
|
|
14138
|
+
}
|
|
14139
|
+
if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
|
|
14140
|
+
controller.enqueue({
|
|
14141
|
+
type: "tool-call-delta",
|
|
14142
|
+
toolCallType: "function",
|
|
14143
|
+
toolCallId: toolCall2.id,
|
|
14144
|
+
toolName: toolCall2.function.name,
|
|
14145
|
+
argsTextDelta: toolCall2.function.arguments
|
|
14146
|
+
});
|
|
14147
|
+
controller.enqueue({
|
|
14148
|
+
type: "tool-call",
|
|
14149
|
+
toolCallType: "function",
|
|
14150
|
+
toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
|
|
14151
|
+
toolName: toolCall2.function.name,
|
|
14152
|
+
args: toolCall2.function.arguments
|
|
14153
|
+
});
|
|
14154
|
+
toolCall2.sent = true;
|
|
14155
|
+
}
|
|
14156
|
+
continue;
|
|
14157
|
+
}
|
|
14158
|
+
const toolCall = toolCalls[index];
|
|
14159
|
+
if (toolCall == null) {
|
|
14160
|
+
throw new Error("Tool call is missing");
|
|
14161
|
+
}
|
|
14162
|
+
if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
|
|
14163
|
+
toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
|
|
14164
|
+
}
|
|
14165
|
+
controller.enqueue({
|
|
14166
|
+
type: "tool-call-delta",
|
|
14167
|
+
toolCallType: "function",
|
|
14168
|
+
toolCallId: toolCall.id,
|
|
14169
|
+
toolName: toolCall.function.name,
|
|
14170
|
+
argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
|
|
14171
|
+
});
|
|
14172
|
+
if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
|
|
14173
|
+
controller.enqueue({
|
|
14174
|
+
type: "tool-call",
|
|
14175
|
+
toolCallType: "function",
|
|
14176
|
+
toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
|
|
14177
|
+
toolName: toolCall.function.name,
|
|
14178
|
+
args: toolCall.function.arguments
|
|
14179
|
+
});
|
|
14180
|
+
toolCall.sent = true;
|
|
14181
|
+
}
|
|
14182
|
+
}
|
|
14183
|
+
}
|
|
14184
|
+
},
|
|
14185
|
+
flush(controller) {
|
|
14186
|
+
var _a2;
|
|
14187
|
+
if (finishReason === "tool-calls") {
|
|
14188
|
+
for (const toolCall of toolCalls) {
|
|
14189
|
+
if (!toolCall.sent) {
|
|
14190
|
+
controller.enqueue({
|
|
14191
|
+
type: "tool-call",
|
|
14192
|
+
toolCallType: "function",
|
|
14193
|
+
toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
|
|
14194
|
+
toolName: toolCall.function.name,
|
|
14195
|
+
// Coerce invalid arguments to an empty JSON object
|
|
14196
|
+
args: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
|
|
14197
|
+
});
|
|
14198
|
+
toolCall.sent = true;
|
|
14199
|
+
}
|
|
14200
|
+
}
|
|
14201
|
+
}
|
|
14202
|
+
controller.enqueue({
|
|
14203
|
+
type: "finish",
|
|
14204
|
+
finishReason,
|
|
14205
|
+
logprobs,
|
|
14206
|
+
usage
|
|
14207
|
+
});
|
|
14208
|
+
}
|
|
14209
|
+
})
|
|
14210
|
+
),
|
|
14211
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14212
|
+
rawResponse: { headers: responseHeaders },
|
|
14213
|
+
warnings: []
|
|
14214
|
+
};
|
|
14215
|
+
}
|
|
14216
|
+
};
|
|
14217
|
+
var OpenRouterChatCompletionBaseResponseSchema = z.object({
|
|
14218
|
+
id: z.string().optional(),
|
|
14219
|
+
model: z.string().optional(),
|
|
14220
|
+
usage: z.object({
|
|
14221
|
+
prompt_tokens: z.number(),
|
|
14222
|
+
completion_tokens: z.number(),
|
|
14223
|
+
total_tokens: z.number()
|
|
14224
|
+
}).nullish()
|
|
14225
|
+
});
|
|
14226
|
+
var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
14227
|
+
choices: z.array(
|
|
14228
|
+
z.object({
|
|
14229
|
+
message: z.object({
|
|
14230
|
+
role: z.literal("assistant"),
|
|
14231
|
+
content: z.string().nullable().optional(),
|
|
14232
|
+
reasoning: z.string().nullable().optional(),
|
|
14233
|
+
tool_calls: z.array(
|
|
14234
|
+
z.object({
|
|
14235
|
+
id: z.string().optional().nullable(),
|
|
14236
|
+
type: z.literal("function"),
|
|
14237
|
+
function: z.object({
|
|
14238
|
+
name: z.string(),
|
|
14239
|
+
arguments: z.string()
|
|
14240
|
+
})
|
|
14241
|
+
})
|
|
14242
|
+
).optional()
|
|
14243
|
+
}),
|
|
14244
|
+
index: z.number(),
|
|
14245
|
+
logprobs: z.object({
|
|
14246
|
+
content: z.array(
|
|
14247
|
+
z.object({
|
|
14248
|
+
token: z.string(),
|
|
14249
|
+
logprob: z.number(),
|
|
14250
|
+
top_logprobs: z.array(
|
|
14251
|
+
z.object({
|
|
14252
|
+
token: z.string(),
|
|
14253
|
+
logprob: z.number()
|
|
14254
|
+
})
|
|
14255
|
+
)
|
|
14256
|
+
})
|
|
14257
|
+
).nullable()
|
|
14258
|
+
}).nullable().optional(),
|
|
14259
|
+
finish_reason: z.string().optional().nullable()
|
|
14260
|
+
})
|
|
14261
|
+
)
|
|
14262
|
+
});
|
|
14263
|
+
var OpenRouterStreamChatCompletionChunkSchema = z.union([
|
|
14264
|
+
OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
14265
|
+
choices: z.array(
|
|
14266
|
+
z.object({
|
|
14267
|
+
delta: z.object({
|
|
14268
|
+
role: z.enum(["assistant"]).optional(),
|
|
14269
|
+
content: z.string().nullish(),
|
|
14270
|
+
reasoning: z.string().nullish().optional(),
|
|
14271
|
+
tool_calls: z.array(
|
|
14272
|
+
z.object({
|
|
14273
|
+
index: z.number(),
|
|
14274
|
+
id: z.string().nullish(),
|
|
14275
|
+
type: z.literal("function").optional(),
|
|
14276
|
+
function: z.object({
|
|
14277
|
+
name: z.string().nullish(),
|
|
14278
|
+
arguments: z.string().nullish()
|
|
14279
|
+
})
|
|
14280
|
+
})
|
|
14281
|
+
).nullish()
|
|
14282
|
+
}).nullish(),
|
|
14283
|
+
logprobs: z.object({
|
|
14284
|
+
content: z.array(
|
|
14285
|
+
z.object({
|
|
14286
|
+
token: z.string(),
|
|
14287
|
+
logprob: z.number(),
|
|
14288
|
+
top_logprobs: z.array(
|
|
14289
|
+
z.object({
|
|
14290
|
+
token: z.string(),
|
|
14291
|
+
logprob: z.number()
|
|
14292
|
+
})
|
|
14293
|
+
)
|
|
14294
|
+
})
|
|
14295
|
+
).nullable()
|
|
14296
|
+
}).nullish(),
|
|
14297
|
+
finish_reason: z.string().nullable().optional(),
|
|
14298
|
+
index: z.number()
|
|
14299
|
+
})
|
|
14300
|
+
)
|
|
14301
|
+
}),
|
|
14302
|
+
OpenRouterErrorResponseSchema
|
|
14303
|
+
]);
|
|
14304
|
+
function prepareToolsAndToolChoice(mode) {
|
|
14305
|
+
var _a;
|
|
14306
|
+
const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
|
|
14307
|
+
if (tools == null) {
|
|
14308
|
+
return { tools: void 0, tool_choice: void 0 };
|
|
14309
|
+
}
|
|
14310
|
+
const mappedTools = tools.map((tool) => {
|
|
14311
|
+
if (isFunctionTool(tool)) {
|
|
14312
|
+
return {
|
|
14313
|
+
type: "function",
|
|
14314
|
+
function: {
|
|
14315
|
+
name: tool.name,
|
|
14316
|
+
description: tool.description,
|
|
14317
|
+
parameters: tool.parameters
|
|
14318
|
+
}
|
|
14319
|
+
};
|
|
14320
|
+
} else {
|
|
14321
|
+
return {
|
|
14322
|
+
type: "function",
|
|
14323
|
+
function: {
|
|
14324
|
+
name: tool.name
|
|
14325
|
+
}
|
|
14326
|
+
};
|
|
14327
|
+
}
|
|
14328
|
+
});
|
|
14329
|
+
const toolChoice = mode.toolChoice;
|
|
14330
|
+
if (toolChoice == null) {
|
|
14331
|
+
return { tools: mappedTools, tool_choice: void 0 };
|
|
14332
|
+
}
|
|
14333
|
+
const type = toolChoice.type;
|
|
14334
|
+
switch (type) {
|
|
14335
|
+
case "auto":
|
|
14336
|
+
case "none":
|
|
14337
|
+
case "required":
|
|
14338
|
+
return { tools: mappedTools, tool_choice: type };
|
|
14339
|
+
case "tool":
|
|
14340
|
+
return {
|
|
14341
|
+
tools: mappedTools,
|
|
14342
|
+
tool_choice: {
|
|
14343
|
+
type: "function",
|
|
14344
|
+
function: {
|
|
14345
|
+
name: toolChoice.toolName
|
|
14346
|
+
}
|
|
14347
|
+
}
|
|
14348
|
+
};
|
|
14349
|
+
default: {
|
|
14350
|
+
const _exhaustiveCheck = type;
|
|
14351
|
+
throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
|
|
14352
|
+
}
|
|
14353
|
+
}
|
|
14354
|
+
}
|
|
14355
|
+
function convertToOpenRouterCompletionPrompt({
|
|
14356
|
+
prompt,
|
|
14357
|
+
inputFormat,
|
|
14358
|
+
user = "user",
|
|
14359
|
+
assistant = "assistant"
|
|
14360
|
+
}) {
|
|
14361
|
+
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") {
|
|
14362
|
+
return { prompt: prompt[0].content[0].text };
|
|
14363
|
+
}
|
|
14364
|
+
let text = "";
|
|
14365
|
+
if (prompt[0] && prompt[0].role === "system") {
|
|
14366
|
+
text += `${prompt[0].content}
|
|
14367
|
+
|
|
14368
|
+
`;
|
|
14369
|
+
prompt = prompt.slice(1);
|
|
14370
|
+
}
|
|
14371
|
+
for (const { role, content } of prompt) {
|
|
14372
|
+
switch (role) {
|
|
14373
|
+
case "system": {
|
|
14374
|
+
throw new InvalidPromptError({
|
|
14375
|
+
message: "Unexpected system message in prompt: ${content}",
|
|
14376
|
+
prompt
|
|
14377
|
+
});
|
|
14378
|
+
}
|
|
14379
|
+
case "user": {
|
|
14380
|
+
const userMessage = content.map((part) => {
|
|
14381
|
+
switch (part.type) {
|
|
14382
|
+
case "text": {
|
|
14383
|
+
return part.text;
|
|
14384
|
+
}
|
|
14385
|
+
case "image": {
|
|
14386
|
+
throw new UnsupportedFunctionalityError({
|
|
14387
|
+
functionality: "images"
|
|
14388
|
+
});
|
|
14389
|
+
}
|
|
14390
|
+
case "file": {
|
|
14391
|
+
throw new UnsupportedFunctionalityError({
|
|
14392
|
+
functionality: "file attachments"
|
|
14393
|
+
});
|
|
14394
|
+
}
|
|
14395
|
+
default: {
|
|
14396
|
+
const _exhaustiveCheck = part;
|
|
14397
|
+
throw new Error(
|
|
14398
|
+
`Unsupported content type: ${_exhaustiveCheck}`
|
|
14399
|
+
);
|
|
14400
|
+
}
|
|
14401
|
+
}
|
|
14402
|
+
}).join("");
|
|
14403
|
+
text += `${user}:
|
|
14404
|
+
${userMessage}
|
|
14405
|
+
|
|
14406
|
+
`;
|
|
14407
|
+
break;
|
|
14408
|
+
}
|
|
14409
|
+
case "assistant": {
|
|
14410
|
+
const assistantMessage = content.map((part) => {
|
|
14411
|
+
switch (part.type) {
|
|
14412
|
+
case "text": {
|
|
14413
|
+
return part.text;
|
|
14414
|
+
}
|
|
14415
|
+
case "tool-call": {
|
|
14416
|
+
throw new UnsupportedFunctionalityError({
|
|
14417
|
+
functionality: "tool-call messages"
|
|
14418
|
+
});
|
|
14419
|
+
}
|
|
14420
|
+
case "reasoning": {
|
|
14421
|
+
throw new UnsupportedFunctionalityError({
|
|
14422
|
+
functionality: "reasoning messages"
|
|
14423
|
+
});
|
|
14424
|
+
}
|
|
14425
|
+
case "redacted-reasoning": {
|
|
14426
|
+
throw new UnsupportedFunctionalityError({
|
|
14427
|
+
functionality: "redacted reasoning messages"
|
|
14428
|
+
});
|
|
14429
|
+
}
|
|
14430
|
+
default: {
|
|
14431
|
+
const _exhaustiveCheck = part;
|
|
14432
|
+
throw new Error(
|
|
14433
|
+
`Unsupported content type: ${_exhaustiveCheck}`
|
|
14434
|
+
);
|
|
14435
|
+
}
|
|
14436
|
+
}
|
|
14437
|
+
}).join("");
|
|
14438
|
+
text += `${assistant}:
|
|
14439
|
+
${assistantMessage}
|
|
14440
|
+
|
|
14441
|
+
`;
|
|
14442
|
+
break;
|
|
14443
|
+
}
|
|
14444
|
+
case "tool": {
|
|
14445
|
+
throw new UnsupportedFunctionalityError({
|
|
14446
|
+
functionality: "tool messages"
|
|
14447
|
+
});
|
|
14448
|
+
}
|
|
14449
|
+
default: {
|
|
14450
|
+
const _exhaustiveCheck = role;
|
|
14451
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
|
14452
|
+
}
|
|
14453
|
+
}
|
|
14454
|
+
}
|
|
14455
|
+
text += `${assistant}:
|
|
14456
|
+
`;
|
|
14457
|
+
return {
|
|
14458
|
+
prompt: text
|
|
14459
|
+
};
|
|
14460
|
+
}
|
|
14461
|
+
|
|
14462
|
+
// src/map-openrouter-completion-logprobs.ts
|
|
14463
|
+
function mapOpenRouterCompletionLogProbs(logprobs) {
|
|
14464
|
+
return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => {
|
|
14465
|
+
var _a, _b;
|
|
14466
|
+
return {
|
|
14467
|
+
token,
|
|
14468
|
+
logprob: (_a = logprobs.token_logprobs[index]) != null ? _a : 0,
|
|
14469
|
+
topLogprobs: logprobs.top_logprobs ? Object.entries((_b = logprobs.top_logprobs[index]) != null ? _b : {}).map(
|
|
14470
|
+
([token2, logprob]) => ({
|
|
14471
|
+
token: token2,
|
|
14472
|
+
logprob
|
|
14473
|
+
})
|
|
14474
|
+
) : []
|
|
14475
|
+
};
|
|
14476
|
+
});
|
|
14477
|
+
}
|
|
14478
|
+
|
|
14479
|
+
// src/openrouter-completion-language-model.ts
|
|
14480
|
+
var OpenRouterCompletionLanguageModel = class {
|
|
14481
|
+
constructor(modelId, settings, config) {
|
|
14482
|
+
this.specificationVersion = "v1";
|
|
14483
|
+
this.defaultObjectGenerationMode = void 0;
|
|
14484
|
+
this.modelId = modelId;
|
|
14485
|
+
this.settings = settings;
|
|
14486
|
+
this.config = config;
|
|
14487
|
+
}
|
|
14488
|
+
get provider() {
|
|
14489
|
+
return this.config.provider;
|
|
14490
|
+
}
|
|
14491
|
+
getArgs({
|
|
14492
|
+
mode,
|
|
14493
|
+
inputFormat,
|
|
14494
|
+
prompt,
|
|
14495
|
+
maxTokens,
|
|
14496
|
+
temperature,
|
|
14497
|
+
topP,
|
|
14498
|
+
frequencyPenalty,
|
|
14499
|
+
presencePenalty,
|
|
14500
|
+
seed,
|
|
14501
|
+
responseFormat,
|
|
14502
|
+
topK,
|
|
14503
|
+
stopSequences,
|
|
14504
|
+
providerMetadata
|
|
14505
|
+
}) {
|
|
14506
|
+
var _a, _b;
|
|
14507
|
+
const type = mode.type;
|
|
14508
|
+
const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
|
|
14509
|
+
const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
|
|
14510
|
+
prompt,
|
|
14511
|
+
inputFormat
|
|
14512
|
+
});
|
|
14513
|
+
const baseArgs = __spreadValues(__spreadValues(__spreadValues({
|
|
14514
|
+
// model id:
|
|
14515
|
+
model: this.modelId,
|
|
14516
|
+
models: this.settings.models,
|
|
14517
|
+
// model specific settings:
|
|
14518
|
+
logit_bias: this.settings.logitBias,
|
|
14519
|
+
logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
|
|
14520
|
+
suffix: this.settings.suffix,
|
|
14521
|
+
user: this.settings.user,
|
|
14522
|
+
// standardized settings:
|
|
14523
|
+
max_tokens: maxTokens,
|
|
14524
|
+
temperature,
|
|
14525
|
+
top_p: topP,
|
|
14526
|
+
frequency_penalty: frequencyPenalty,
|
|
14527
|
+
presence_penalty: presencePenalty,
|
|
14528
|
+
seed,
|
|
14529
|
+
stop: stopSequences,
|
|
14530
|
+
response_format: responseFormat,
|
|
14531
|
+
top_k: topK,
|
|
14532
|
+
// prompt:
|
|
14533
|
+
prompt: completionPrompt,
|
|
14534
|
+
// OpenRouter specific settings:
|
|
14535
|
+
include_reasoning: this.settings.includeReasoning,
|
|
14536
|
+
reasoning: this.settings.reasoning
|
|
14537
|
+
}, this.config.extraBody), this.settings.extraBody), extraCallingBody);
|
|
14538
|
+
switch (type) {
|
|
14539
|
+
case "regular": {
|
|
14540
|
+
if ((_b = mode.tools) == null ? void 0 : _b.length) {
|
|
14541
|
+
throw new UnsupportedFunctionalityError({
|
|
14542
|
+
functionality: "tools"
|
|
14543
|
+
});
|
|
14544
|
+
}
|
|
14545
|
+
if (mode.toolChoice) {
|
|
14546
|
+
throw new UnsupportedFunctionalityError({
|
|
14547
|
+
functionality: "toolChoice"
|
|
14548
|
+
});
|
|
14549
|
+
}
|
|
14550
|
+
return baseArgs;
|
|
14551
|
+
}
|
|
14552
|
+
case "object-json": {
|
|
14553
|
+
throw new UnsupportedFunctionalityError({
|
|
14554
|
+
functionality: "object-json mode"
|
|
14555
|
+
});
|
|
14556
|
+
}
|
|
14557
|
+
case "object-tool": {
|
|
14558
|
+
throw new UnsupportedFunctionalityError({
|
|
14559
|
+
functionality: "object-tool mode"
|
|
14560
|
+
});
|
|
14561
|
+
}
|
|
14562
|
+
// Handle all non-text types with a single default case
|
|
14563
|
+
default: {
|
|
14564
|
+
const _exhaustiveCheck = type;
|
|
14565
|
+
throw new UnsupportedFunctionalityError({
|
|
14566
|
+
functionality: `${_exhaustiveCheck} mode`
|
|
14567
|
+
});
|
|
14568
|
+
}
|
|
14569
|
+
}
|
|
14570
|
+
}
|
|
14571
|
+
async doGenerate(options) {
|
|
14572
|
+
var _b, _c, _d, _e, _f;
|
|
14573
|
+
const args = this.getArgs(options);
|
|
14574
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14575
|
+
url: this.config.url({
|
|
14576
|
+
path: "/completions",
|
|
14577
|
+
modelId: this.modelId
|
|
14578
|
+
}),
|
|
14579
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14580
|
+
body: args,
|
|
14581
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14582
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
14583
|
+
OpenRouterCompletionChunkSchema
|
|
14584
|
+
),
|
|
14585
|
+
abortSignal: options.abortSignal,
|
|
14586
|
+
fetch: this.config.fetch
|
|
14587
|
+
});
|
|
14588
|
+
const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
|
|
14589
|
+
if ("error" in response) {
|
|
14590
|
+
throw new Error(`${response.error.message}`);
|
|
14591
|
+
}
|
|
14592
|
+
const choice = response.choices[0];
|
|
14593
|
+
if (!choice) {
|
|
14594
|
+
throw new Error("No choice in OpenRouter completion response");
|
|
14595
|
+
}
|
|
14596
|
+
return {
|
|
14597
|
+
response: {
|
|
14598
|
+
id: response.id,
|
|
14599
|
+
modelId: response.model
|
|
14600
|
+
},
|
|
14601
|
+
text: (_b = choice.text) != null ? _b : "",
|
|
14602
|
+
reasoning: choice.reasoning || void 0,
|
|
14603
|
+
usage: {
|
|
14604
|
+
promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : 0,
|
|
14605
|
+
completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : 0
|
|
14606
|
+
},
|
|
14607
|
+
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
|
|
14608
|
+
logprobs: mapOpenRouterCompletionLogProbs(choice.logprobs),
|
|
14609
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14610
|
+
rawResponse: { headers: responseHeaders },
|
|
14611
|
+
warnings: []
|
|
14612
|
+
};
|
|
14613
|
+
}
|
|
14614
|
+
async doStream(options) {
|
|
14615
|
+
const args = this.getArgs(options);
|
|
14616
|
+
const { responseHeaders, value: response } = await postJsonToApi({
|
|
14617
|
+
url: this.config.url({
|
|
14618
|
+
path: "/completions",
|
|
14619
|
+
modelId: this.modelId
|
|
14620
|
+
}),
|
|
14621
|
+
headers: combineHeaders(this.config.headers(), options.headers),
|
|
14622
|
+
body: __spreadProps(__spreadValues({}, this.getArgs(options)), {
|
|
14623
|
+
stream: true,
|
|
14624
|
+
// only include stream_options when in strict compatibility mode:
|
|
14625
|
+
stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
|
|
14626
|
+
}),
|
|
14627
|
+
failedResponseHandler: openrouterFailedResponseHandler,
|
|
14628
|
+
successfulResponseHandler: createEventSourceResponseHandler(
|
|
14629
|
+
OpenRouterCompletionChunkSchema
|
|
14630
|
+
),
|
|
14631
|
+
abortSignal: options.abortSignal,
|
|
14632
|
+
fetch: this.config.fetch
|
|
14633
|
+
});
|
|
14634
|
+
const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
|
|
14635
|
+
let finishReason = "other";
|
|
14636
|
+
let usage = {
|
|
14637
|
+
promptTokens: Number.NaN,
|
|
14638
|
+
completionTokens: Number.NaN
|
|
14639
|
+
};
|
|
14640
|
+
let logprobs;
|
|
14641
|
+
return {
|
|
14642
|
+
stream: response.pipeThrough(
|
|
14643
|
+
new TransformStream({
|
|
14644
|
+
transform(chunk, controller) {
|
|
14645
|
+
if (!chunk.success) {
|
|
14646
|
+
finishReason = "error";
|
|
14647
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
|
14648
|
+
return;
|
|
14649
|
+
}
|
|
14650
|
+
const value = chunk.value;
|
|
14651
|
+
if ("error" in value) {
|
|
14652
|
+
finishReason = "error";
|
|
14653
|
+
controller.enqueue({ type: "error", error: value.error });
|
|
14654
|
+
return;
|
|
14655
|
+
}
|
|
14656
|
+
if (value.usage != null) {
|
|
14657
|
+
usage = {
|
|
14658
|
+
promptTokens: value.usage.prompt_tokens,
|
|
14659
|
+
completionTokens: value.usage.completion_tokens
|
|
14660
|
+
};
|
|
14661
|
+
}
|
|
14662
|
+
const choice = value.choices[0];
|
|
14663
|
+
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
14664
|
+
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
14665
|
+
}
|
|
14666
|
+
if ((choice == null ? void 0 : choice.text) != null) {
|
|
14667
|
+
controller.enqueue({
|
|
14668
|
+
type: "text-delta",
|
|
14669
|
+
textDelta: choice.text
|
|
14670
|
+
});
|
|
14671
|
+
}
|
|
14672
|
+
const mappedLogprobs = mapOpenRouterCompletionLogProbs(
|
|
14673
|
+
choice == null ? void 0 : choice.logprobs
|
|
14674
|
+
);
|
|
14675
|
+
if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
|
|
14676
|
+
if (logprobs === void 0) logprobs = [];
|
|
14677
|
+
logprobs.push(...mappedLogprobs);
|
|
14678
|
+
}
|
|
14679
|
+
},
|
|
14680
|
+
flush(controller) {
|
|
14681
|
+
controller.enqueue({
|
|
14682
|
+
type: "finish",
|
|
14683
|
+
finishReason,
|
|
14684
|
+
logprobs,
|
|
14685
|
+
usage
|
|
14686
|
+
});
|
|
14687
|
+
}
|
|
14688
|
+
})
|
|
14689
|
+
),
|
|
14690
|
+
rawCall: { rawPrompt, rawSettings },
|
|
14691
|
+
rawResponse: { headers: responseHeaders },
|
|
14692
|
+
warnings: []
|
|
14693
|
+
};
|
|
14694
|
+
}
|
|
14695
|
+
};
|
|
14696
|
+
var OpenRouterCompletionChunkSchema = z.union([
|
|
14697
|
+
z.object({
|
|
14698
|
+
id: z.string().optional(),
|
|
14699
|
+
model: z.string().optional(),
|
|
14700
|
+
choices: z.array(
|
|
14701
|
+
z.object({
|
|
14702
|
+
text: z.string(),
|
|
14703
|
+
reasoning: z.string().nullish().optional(),
|
|
14704
|
+
finish_reason: z.string().nullish(),
|
|
14705
|
+
index: z.number(),
|
|
14706
|
+
logprobs: z.object({
|
|
14707
|
+
tokens: z.array(z.string()),
|
|
14708
|
+
token_logprobs: z.array(z.number()),
|
|
14709
|
+
top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
|
|
14710
|
+
}).nullable().optional()
|
|
14711
|
+
})
|
|
14712
|
+
),
|
|
14713
|
+
usage: z.object({
|
|
14714
|
+
prompt_tokens: z.number(),
|
|
14715
|
+
completion_tokens: z.number()
|
|
14716
|
+
}).optional().nullable()
|
|
14717
|
+
}),
|
|
14718
|
+
OpenRouterErrorResponseSchema
|
|
14719
|
+
]);
|
|
14720
|
+
function createOpenRouter(options = {}) {
|
|
14721
|
+
var _a, _b, _c;
|
|
14722
|
+
const baseURL = (_b = withoutTrailingSlash((_a = options.baseURL) != null ? _a : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
|
|
14723
|
+
const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
|
|
14724
|
+
const getHeaders = () => __spreadValues({
|
|
14725
|
+
Authorization: `Bearer ${loadApiKey({
|
|
14726
|
+
apiKey: options.apiKey,
|
|
14727
|
+
environmentVariableName: "OPENROUTER_API_KEY",
|
|
14728
|
+
description: "OpenRouter"
|
|
14729
|
+
})}`
|
|
14730
|
+
}, options.headers);
|
|
14731
|
+
const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
|
|
14732
|
+
provider: "openrouter.chat",
|
|
14733
|
+
url: ({ path }) => `${baseURL}${path}`,
|
|
14734
|
+
headers: getHeaders,
|
|
14735
|
+
compatibility,
|
|
14736
|
+
fetch: options.fetch,
|
|
14737
|
+
extraBody: options.extraBody
|
|
14738
|
+
});
|
|
14739
|
+
const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
|
|
14740
|
+
provider: "openrouter.completion",
|
|
14741
|
+
url: ({ path }) => `${baseURL}${path}`,
|
|
14742
|
+
headers: getHeaders,
|
|
14743
|
+
compatibility,
|
|
14744
|
+
fetch: options.fetch,
|
|
14745
|
+
extraBody: options.extraBody
|
|
14746
|
+
});
|
|
14747
|
+
const createLanguageModel = (modelId, settings) => {
|
|
14748
|
+
if (new.target) {
|
|
14749
|
+
throw new Error(
|
|
14750
|
+
"The OpenRouter model function cannot be called with the new keyword."
|
|
14751
|
+
);
|
|
14752
|
+
}
|
|
14753
|
+
if (modelId === "openai/gpt-3.5-turbo-instruct") {
|
|
14754
|
+
return createCompletionModel(
|
|
14755
|
+
modelId,
|
|
14756
|
+
settings
|
|
14757
|
+
);
|
|
14758
|
+
}
|
|
14759
|
+
return createChatModel(modelId, settings);
|
|
14760
|
+
};
|
|
14761
|
+
const provider = function(modelId, settings) {
|
|
14762
|
+
return createLanguageModel(modelId, settings);
|
|
14763
|
+
};
|
|
14764
|
+
provider.languageModel = createLanguageModel;
|
|
14765
|
+
provider.chat = createChatModel;
|
|
14766
|
+
provider.completion = createCompletionModel;
|
|
14767
|
+
return provider;
|
|
14768
|
+
}
|
|
14769
|
+
createOpenRouter({
|
|
14770
|
+
compatibility: "strict"
|
|
14771
|
+
// strict for OpenRouter API
|
|
14772
|
+
});
|
|
14773
|
+
|
|
14774
|
+
class RetryLanguageModel {
|
|
14775
|
+
constructor(llms, names, stream_first_timeout) {
|
|
14776
|
+
this.llms = llms;
|
|
14777
|
+
this.names = names || [];
|
|
14778
|
+
this.stream_first_timeout = stream_first_timeout || 30000;
|
|
14779
|
+
if (this.names.indexOf("default") == -1) {
|
|
14780
|
+
this.names.push("default");
|
|
14781
|
+
}
|
|
14782
|
+
}
|
|
14783
|
+
async call(request) {
|
|
14784
|
+
return await this.doGenerate({
|
|
14785
|
+
inputFormat: "messages",
|
|
14786
|
+
mode: {
|
|
14787
|
+
type: "regular",
|
|
14788
|
+
tools: request.tools,
|
|
14789
|
+
toolChoice: request.toolChoice,
|
|
14790
|
+
},
|
|
14791
|
+
prompt: request.messages,
|
|
14792
|
+
maxTokens: request.maxTokens || config.maxTokens,
|
|
14793
|
+
temperature: request.temperature,
|
|
14794
|
+
topP: request.topP,
|
|
14795
|
+
topK: request.topK,
|
|
14796
|
+
providerMetadata: {},
|
|
12760
14797
|
abortSignal: request.abortSignal,
|
|
12761
14798
|
});
|
|
12762
14799
|
}
|
|
@@ -12871,7 +14908,7 @@ class RetryLanguageModel {
|
|
|
12871
14908
|
baseURL: llm.config?.baseURL,
|
|
12872
14909
|
}).languageModel(llm.model, {
|
|
12873
14910
|
// disable_parallel_tool_use
|
|
12874
|
-
parallelToolCalls: false,
|
|
14911
|
+
parallelToolCalls: llm.config?.parallelToolCalls || false,
|
|
12875
14912
|
});
|
|
12876
14913
|
}
|
|
12877
14914
|
else if (llm.provider == "anthropic") {
|
|
@@ -12889,10 +14926,16 @@ class RetryLanguageModel {
|
|
|
12889
14926
|
else if (llm.provider == "aws") {
|
|
12890
14927
|
let keys = llm.apiKey.split("=");
|
|
12891
14928
|
return createAmazonBedrock({
|
|
12892
|
-
region: llm.config?.region || "us-east-2",
|
|
12893
|
-
baseURL: llm.config?.baseURL,
|
|
12894
14929
|
accessKeyId: keys[0],
|
|
12895
14930
|
secretAccessKey: keys[1],
|
|
14931
|
+
baseURL: llm.config?.baseURL,
|
|
14932
|
+
region: llm.config?.region || "us-east-1",
|
|
14933
|
+
}).languageModel(llm.model);
|
|
14934
|
+
}
|
|
14935
|
+
else if (llm.provider == "openrouter") {
|
|
14936
|
+
return createOpenRouter({
|
|
14937
|
+
apiKey: llm.apiKey,
|
|
14938
|
+
baseURL: llm.config?.baseURL,
|
|
12896
14939
|
}).languageModel(llm.model);
|
|
12897
14940
|
}
|
|
12898
14941
|
else {
|
|
@@ -15474,59 +17517,276 @@ function parseWorkflowNodes(nodes, xmlNodes) {
|
|
|
15474
17517
|
if (triggerNode.length > 0) {
|
|
15475
17518
|
parseWorkflowNodes(_nodes, triggerNode[0].childNodes);
|
|
15476
17519
|
}
|
|
15477
|
-
nodes.push(node);
|
|
15478
|
-
break;
|
|
17520
|
+
nodes.push(node);
|
|
17521
|
+
break;
|
|
17522
|
+
}
|
|
17523
|
+
}
|
|
17524
|
+
}
|
|
17525
|
+
}
|
|
17526
|
+
function buildAgentRootXml(agentXml, mainTaskPrompt, nodeCallback) {
|
|
17527
|
+
const parser = new domParserExports.DOMParser();
|
|
17528
|
+
const doc = parser.parseFromString(agentXml, "text/xml");
|
|
17529
|
+
let agentNode = doc.getElementsByTagName("agent");
|
|
17530
|
+
let nodesNode = doc.getElementsByTagName("nodes");
|
|
17531
|
+
if (nodesNode.length > 0) {
|
|
17532
|
+
let nodes = nodesNode[0].childNodes;
|
|
17533
|
+
let nodeId = 0;
|
|
17534
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
17535
|
+
let node = nodes[i];
|
|
17536
|
+
if (node.nodeType == 1) {
|
|
17537
|
+
node.setAttribute("id", nodeId + "");
|
|
17538
|
+
nodeCallback && nodeCallback(nodeId, node);
|
|
17539
|
+
nodeId++;
|
|
17540
|
+
}
|
|
17541
|
+
}
|
|
17542
|
+
}
|
|
17543
|
+
// <root><mainTask></mainTask><currentTask></currentTask><nodes><node id="0"></node></nodes></root>
|
|
17544
|
+
let agentInnerHTML = getInnerXML(agentNode[0]);
|
|
17545
|
+
let prefix = agentInnerHTML.substring(0, agentInnerHTML.indexOf("<task>"));
|
|
17546
|
+
agentInnerHTML = agentInnerHTML
|
|
17547
|
+
.replace("<task>", "<currentTask>")
|
|
17548
|
+
.replace("</task>", "</currentTask>");
|
|
17549
|
+
return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
|
|
17550
|
+
}
|
|
17551
|
+
function extractAgentXmlNode(agentXml, nodeId) {
|
|
17552
|
+
const parser = new domParserExports.DOMParser();
|
|
17553
|
+
const doc = parser.parseFromString(agentXml, "text/xml");
|
|
17554
|
+
let nodesNode = doc.getElementsByTagName("nodes");
|
|
17555
|
+
if (nodesNode.length > 0) {
|
|
17556
|
+
let nodes = nodesNode[0].childNodes;
|
|
17557
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
17558
|
+
let node = nodes[i];
|
|
17559
|
+
if (node.nodeType == 1 && node.getAttribute("id") == nodeId + "") {
|
|
17560
|
+
return node;
|
|
17561
|
+
}
|
|
17562
|
+
}
|
|
17563
|
+
}
|
|
17564
|
+
return null;
|
|
17565
|
+
}
|
|
17566
|
+
function getInnerXML(node) {
|
|
17567
|
+
let result = "";
|
|
17568
|
+
const serializer = new domParserExports.XMLSerializer();
|
|
17569
|
+
for (let i = 0; i < node.childNodes.length; i++) {
|
|
17570
|
+
result += serializer.serializeToString(node.childNodes[i]);
|
|
17571
|
+
}
|
|
17572
|
+
return result;
|
|
17573
|
+
}
|
|
17574
|
+
|
|
17575
|
+
const TOOL_NAME$5 = "task_snapshot";
|
|
17576
|
+
class TaskSnapshotTool {
|
|
17577
|
+
constructor() {
|
|
17578
|
+
this.name = TOOL_NAME$5;
|
|
17579
|
+
this.description = `Task snapshot archive, recording key information of the current task, updating task node status, facilitating subsequent continuation of operation.`;
|
|
17580
|
+
this.parameters = {
|
|
17581
|
+
type: "object",
|
|
17582
|
+
properties: {
|
|
17583
|
+
doneIds: {
|
|
17584
|
+
type: "array",
|
|
17585
|
+
description: "Update task node completion status, list of completed node IDs.",
|
|
17586
|
+
items: {
|
|
17587
|
+
type: "number",
|
|
17588
|
+
},
|
|
17589
|
+
},
|
|
17590
|
+
taskSnapshot: {
|
|
17591
|
+
type: "string",
|
|
17592
|
+
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.",
|
|
17593
|
+
},
|
|
17594
|
+
},
|
|
17595
|
+
required: ["doneIds", "taskSnapshot"],
|
|
17596
|
+
};
|
|
17597
|
+
}
|
|
17598
|
+
async execute(args, agentContext) {
|
|
17599
|
+
let doneIds = args.doneIds;
|
|
17600
|
+
let taskSnapshot = args.taskSnapshot;
|
|
17601
|
+
let agentNode = agentContext.agentChain.agent;
|
|
17602
|
+
let taskPrompt = agentContext.context.chain.taskPrompt;
|
|
17603
|
+
let agentXml = buildAgentRootXml(agentNode.xml, taskPrompt, (nodeId, node) => {
|
|
17604
|
+
let done = doneIds.indexOf(nodeId) > -1;
|
|
17605
|
+
node.setAttribute("status", done ? "done" : "todo");
|
|
17606
|
+
});
|
|
17607
|
+
let text = "The current task has been interrupted. Below is a snapshot of the task execution history.\n" +
|
|
17608
|
+
"# Task Snapshot\n" +
|
|
17609
|
+
taskSnapshot.trim() +
|
|
17610
|
+
"\n\n# Task\n" +
|
|
17611
|
+
agentXml;
|
|
17612
|
+
return {
|
|
17613
|
+
content: [
|
|
17614
|
+
{
|
|
17615
|
+
type: "text",
|
|
17616
|
+
text: text,
|
|
17617
|
+
},
|
|
17618
|
+
],
|
|
17619
|
+
};
|
|
17620
|
+
}
|
|
17621
|
+
}
|
|
17622
|
+
|
|
17623
|
+
function handleMultiImageFileMessage(messages) {
|
|
17624
|
+
let imageNum = 0;
|
|
17625
|
+
let fileNum = 0;
|
|
17626
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
17627
|
+
let message = messages[i];
|
|
17628
|
+
if (message.role == "user") {
|
|
17629
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17630
|
+
let content = message.content[j];
|
|
17631
|
+
if (content.type == "image") {
|
|
17632
|
+
if (++imageNum == 1) {
|
|
17633
|
+
break;
|
|
17634
|
+
}
|
|
17635
|
+
content = {
|
|
17636
|
+
type: "text",
|
|
17637
|
+
text: "[image]",
|
|
17638
|
+
};
|
|
17639
|
+
message.content[j] = content;
|
|
17640
|
+
}
|
|
17641
|
+
else if (content.type == "file") {
|
|
17642
|
+
if (++fileNum == 1) {
|
|
17643
|
+
break;
|
|
17644
|
+
}
|
|
17645
|
+
content = {
|
|
17646
|
+
type: "text",
|
|
17647
|
+
text: "[file]",
|
|
17648
|
+
};
|
|
17649
|
+
message.content[j] = content;
|
|
17650
|
+
}
|
|
17651
|
+
}
|
|
17652
|
+
}
|
|
17653
|
+
else if (message.role == "tool") {
|
|
17654
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17655
|
+
let content = message.content[j];
|
|
17656
|
+
let tool_content = content.content;
|
|
17657
|
+
if (!tool_content || tool_content.length == 0) {
|
|
17658
|
+
continue;
|
|
17659
|
+
}
|
|
17660
|
+
for (let r = 0; r < tool_content.length; r++) {
|
|
17661
|
+
let _content = tool_content[r];
|
|
17662
|
+
if (_content.type == "image") {
|
|
17663
|
+
if (++imageNum == 1) {
|
|
17664
|
+
break;
|
|
17665
|
+
}
|
|
17666
|
+
_content = {
|
|
17667
|
+
type: "text",
|
|
17668
|
+
text: "[image]",
|
|
17669
|
+
};
|
|
17670
|
+
tool_content[r] = _content;
|
|
17671
|
+
}
|
|
17672
|
+
}
|
|
15479
17673
|
}
|
|
15480
17674
|
}
|
|
15481
17675
|
}
|
|
15482
17676
|
}
|
|
15483
|
-
function
|
|
15484
|
-
|
|
15485
|
-
|
|
15486
|
-
|
|
15487
|
-
|
|
15488
|
-
|
|
15489
|
-
|
|
15490
|
-
|
|
15491
|
-
|
|
15492
|
-
let
|
|
15493
|
-
|
|
15494
|
-
|
|
15495
|
-
|
|
15496
|
-
|
|
17677
|
+
function removeDuplicateToolUse(results) {
|
|
17678
|
+
if (results.length <= 1 ||
|
|
17679
|
+
results.filter((r) => r.type == "tool-call").length <= 1) {
|
|
17680
|
+
return results;
|
|
17681
|
+
}
|
|
17682
|
+
let _results = [];
|
|
17683
|
+
let tool_uniques = [];
|
|
17684
|
+
for (let i = 0; i < results.length; i++) {
|
|
17685
|
+
if (results[i].type === "tool-call") {
|
|
17686
|
+
let tool = results[i];
|
|
17687
|
+
let key = tool.toolName + tool.args;
|
|
17688
|
+
if (tool_uniques.indexOf(key) == -1) {
|
|
17689
|
+
_results.push(results[i]);
|
|
17690
|
+
tool_uniques.push(key);
|
|
15497
17691
|
}
|
|
15498
17692
|
}
|
|
17693
|
+
else {
|
|
17694
|
+
_results.push(results[i]);
|
|
17695
|
+
}
|
|
15499
17696
|
}
|
|
15500
|
-
|
|
15501
|
-
let agentInnerHTML = getInnerXML(agentNode[0]);
|
|
15502
|
-
let prefix = agentInnerHTML.substring(0, agentInnerHTML.indexOf("<task>"));
|
|
15503
|
-
agentInnerHTML = agentInnerHTML
|
|
15504
|
-
.replace("<task>", "<currentTask>")
|
|
15505
|
-
.replace("</task>", "</currentTask>");
|
|
15506
|
-
return `<root>${prefix}<mainTask>${mainTaskPrompt}</mainTask>${agentInnerHTML}</root>`;
|
|
17697
|
+
return _results;
|
|
15507
17698
|
}
|
|
15508
|
-
function
|
|
15509
|
-
|
|
15510
|
-
|
|
15511
|
-
let
|
|
15512
|
-
|
|
15513
|
-
|
|
15514
|
-
|
|
15515
|
-
|
|
15516
|
-
|
|
15517
|
-
|
|
17699
|
+
function extractUsedTool(messages, agentTools) {
|
|
17700
|
+
let tools = [];
|
|
17701
|
+
let toolNames = [];
|
|
17702
|
+
for (let i = 0; i < messages.length; i++) {
|
|
17703
|
+
let message = messages[i];
|
|
17704
|
+
if (message.role == "tool") {
|
|
17705
|
+
for (let j = 0; j < message.content.length; j++) {
|
|
17706
|
+
let toolName = message.content[j].toolName;
|
|
17707
|
+
if (toolNames.indexOf(toolName) > -1) {
|
|
17708
|
+
continue;
|
|
17709
|
+
}
|
|
17710
|
+
toolNames.push(toolName);
|
|
17711
|
+
let tool = agentTools.filter((tool) => tool.name === toolName)[0];
|
|
17712
|
+
if (tool) {
|
|
17713
|
+
tools.push(tool);
|
|
17714
|
+
}
|
|
15518
17715
|
}
|
|
15519
17716
|
}
|
|
15520
17717
|
}
|
|
15521
|
-
return
|
|
17718
|
+
return tools;
|
|
15522
17719
|
}
|
|
15523
|
-
function
|
|
15524
|
-
|
|
15525
|
-
|
|
15526
|
-
for (let i = 0; i < node.childNodes.length; i++) {
|
|
15527
|
-
result += serializer.serializeToString(node.childNodes[i]);
|
|
17720
|
+
async function compressAgentMessages(agentContext, rlm, messages, tools) {
|
|
17721
|
+
if (messages.length < 10) {
|
|
17722
|
+
return;
|
|
15528
17723
|
}
|
|
15529
|
-
|
|
17724
|
+
// extract used tool
|
|
17725
|
+
let usedTools = extractUsedTool(messages, tools);
|
|
17726
|
+
let snapshotTool = new TaskSnapshotTool();
|
|
17727
|
+
let newTools = mergeTools(usedTools, [
|
|
17728
|
+
{
|
|
17729
|
+
type: "function",
|
|
17730
|
+
name: snapshotTool.name,
|
|
17731
|
+
description: snapshotTool.description,
|
|
17732
|
+
parameters: snapshotTool.parameters,
|
|
17733
|
+
},
|
|
17734
|
+
]);
|
|
17735
|
+
// handle messages
|
|
17736
|
+
let lastToolIndex = messages.length - 1;
|
|
17737
|
+
let newMessages = messages;
|
|
17738
|
+
for (let r = newMessages.length - 1; r > 3; r--) {
|
|
17739
|
+
if (newMessages[r].role == "tool") {
|
|
17740
|
+
newMessages = newMessages.slice(0, r + 1);
|
|
17741
|
+
lastToolIndex = r;
|
|
17742
|
+
break;
|
|
17743
|
+
}
|
|
17744
|
+
}
|
|
17745
|
+
newMessages.push({
|
|
17746
|
+
role: "user",
|
|
17747
|
+
content: [
|
|
17748
|
+
{
|
|
17749
|
+
type: "text",
|
|
17750
|
+
text: "Please create a snapshot backup of the current task, keeping only key important information and node completion status.",
|
|
17751
|
+
},
|
|
17752
|
+
],
|
|
17753
|
+
});
|
|
17754
|
+
// compress snapshot
|
|
17755
|
+
let result = await callLLM(agentContext, rlm, newMessages, newTools, true, {
|
|
17756
|
+
type: "tool",
|
|
17757
|
+
toolName: snapshotTool.name,
|
|
17758
|
+
});
|
|
17759
|
+
let toolCall = result.filter((s) => s.type == "tool-call")[0];
|
|
17760
|
+
let args = typeof toolCall.args == "string"
|
|
17761
|
+
? JSON.parse(toolCall.args || "{}")
|
|
17762
|
+
: toolCall.args || {};
|
|
17763
|
+
let toolResult = await snapshotTool.execute(args, agentContext);
|
|
17764
|
+
let callback = agentContext.context.config.callback;
|
|
17765
|
+
if (callback) {
|
|
17766
|
+
await callback.onMessage({
|
|
17767
|
+
taskId: agentContext.context.taskId,
|
|
17768
|
+
agentName: toolCall.toolName,
|
|
17769
|
+
nodeId: agentContext.agentChain.agent.id,
|
|
17770
|
+
type: "tool_result",
|
|
17771
|
+
toolId: toolCall.toolCallId,
|
|
17772
|
+
toolName: toolCall.toolName,
|
|
17773
|
+
params: args,
|
|
17774
|
+
toolResult: toolResult,
|
|
17775
|
+
});
|
|
17776
|
+
}
|
|
17777
|
+
// handle original messages
|
|
17778
|
+
let firstToolIndex = 3;
|
|
17779
|
+
for (let i = 0; i < messages.length; i++) {
|
|
17780
|
+
if (messages[0].role == "tool") {
|
|
17781
|
+
firstToolIndex = i;
|
|
17782
|
+
break;
|
|
17783
|
+
}
|
|
17784
|
+
}
|
|
17785
|
+
// system, user, assistant, tool(first), [...], <user>, assistant, tool(last), ...
|
|
17786
|
+
messages.splice(firstToolIndex + 1, lastToolIndex - firstToolIndex - 2, {
|
|
17787
|
+
role: "user",
|
|
17788
|
+
content: toolResult.content.filter((s) => s.type == "text"),
|
|
17789
|
+
});
|
|
15530
17790
|
}
|
|
15531
17791
|
|
|
15532
17792
|
class ToolWrapper {
|
|
@@ -16049,13 +18309,13 @@ class Agent {
|
|
|
16049
18309
|
let controlMcp = await this.controlMcpTools(agentContext, messages, loopNum);
|
|
16050
18310
|
if (controlMcp.mcpTools) {
|
|
16051
18311
|
let mcpTools = await this.listTools(agentNode, context, mcpClient, controlMcp.mcpParams);
|
|
16052
|
-
let usedTools =
|
|
18312
|
+
let usedTools = extractUsedTool(messages, agentTools);
|
|
16053
18313
|
let _agentTools = mergeTools(tools, usedTools);
|
|
16054
18314
|
agentTools = mergeTools(_agentTools, mcpTools);
|
|
16055
18315
|
}
|
|
16056
18316
|
}
|
|
16057
18317
|
await this.handleMessages(agentContext, messages);
|
|
16058
|
-
let results = await
|
|
18318
|
+
let results = await callLLM(agentContext, rlm, messages, this.convertTools(agentTools));
|
|
16059
18319
|
let finalResult = await this.handleResult(agentContext, messages, agentTools, results);
|
|
16060
18320
|
if (finalResult) {
|
|
16061
18321
|
return finalResult;
|
|
@@ -16069,7 +18329,7 @@ class Agent {
|
|
|
16069
18329
|
let context = agentContext.context;
|
|
16070
18330
|
let user_messages = [];
|
|
16071
18331
|
let toolResults = [];
|
|
16072
|
-
results =
|
|
18332
|
+
results = removeDuplicateToolUse(results);
|
|
16073
18333
|
if (results.length == 0) {
|
|
16074
18334
|
return null;
|
|
16075
18335
|
}
|
|
@@ -16153,28 +18413,6 @@ class Agent {
|
|
|
16153
18413
|
let toolNames = this.tools.map((tool) => tool.name);
|
|
16154
18414
|
return tools.filter((tool) => toolNames.indexOf(tool.name) == -1);
|
|
16155
18415
|
}
|
|
16156
|
-
removeDuplicateToolUse(results) {
|
|
16157
|
-
if (results.length <= 1 ||
|
|
16158
|
-
results.filter((r) => r.type == "tool-call").length <= 1) {
|
|
16159
|
-
return results;
|
|
16160
|
-
}
|
|
16161
|
-
let _results = [];
|
|
16162
|
-
let tool_uniques = [];
|
|
16163
|
-
for (let i = 0; i < results.length; i++) {
|
|
16164
|
-
if (results[i].type === "tool-call") {
|
|
16165
|
-
let tool = results[i];
|
|
16166
|
-
let key = tool.toolName + tool.args;
|
|
16167
|
-
if (tool_uniques.indexOf(key) == -1) {
|
|
16168
|
-
_results.push(results[i]);
|
|
16169
|
-
tool_uniques.push(key);
|
|
16170
|
-
}
|
|
16171
|
-
}
|
|
16172
|
-
else {
|
|
16173
|
-
_results.push(results[i]);
|
|
16174
|
-
}
|
|
16175
|
-
}
|
|
16176
|
-
return _results;
|
|
16177
|
-
}
|
|
16178
18416
|
async initMessages(agentContext, tools) {
|
|
16179
18417
|
let messages = [
|
|
16180
18418
|
{
|
|
@@ -16252,27 +18490,6 @@ class Agent {
|
|
|
16252
18490
|
}
|
|
16253
18491
|
return null;
|
|
16254
18492
|
}
|
|
16255
|
-
extractUsedTool(messages, agentTools) {
|
|
16256
|
-
let tools = [];
|
|
16257
|
-
let toolNames = [];
|
|
16258
|
-
for (let i = 0; i < messages.length; i++) {
|
|
16259
|
-
let message = messages[i];
|
|
16260
|
-
if (message.role == "tool") {
|
|
16261
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16262
|
-
let toolName = message.content[j].toolName;
|
|
16263
|
-
if (toolNames.indexOf(toolName) > -1) {
|
|
16264
|
-
continue;
|
|
16265
|
-
}
|
|
16266
|
-
toolNames.push(toolName);
|
|
16267
|
-
let tool = agentTools.filter((tool) => tool.name === toolName)[0];
|
|
16268
|
-
if (tool) {
|
|
16269
|
-
tools.push(tool);
|
|
16270
|
-
}
|
|
16271
|
-
}
|
|
16272
|
-
}
|
|
16273
|
-
}
|
|
16274
|
-
return tools;
|
|
16275
|
-
}
|
|
16276
18493
|
convertToolResult(toolUse, toolResult, user_messages) {
|
|
16277
18494
|
let text = "";
|
|
16278
18495
|
for (let i = 0; i < toolResult.content.length; i++) {
|
|
@@ -16328,218 +18545,7 @@ class Agent {
|
|
|
16328
18545
|
}
|
|
16329
18546
|
async handleMessages(agentContext, messages) {
|
|
16330
18547
|
// Only keep the last image / file
|
|
16331
|
-
|
|
16332
|
-
let fileNum = 0;
|
|
16333
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
16334
|
-
let message = messages[i];
|
|
16335
|
-
if (message.role == "user") {
|
|
16336
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16337
|
-
let content = message.content[j];
|
|
16338
|
-
if (content.type == "image") {
|
|
16339
|
-
if (++imageNum == 1) {
|
|
16340
|
-
break;
|
|
16341
|
-
}
|
|
16342
|
-
content = {
|
|
16343
|
-
type: "text",
|
|
16344
|
-
text: "[image]",
|
|
16345
|
-
};
|
|
16346
|
-
message.content[j] = content;
|
|
16347
|
-
}
|
|
16348
|
-
else if (content.type == "file") {
|
|
16349
|
-
if (++fileNum == 1) {
|
|
16350
|
-
break;
|
|
16351
|
-
}
|
|
16352
|
-
content = {
|
|
16353
|
-
type: "text",
|
|
16354
|
-
text: "[file]",
|
|
16355
|
-
};
|
|
16356
|
-
message.content[j] = content;
|
|
16357
|
-
}
|
|
16358
|
-
}
|
|
16359
|
-
}
|
|
16360
|
-
else if (message.role == "tool") {
|
|
16361
|
-
for (let j = 0; j < message.content.length; j++) {
|
|
16362
|
-
let content = message.content[j];
|
|
16363
|
-
let tool_content = content.content;
|
|
16364
|
-
if (!tool_content || tool_content.length == 0) {
|
|
16365
|
-
continue;
|
|
16366
|
-
}
|
|
16367
|
-
for (let r = 0; r < tool_content.length; r++) {
|
|
16368
|
-
let _content = tool_content[r];
|
|
16369
|
-
if (_content.type == "image") {
|
|
16370
|
-
if (++imageNum == 1) {
|
|
16371
|
-
break;
|
|
16372
|
-
}
|
|
16373
|
-
_content = {
|
|
16374
|
-
type: "text",
|
|
16375
|
-
text: "[image]",
|
|
16376
|
-
};
|
|
16377
|
-
tool_content[r] = _content;
|
|
16378
|
-
}
|
|
16379
|
-
}
|
|
16380
|
-
}
|
|
16381
|
-
}
|
|
16382
|
-
}
|
|
16383
|
-
}
|
|
16384
|
-
async callLLM(agentContext, rlm, messages, tools) {
|
|
16385
|
-
let context = agentContext.context;
|
|
16386
|
-
let agentChain = agentContext.agentChain;
|
|
16387
|
-
let agentNode = agentChain.agent;
|
|
16388
|
-
let streamCallback = context.config.callback || {
|
|
16389
|
-
onMessage: async () => { },
|
|
16390
|
-
};
|
|
16391
|
-
let request = {
|
|
16392
|
-
tools: tools,
|
|
16393
|
-
messages: messages,
|
|
16394
|
-
abortSignal: context.controller.signal,
|
|
16395
|
-
};
|
|
16396
|
-
agentChain.agentRequest = request;
|
|
16397
|
-
let result = await rlm.callStream(request);
|
|
16398
|
-
let streamText = "";
|
|
16399
|
-
let thinkText = "";
|
|
16400
|
-
let toolArgsText = "";
|
|
16401
|
-
let streamId = uuidv4();
|
|
16402
|
-
let textStreamDone = false;
|
|
16403
|
-
let toolParts = [];
|
|
16404
|
-
const reader = result.stream.getReader();
|
|
16405
|
-
try {
|
|
16406
|
-
while (true) {
|
|
16407
|
-
context.checkAborted();
|
|
16408
|
-
const { done, value } = await reader.read();
|
|
16409
|
-
if (done) {
|
|
16410
|
-
break;
|
|
16411
|
-
}
|
|
16412
|
-
let chunk = value;
|
|
16413
|
-
switch (chunk.type) {
|
|
16414
|
-
case "text-delta": {
|
|
16415
|
-
streamText += chunk.textDelta || "";
|
|
16416
|
-
await streamCallback.onMessage({
|
|
16417
|
-
taskId: context.taskId,
|
|
16418
|
-
agentName: agentNode.name,
|
|
16419
|
-
nodeId: agentNode.id,
|
|
16420
|
-
type: "text",
|
|
16421
|
-
streamId,
|
|
16422
|
-
streamDone: false,
|
|
16423
|
-
text: streamText,
|
|
16424
|
-
});
|
|
16425
|
-
break;
|
|
16426
|
-
}
|
|
16427
|
-
case "reasoning": {
|
|
16428
|
-
thinkText += chunk.textDelta || "";
|
|
16429
|
-
await streamCallback.onMessage({
|
|
16430
|
-
taskId: context.taskId,
|
|
16431
|
-
agentName: agentNode.name,
|
|
16432
|
-
nodeId: agentNode.id,
|
|
16433
|
-
type: "thinking",
|
|
16434
|
-
streamId,
|
|
16435
|
-
streamDone: false,
|
|
16436
|
-
text: thinkText,
|
|
16437
|
-
});
|
|
16438
|
-
break;
|
|
16439
|
-
}
|
|
16440
|
-
case "tool-call-delta": {
|
|
16441
|
-
if (!textStreamDone) {
|
|
16442
|
-
textStreamDone = true;
|
|
16443
|
-
await streamCallback.onMessage({
|
|
16444
|
-
taskId: context.taskId,
|
|
16445
|
-
agentName: agentNode.name,
|
|
16446
|
-
nodeId: agentNode.id,
|
|
16447
|
-
type: "text",
|
|
16448
|
-
streamId,
|
|
16449
|
-
streamDone: true,
|
|
16450
|
-
text: streamText,
|
|
16451
|
-
});
|
|
16452
|
-
}
|
|
16453
|
-
toolArgsText += chunk.argsTextDelta || "";
|
|
16454
|
-
await streamCallback.onMessage({
|
|
16455
|
-
taskId: context.taskId,
|
|
16456
|
-
agentName: agentNode.name,
|
|
16457
|
-
nodeId: agentNode.id,
|
|
16458
|
-
type: "tool_streaming",
|
|
16459
|
-
toolId: chunk.toolCallId,
|
|
16460
|
-
toolName: chunk.toolName,
|
|
16461
|
-
paramsText: toolArgsText,
|
|
16462
|
-
});
|
|
16463
|
-
break;
|
|
16464
|
-
}
|
|
16465
|
-
case "tool-call": {
|
|
16466
|
-
toolArgsText = "";
|
|
16467
|
-
let args = chunk.args ? JSON.parse(chunk.args) : {};
|
|
16468
|
-
await streamCallback.onMessage({
|
|
16469
|
-
taskId: context.taskId,
|
|
16470
|
-
agentName: agentNode.name,
|
|
16471
|
-
nodeId: agentNode.id,
|
|
16472
|
-
type: "tool_use",
|
|
16473
|
-
toolId: chunk.toolCallId,
|
|
16474
|
-
toolName: chunk.toolName,
|
|
16475
|
-
params: args,
|
|
16476
|
-
});
|
|
16477
|
-
toolParts.push({
|
|
16478
|
-
type: "tool-call",
|
|
16479
|
-
toolCallId: chunk.toolCallId,
|
|
16480
|
-
toolName: chunk.toolName,
|
|
16481
|
-
args: args,
|
|
16482
|
-
});
|
|
16483
|
-
break;
|
|
16484
|
-
}
|
|
16485
|
-
case "file": {
|
|
16486
|
-
await streamCallback.onMessage({
|
|
16487
|
-
taskId: context.taskId,
|
|
16488
|
-
agentName: agentNode.name,
|
|
16489
|
-
nodeId: agentNode.id,
|
|
16490
|
-
type: "file",
|
|
16491
|
-
mimeType: chunk.mimeType,
|
|
16492
|
-
data: chunk.data,
|
|
16493
|
-
});
|
|
16494
|
-
break;
|
|
16495
|
-
}
|
|
16496
|
-
case "error": {
|
|
16497
|
-
Log.error(`${this.name} agent error: `, chunk);
|
|
16498
|
-
await streamCallback.onMessage({
|
|
16499
|
-
taskId: context.taskId,
|
|
16500
|
-
agentName: agentNode.name,
|
|
16501
|
-
nodeId: agentNode.id,
|
|
16502
|
-
type: "error",
|
|
16503
|
-
error: chunk.error,
|
|
16504
|
-
});
|
|
16505
|
-
throw new Error("Plan Error");
|
|
16506
|
-
}
|
|
16507
|
-
case "finish": {
|
|
16508
|
-
if (!textStreamDone) {
|
|
16509
|
-
textStreamDone = true;
|
|
16510
|
-
await streamCallback.onMessage({
|
|
16511
|
-
taskId: context.taskId,
|
|
16512
|
-
agentName: agentNode.name,
|
|
16513
|
-
nodeId: agentNode.id,
|
|
16514
|
-
type: "text",
|
|
16515
|
-
streamId,
|
|
16516
|
-
streamDone: true,
|
|
16517
|
-
text: streamText,
|
|
16518
|
-
});
|
|
16519
|
-
}
|
|
16520
|
-
await streamCallback.onMessage({
|
|
16521
|
-
taskId: context.taskId,
|
|
16522
|
-
agentName: agentNode.name,
|
|
16523
|
-
nodeId: agentNode.id,
|
|
16524
|
-
type: "finish",
|
|
16525
|
-
finishReason: chunk.finishReason,
|
|
16526
|
-
usage: chunk.usage,
|
|
16527
|
-
});
|
|
16528
|
-
break;
|
|
16529
|
-
}
|
|
16530
|
-
}
|
|
16531
|
-
}
|
|
16532
|
-
}
|
|
16533
|
-
finally {
|
|
16534
|
-
reader.releaseLock();
|
|
16535
|
-
}
|
|
16536
|
-
agentChain.agentResult = streamText;
|
|
16537
|
-
return streamText
|
|
16538
|
-
? [
|
|
16539
|
-
{ type: "text", text: streamText },
|
|
16540
|
-
...toolParts,
|
|
16541
|
-
]
|
|
16542
|
-
: toolParts;
|
|
18548
|
+
handleMultiImageFileMessage(messages);
|
|
16543
18549
|
}
|
|
16544
18550
|
async callInnerTool(fun) {
|
|
16545
18551
|
let result = await fun();
|
|
@@ -16572,6 +18578,170 @@ class Agent {
|
|
|
16572
18578
|
return this.mcpClient;
|
|
16573
18579
|
}
|
|
16574
18580
|
}
|
|
18581
|
+
async function callLLM(agentContext, rlm, messages, tools, noCompress, toolChoice) {
|
|
18582
|
+
if (messages.length >= config.compressThreshold && !noCompress) {
|
|
18583
|
+
await compressAgentMessages(agentContext, rlm, messages, tools);
|
|
18584
|
+
}
|
|
18585
|
+
let context = agentContext.context;
|
|
18586
|
+
let agentChain = agentContext.agentChain;
|
|
18587
|
+
let agentNode = agentChain.agent;
|
|
18588
|
+
let streamCallback = context.config.callback || {
|
|
18589
|
+
onMessage: async () => { },
|
|
18590
|
+
};
|
|
18591
|
+
let request = {
|
|
18592
|
+
tools: tools,
|
|
18593
|
+
toolChoice,
|
|
18594
|
+
messages: messages,
|
|
18595
|
+
abortSignal: context.controller.signal,
|
|
18596
|
+
};
|
|
18597
|
+
agentChain.agentRequest = request;
|
|
18598
|
+
let result = await rlm.callStream(request);
|
|
18599
|
+
let streamText = "";
|
|
18600
|
+
let thinkText = "";
|
|
18601
|
+
let toolArgsText = "";
|
|
18602
|
+
let streamId = uuidv4();
|
|
18603
|
+
let textStreamDone = false;
|
|
18604
|
+
let toolParts = [];
|
|
18605
|
+
const reader = result.stream.getReader();
|
|
18606
|
+
try {
|
|
18607
|
+
while (true) {
|
|
18608
|
+
context.checkAborted();
|
|
18609
|
+
const { done, value } = await reader.read();
|
|
18610
|
+
if (done) {
|
|
18611
|
+
break;
|
|
18612
|
+
}
|
|
18613
|
+
let chunk = value;
|
|
18614
|
+
switch (chunk.type) {
|
|
18615
|
+
case "text-delta": {
|
|
18616
|
+
streamText += chunk.textDelta || "";
|
|
18617
|
+
await streamCallback.onMessage({
|
|
18618
|
+
taskId: context.taskId,
|
|
18619
|
+
agentName: agentNode.name,
|
|
18620
|
+
nodeId: agentNode.id,
|
|
18621
|
+
type: "text",
|
|
18622
|
+
streamId,
|
|
18623
|
+
streamDone: false,
|
|
18624
|
+
text: streamText,
|
|
18625
|
+
});
|
|
18626
|
+
break;
|
|
18627
|
+
}
|
|
18628
|
+
case "reasoning": {
|
|
18629
|
+
thinkText += chunk.textDelta || "";
|
|
18630
|
+
await streamCallback.onMessage({
|
|
18631
|
+
taskId: context.taskId,
|
|
18632
|
+
agentName: agentNode.name,
|
|
18633
|
+
nodeId: agentNode.id,
|
|
18634
|
+
type: "thinking",
|
|
18635
|
+
streamId,
|
|
18636
|
+
streamDone: false,
|
|
18637
|
+
text: thinkText,
|
|
18638
|
+
});
|
|
18639
|
+
break;
|
|
18640
|
+
}
|
|
18641
|
+
case "tool-call-delta": {
|
|
18642
|
+
if (!textStreamDone) {
|
|
18643
|
+
textStreamDone = true;
|
|
18644
|
+
await streamCallback.onMessage({
|
|
18645
|
+
taskId: context.taskId,
|
|
18646
|
+
agentName: agentNode.name,
|
|
18647
|
+
nodeId: agentNode.id,
|
|
18648
|
+
type: "text",
|
|
18649
|
+
streamId,
|
|
18650
|
+
streamDone: true,
|
|
18651
|
+
text: streamText,
|
|
18652
|
+
});
|
|
18653
|
+
}
|
|
18654
|
+
toolArgsText += chunk.argsTextDelta || "";
|
|
18655
|
+
await streamCallback.onMessage({
|
|
18656
|
+
taskId: context.taskId,
|
|
18657
|
+
agentName: agentNode.name,
|
|
18658
|
+
nodeId: agentNode.id,
|
|
18659
|
+
type: "tool_streaming",
|
|
18660
|
+
toolId: chunk.toolCallId,
|
|
18661
|
+
toolName: chunk.toolName,
|
|
18662
|
+
paramsText: toolArgsText,
|
|
18663
|
+
});
|
|
18664
|
+
break;
|
|
18665
|
+
}
|
|
18666
|
+
case "tool-call": {
|
|
18667
|
+
toolArgsText = "";
|
|
18668
|
+
let args = chunk.args ? JSON.parse(chunk.args) : {};
|
|
18669
|
+
await streamCallback.onMessage({
|
|
18670
|
+
taskId: context.taskId,
|
|
18671
|
+
agentName: agentNode.name,
|
|
18672
|
+
nodeId: agentNode.id,
|
|
18673
|
+
type: "tool_use",
|
|
18674
|
+
toolId: chunk.toolCallId,
|
|
18675
|
+
toolName: chunk.toolName,
|
|
18676
|
+
params: args,
|
|
18677
|
+
});
|
|
18678
|
+
toolParts.push({
|
|
18679
|
+
type: "tool-call",
|
|
18680
|
+
toolCallId: chunk.toolCallId,
|
|
18681
|
+
toolName: chunk.toolName,
|
|
18682
|
+
args: args,
|
|
18683
|
+
});
|
|
18684
|
+
break;
|
|
18685
|
+
}
|
|
18686
|
+
case "file": {
|
|
18687
|
+
await streamCallback.onMessage({
|
|
18688
|
+
taskId: context.taskId,
|
|
18689
|
+
agentName: agentNode.name,
|
|
18690
|
+
nodeId: agentNode.id,
|
|
18691
|
+
type: "file",
|
|
18692
|
+
mimeType: chunk.mimeType,
|
|
18693
|
+
data: chunk.data,
|
|
18694
|
+
});
|
|
18695
|
+
break;
|
|
18696
|
+
}
|
|
18697
|
+
case "error": {
|
|
18698
|
+
Log.error(`${agentNode.name} agent error: `, chunk);
|
|
18699
|
+
await streamCallback.onMessage({
|
|
18700
|
+
taskId: context.taskId,
|
|
18701
|
+
agentName: agentNode.name,
|
|
18702
|
+
nodeId: agentNode.id,
|
|
18703
|
+
type: "error",
|
|
18704
|
+
error: chunk.error,
|
|
18705
|
+
});
|
|
18706
|
+
throw new Error("Plan Error");
|
|
18707
|
+
}
|
|
18708
|
+
case "finish": {
|
|
18709
|
+
if (!textStreamDone) {
|
|
18710
|
+
textStreamDone = true;
|
|
18711
|
+
await streamCallback.onMessage({
|
|
18712
|
+
taskId: context.taskId,
|
|
18713
|
+
agentName: agentNode.name,
|
|
18714
|
+
nodeId: agentNode.id,
|
|
18715
|
+
type: "text",
|
|
18716
|
+
streamId,
|
|
18717
|
+
streamDone: true,
|
|
18718
|
+
text: streamText,
|
|
18719
|
+
});
|
|
18720
|
+
}
|
|
18721
|
+
await streamCallback.onMessage({
|
|
18722
|
+
taskId: context.taskId,
|
|
18723
|
+
agentName: agentNode.name,
|
|
18724
|
+
nodeId: agentNode.id,
|
|
18725
|
+
type: "finish",
|
|
18726
|
+
finishReason: chunk.finishReason,
|
|
18727
|
+
usage: chunk.usage,
|
|
18728
|
+
});
|
|
18729
|
+
break;
|
|
18730
|
+
}
|
|
18731
|
+
}
|
|
18732
|
+
}
|
|
18733
|
+
}
|
|
18734
|
+
finally {
|
|
18735
|
+
reader.releaseLock();
|
|
18736
|
+
}
|
|
18737
|
+
agentChain.agentResult = streamText;
|
|
18738
|
+
return streamText
|
|
18739
|
+
? [
|
|
18740
|
+
{ type: "text", text: streamText },
|
|
18741
|
+
...toolParts,
|
|
18742
|
+
]
|
|
18743
|
+
: toolParts;
|
|
18744
|
+
}
|
|
16575
18745
|
|
|
16576
18746
|
const AGENT_NAME$4 = "Chat";
|
|
16577
18747
|
class BaseChatAgent extends Agent {
|