@eko-ai/eko 2.0.3-alpha.2 → 2.0.3-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -159,10 +159,10 @@ class AgentContext {
159
159
  }
160
160
 
161
161
  // 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 {
162
+ var marker$1 = "vercel.ai.error";
163
+ var symbol$1 = Symbol.for(marker$1);
164
+ var _a$1;
165
+ var _AISDKError$1 = class _AISDKError extends Error {
166
166
  /**
167
167
  * Creates an AI SDK Error.
168
168
  *
@@ -177,7 +177,7 @@ var _AISDKError = class _AISDKError extends Error {
177
177
  cause
178
178
  }) {
179
179
  super(message);
180
- this[_a] = true;
180
+ this[_a$1] = true;
181
181
  this.name = name14;
182
182
  this.cause = cause;
183
183
  }
@@ -187,22 +187,22 @@ var _AISDKError = class _AISDKError extends Error {
187
187
  * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
188
188
  */
189
189
  static isInstance(error) {
190
- return _AISDKError.hasMarker(error, marker);
190
+ return _AISDKError.hasMarker(error, marker$1);
191
191
  }
192
192
  static hasMarker(error, marker15) {
193
193
  const markerSymbol = Symbol.for(marker15);
194
194
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
195
195
  }
196
196
  };
197
- _a = symbol;
198
- var AISDKError = _AISDKError;
197
+ _a$1 = symbol$1;
198
+ var AISDKError$1 = _AISDKError$1;
199
199
 
200
200
  // 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 {
201
+ var name$1 = "AI_APICallError";
202
+ var marker2$1 = `vercel.ai.error.${name$1}`;
203
+ var symbol2$1 = Symbol.for(marker2$1);
204
+ var _a2$1;
205
+ var APICallError$1 = class APICallError extends AISDKError$1 {
206
206
  constructor({
207
207
  message,
208
208
  url,
@@ -218,8 +218,8 @@ var APICallError = class extends AISDKError {
218
218
  // server error
219
219
  data
220
220
  }) {
221
- super({ name, message, cause });
222
- this[_a2] = true;
221
+ super({ name: name$1, message, cause });
222
+ this[_a2$1] = true;
223
223
  this.url = url;
224
224
  this.requestBodyValues = requestBodyValues;
225
225
  this.statusCode = statusCode;
@@ -229,30 +229,30 @@ var APICallError = class extends AISDKError {
229
229
  this.data = data;
230
230
  }
231
231
  static isInstance(error) {
232
- return AISDKError.hasMarker(error, marker2);
232
+ return AISDKError$1.hasMarker(error, marker2$1);
233
233
  }
234
234
  };
235
- _a2 = symbol2;
235
+ _a2$1 = symbol2$1;
236
236
 
237
237
  // 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 {
238
+ var name2$1 = "AI_EmptyResponseBodyError";
239
+ var marker3$1 = `vercel.ai.error.${name2$1}`;
240
+ var symbol3$1 = Symbol.for(marker3$1);
241
+ var _a3$1;
242
+ var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 {
243
243
  // used in isInstance
244
244
  constructor({ message = "Empty response body" } = {}) {
245
- super({ name: name2, message });
246
- this[_a3] = true;
245
+ super({ name: name2$1, message });
246
+ this[_a3$1] = true;
247
247
  }
248
248
  static isInstance(error) {
249
- return AISDKError.hasMarker(error, marker3);
249
+ return AISDKError$1.hasMarker(error, marker3$1);
250
250
  }
251
251
  };
252
- _a3 = symbol3;
252
+ _a3$1 = symbol3$1;
253
253
 
254
254
  // src/errors/get-error-message.ts
255
- function getErrorMessage(error) {
255
+ function getErrorMessage$1(error) {
256
256
  if (error == null) {
257
257
  return "unknown error";
258
258
  }
@@ -266,119 +266,119 @@ function getErrorMessage(error) {
266
266
  }
267
267
 
268
268
  // 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 {
269
+ var name3$1 = "AI_InvalidArgumentError";
270
+ var marker4$1 = `vercel.ai.error.${name3$1}`;
271
+ var symbol4$1 = Symbol.for(marker4$1);
272
+ var _a4$1;
273
+ var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 {
274
274
  constructor({
275
275
  message,
276
276
  cause,
277
277
  argument
278
278
  }) {
279
- super({ name: name3, message, cause });
280
- this[_a4] = true;
279
+ super({ name: name3$1, message, cause });
280
+ this[_a4$1] = true;
281
281
  this.argument = argument;
282
282
  }
283
283
  static isInstance(error) {
284
- return AISDKError.hasMarker(error, marker4);
284
+ return AISDKError$1.hasMarker(error, marker4$1);
285
285
  }
286
286
  };
287
- _a4 = symbol4;
287
+ _a4$1 = symbol4$1;
288
288
 
289
289
  // 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 {
290
+ var name4$1 = "AI_InvalidPromptError";
291
+ var marker5$1 = `vercel.ai.error.${name4$1}`;
292
+ var symbol5$1 = Symbol.for(marker5$1);
293
+ var _a5$1;
294
+ var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 {
295
295
  constructor({
296
296
  prompt,
297
297
  message,
298
298
  cause
299
299
  }) {
300
- super({ name: name4, message: `Invalid prompt: ${message}`, cause });
301
- this[_a5] = true;
300
+ super({ name: name4$1, message: `Invalid prompt: ${message}`, cause });
301
+ this[_a5$1] = true;
302
302
  this.prompt = prompt;
303
303
  }
304
304
  static isInstance(error) {
305
- return AISDKError.hasMarker(error, marker5);
305
+ return AISDKError$1.hasMarker(error, marker5$1);
306
306
  }
307
307
  };
308
- _a5 = symbol5;
308
+ _a5$1 = symbol5$1;
309
309
 
310
310
  // 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 {
311
+ var name5$1 = "AI_InvalidResponseDataError";
312
+ var marker6$1 = `vercel.ai.error.${name5$1}`;
313
+ var symbol6$1 = Symbol.for(marker6$1);
314
+ var _a6$1;
315
+ var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 {
316
316
  constructor({
317
317
  data,
318
318
  message = `Invalid response data: ${JSON.stringify(data)}.`
319
319
  }) {
320
- super({ name: name5, message });
321
- this[_a6] = true;
320
+ super({ name: name5$1, message });
321
+ this[_a6$1] = true;
322
322
  this.data = data;
323
323
  }
324
324
  static isInstance(error) {
325
- return AISDKError.hasMarker(error, marker6);
325
+ return AISDKError$1.hasMarker(error, marker6$1);
326
326
  }
327
327
  };
328
- _a6 = symbol6;
328
+ _a6$1 = symbol6$1;
329
329
 
330
330
  // 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 {
331
+ var name6$1 = "AI_JSONParseError";
332
+ var marker7$1 = `vercel.ai.error.${name6$1}`;
333
+ var symbol7$1 = Symbol.for(marker7$1);
334
+ var _a7$1;
335
+ var JSONParseError$1 = class JSONParseError extends AISDKError$1 {
336
336
  constructor({ text, cause }) {
337
337
  super({
338
- name: name6,
338
+ name: name6$1,
339
339
  message: `JSON parsing failed: Text: ${text}.
340
- Error message: ${getErrorMessage(cause)}`,
340
+ Error message: ${getErrorMessage$1(cause)}`,
341
341
  cause
342
342
  });
343
- this[_a7] = true;
343
+ this[_a7$1] = true;
344
344
  this.text = text;
345
345
  }
346
346
  static isInstance(error) {
347
- return AISDKError.hasMarker(error, marker7);
347
+ return AISDKError$1.hasMarker(error, marker7$1);
348
348
  }
349
349
  };
350
- _a7 = symbol7;
350
+ _a7$1 = symbol7$1;
351
351
 
352
352
  // 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 {
353
+ var name7$1 = "AI_LoadAPIKeyError";
354
+ var marker8$1 = `vercel.ai.error.${name7$1}`;
355
+ var symbol8$1 = Symbol.for(marker8$1);
356
+ var _a8$1;
357
+ var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 {
358
358
  // used in isInstance
359
359
  constructor({ message }) {
360
- super({ name: name7, message });
361
- this[_a8] = true;
360
+ super({ name: name7$1, message });
361
+ this[_a8$1] = true;
362
362
  }
363
363
  static isInstance(error) {
364
- return AISDKError.hasMarker(error, marker8);
364
+ return AISDKError$1.hasMarker(error, marker8$1);
365
365
  }
366
366
  };
367
- _a8 = symbol8;
367
+ _a8$1 = symbol8$1;
368
368
 
369
369
  // src/errors/load-setting-error.ts
370
370
  var name8 = "AI_LoadSettingError";
371
371
  var marker9 = `vercel.ai.error.${name8}`;
372
372
  var symbol9 = Symbol.for(marker9);
373
373
  var _a9;
374
- var LoadSettingError = class extends AISDKError {
374
+ var LoadSettingError = class extends AISDKError$1 {
375
375
  // used in isInstance
376
376
  constructor({ message }) {
377
377
  super({ name: name8, message });
378
378
  this[_a9] = true;
379
379
  }
380
380
  static isInstance(error) {
381
- return AISDKError.hasMarker(error, marker9);
381
+ return AISDKError$1.hasMarker(error, marker9);
382
382
  }
383
383
  };
384
384
  _a9 = symbol9;
@@ -388,7 +388,7 @@ var name10 = "AI_NoSuchModelError";
388
388
  var marker11 = `vercel.ai.error.${name10}`;
389
389
  var symbol11 = Symbol.for(marker11);
390
390
  var _a11;
391
- var NoSuchModelError = class extends AISDKError {
391
+ var NoSuchModelError = class extends AISDKError$1 {
392
392
  constructor({
393
393
  errorName = name10,
394
394
  modelId,
@@ -401,7 +401,7 @@ var NoSuchModelError = class extends AISDKError {
401
401
  this.modelType = modelType;
402
402
  }
403
403
  static isInstance(error) {
404
- return AISDKError.hasMarker(error, marker11);
404
+ return AISDKError$1.hasMarker(error, marker11);
405
405
  }
406
406
  };
407
407
  _a11 = symbol11;
@@ -411,7 +411,7 @@ var name11 = "AI_TooManyEmbeddingValuesForCallError";
411
411
  var marker12 = `vercel.ai.error.${name11}`;
412
412
  var symbol12 = Symbol.for(marker12);
413
413
  var _a12;
414
- var TooManyEmbeddingValuesForCallError = class extends AISDKError {
414
+ var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 {
415
415
  constructor(options) {
416
416
  super({
417
417
  name: name11,
@@ -424,29 +424,29 @@ var TooManyEmbeddingValuesForCallError = class extends AISDKError {
424
424
  this.values = options.values;
425
425
  }
426
426
  static isInstance(error) {
427
- return AISDKError.hasMarker(error, marker12);
427
+ return AISDKError$1.hasMarker(error, marker12);
428
428
  }
429
429
  };
430
430
  _a12 = symbol12;
431
431
 
432
432
  // 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 {
433
+ var name12$1 = "AI_TypeValidationError";
434
+ var marker13$1 = `vercel.ai.error.${name12$1}`;
435
+ var symbol13$1 = Symbol.for(marker13$1);
436
+ var _a13$1;
437
+ var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 {
438
438
  constructor({ value, cause }) {
439
439
  super({
440
- name: name12,
440
+ name: name12$1,
441
441
  message: `Type validation failed: Value: ${JSON.stringify(value)}.
442
- Error message: ${getErrorMessage(cause)}`,
442
+ Error message: ${getErrorMessage$1(cause)}`,
443
443
  cause
444
444
  });
445
- this[_a13] = true;
445
+ this[_a13$1] = true;
446
446
  this.value = value;
447
447
  }
448
448
  static isInstance(error) {
449
- return AISDKError.hasMarker(error, marker13);
449
+ return AISDKError$1.hasMarker(error, marker13$1);
450
450
  }
451
451
  /**
452
452
  * Wraps an error into a TypeValidationError.
@@ -465,28 +465,28 @@ Error message: ${getErrorMessage(cause)}`,
465
465
  return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
466
466
  }
467
467
  };
468
- _a13 = symbol13;
469
- var TypeValidationError = _TypeValidationError;
468
+ _a13$1 = symbol13$1;
469
+ var TypeValidationError$1 = _TypeValidationError$1;
470
470
 
471
471
  // 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 {
472
+ var name13$1 = "AI_UnsupportedFunctionalityError";
473
+ var marker14$1 = `vercel.ai.error.${name13$1}`;
474
+ var symbol14$1 = Symbol.for(marker14$1);
475
+ var _a14$1;
476
+ var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 {
477
477
  constructor({
478
478
  functionality,
479
479
  message = `'${functionality}' functionality not supported.`
480
480
  }) {
481
- super({ name: name13, message });
482
- this[_a14] = true;
481
+ super({ name: name13$1, message });
482
+ this[_a14$1] = true;
483
483
  this.functionality = functionality;
484
484
  }
485
485
  static isInstance(error) {
486
- return AISDKError.hasMarker(error, marker14);
486
+ return AISDKError$1.hasMarker(error, marker14$1);
487
487
  }
488
488
  };
489
- _a14 = symbol14;
489
+ _a14$1 = symbol14$1;
490
490
 
491
491
  let customAlphabet = (alphabet, defaultSize = 21) => {
492
492
  return (size = defaultSize) => {
@@ -503,13 +503,13 @@ function getDefaultExportFromCjs (x) {
503
503
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
504
504
  }
505
505
 
506
- var secureJsonParse = {exports: {}};
506
+ var secureJsonParse$1 = {exports: {}};
507
507
 
508
- var hasRequiredSecureJsonParse;
508
+ var hasRequiredSecureJsonParse$1;
509
509
 
510
- function requireSecureJsonParse () {
511
- if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
512
- hasRequiredSecureJsonParse = 1;
510
+ function requireSecureJsonParse$1 () {
511
+ if (hasRequiredSecureJsonParse$1) return secureJsonParse$1.exports;
512
+ hasRequiredSecureJsonParse$1 = 1;
513
513
 
514
514
  const hasBuffer = typeof Buffer !== 'undefined';
515
515
  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 +630,19 @@ function requireSecureJsonParse () {
630
630
  }
631
631
  }
632
632
 
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;
633
+ secureJsonParse$1.exports = parse;
634
+ secureJsonParse$1.exports.default = parse;
635
+ secureJsonParse$1.exports.parse = parse;
636
+ secureJsonParse$1.exports.safeParse = safeParse;
637
+ secureJsonParse$1.exports.scan = filter;
638
+ return secureJsonParse$1.exports;
639
639
  }
640
640
 
641
- var secureJsonParseExports = requireSecureJsonParse();
642
- var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
641
+ var secureJsonParseExports$1 = requireSecureJsonParse$1();
642
+ var SecureJSON$1 = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports$1);
643
643
 
644
644
  // src/combine-headers.ts
645
- function combineHeaders(...headers) {
645
+ function combineHeaders$1(...headers) {
646
646
  return headers.reduce(
647
647
  (combinedHeaders, currentHeaders) => ({
648
648
  ...combinedHeaders,
@@ -711,7 +711,7 @@ function createEventSourceParserStream() {
711
711
  }
712
712
  return new TransformStream({
713
713
  transform(chunk, controller) {
714
- const { lines, incompleteLine } = splitLines(buffer, chunk);
714
+ const { lines, incompleteLine } = splitLines$1(buffer, chunk);
715
715
  buffer = incompleteLine;
716
716
  for (let i = 0; i < lines.length; i++) {
717
717
  parseLine(lines[i], controller);
@@ -723,7 +723,7 @@ function createEventSourceParserStream() {
723
723
  }
724
724
  });
725
725
  }
726
- function splitLines(buffer, chunk) {
726
+ function splitLines$1(buffer, chunk) {
727
727
  const lines = [];
728
728
  let currentLine = buffer;
729
729
  for (let i = 0; i < chunk.length; ) {
@@ -745,14 +745,14 @@ function splitLines(buffer, chunk) {
745
745
  }
746
746
 
747
747
  // src/extract-response-headers.ts
748
- function extractResponseHeaders(response) {
748
+ function extractResponseHeaders$1(response) {
749
749
  const headers = {};
750
750
  response.headers.forEach((value, key) => {
751
751
  headers[key] = value;
752
752
  });
753
753
  return headers;
754
754
  }
755
- var createIdGenerator = ({
755
+ var createIdGenerator$1 = ({
756
756
  prefix,
757
757
  size: defaultSize = 16,
758
758
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
@@ -763,27 +763,27 @@ var createIdGenerator = ({
763
763
  return generator;
764
764
  }
765
765
  if (alphabet.includes(separator)) {
766
- throw new InvalidArgumentError({
766
+ throw new InvalidArgumentError$1({
767
767
  argument: "separator",
768
768
  message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
769
769
  });
770
770
  }
771
771
  return (size) => `${prefix}${separator}${generator(size)}`;
772
772
  };
773
- var generateId = createIdGenerator();
773
+ var generateId$1 = createIdGenerator$1();
774
774
 
775
775
  // src/remove-undefined-entries.ts
776
- function removeUndefinedEntries(record) {
776
+ function removeUndefinedEntries$1(record) {
777
777
  return Object.fromEntries(
778
778
  Object.entries(record).filter(([_key, value]) => value != null)
779
779
  );
780
780
  }
781
781
 
782
782
  // src/is-abort-error.ts
783
- function isAbortError(error) {
783
+ function isAbortError$1(error) {
784
784
  return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
785
785
  }
786
- function loadApiKey({
786
+ function loadApiKey$1({
787
787
  apiKey,
788
788
  environmentVariableName,
789
789
  apiKeyParameterName = "apiKey",
@@ -793,23 +793,23 @@ function loadApiKey({
793
793
  return apiKey;
794
794
  }
795
795
  if (apiKey != null) {
796
- throw new LoadAPIKeyError({
796
+ throw new LoadAPIKeyError$1({
797
797
  message: `${description} API key must be a string.`
798
798
  });
799
799
  }
800
800
  if (typeof process === "undefined") {
801
- throw new LoadAPIKeyError({
801
+ throw new LoadAPIKeyError$1({
802
802
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
803
803
  });
804
804
  }
805
805
  apiKey = process.env[environmentVariableName];
806
806
  if (apiKey == null) {
807
- throw new LoadAPIKeyError({
807
+ throw new LoadAPIKeyError$1({
808
808
  message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
809
809
  });
810
810
  }
811
811
  if (typeof apiKey !== "string") {
812
- throw new LoadAPIKeyError({
812
+ throw new LoadAPIKeyError$1({
813
813
  message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
814
814
  });
815
815
  }
@@ -867,39 +867,39 @@ function loadSetting({
867
867
  }
868
868
 
869
869
  // src/validator.ts
870
- var validatorSymbol = Symbol.for("vercel.ai.validator");
871
- function validator(validate) {
872
- return { [validatorSymbol]: true, validate };
870
+ var validatorSymbol$1 = Symbol.for("vercel.ai.validator");
871
+ function validator$1(validate) {
872
+ return { [validatorSymbol$1]: true, validate };
873
873
  }
874
- function isValidator(value) {
875
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
874
+ function isValidator$1(value) {
875
+ return typeof value === "object" && value !== null && validatorSymbol$1 in value && value[validatorSymbol$1] === true && "validate" in value;
876
876
  }
877
- function asValidator(value) {
878
- return isValidator(value) ? value : zodValidator(value);
877
+ function asValidator$1(value) {
878
+ return isValidator$1(value) ? value : zodValidator$1(value);
879
879
  }
880
- function zodValidator(zodSchema) {
881
- return validator((value) => {
880
+ function zodValidator$1(zodSchema) {
881
+ return validator$1((value) => {
882
882
  const result = zodSchema.safeParse(value);
883
883
  return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
884
884
  });
885
885
  }
886
886
 
887
887
  // src/validate-types.ts
888
- function validateTypes({
888
+ function validateTypes$1({
889
889
  value,
890
890
  schema: inputSchema
891
891
  }) {
892
- const result = safeValidateTypes({ value, schema: inputSchema });
892
+ const result = safeValidateTypes$1({ value, schema: inputSchema });
893
893
  if (!result.success) {
894
- throw TypeValidationError.wrap({ value, cause: result.error });
894
+ throw TypeValidationError$1.wrap({ value, cause: result.error });
895
895
  }
896
896
  return result.value;
897
897
  }
898
- function safeValidateTypes({
898
+ function safeValidateTypes$1({
899
899
  value,
900
900
  schema
901
901
  }) {
902
- const validator2 = asValidator(schema);
902
+ const validator2 = asValidator$1(schema);
903
903
  try {
904
904
  if (validator2.validate == null) {
905
905
  return { success: true, value };
@@ -910,55 +910,55 @@ function safeValidateTypes({
910
910
  }
911
911
  return {
912
912
  success: false,
913
- error: TypeValidationError.wrap({ value, cause: result.error })
913
+ error: TypeValidationError$1.wrap({ value, cause: result.error })
914
914
  };
915
915
  } catch (error) {
916
916
  return {
917
917
  success: false,
918
- error: TypeValidationError.wrap({ value, cause: error })
918
+ error: TypeValidationError$1.wrap({ value, cause: error })
919
919
  };
920
920
  }
921
921
  }
922
922
 
923
923
  // src/parse-json.ts
924
- function parseJSON({
924
+ function parseJSON$1({
925
925
  text,
926
926
  schema
927
927
  }) {
928
928
  try {
929
- const value = SecureJSON.parse(text);
929
+ const value = SecureJSON$1.parse(text);
930
930
  if (schema == null) {
931
931
  return value;
932
932
  }
933
- return validateTypes({ value, schema });
933
+ return validateTypes$1({ value, schema });
934
934
  } catch (error) {
935
- if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
935
+ if (JSONParseError$1.isInstance(error) || TypeValidationError$1.isInstance(error)) {
936
936
  throw error;
937
937
  }
938
- throw new JSONParseError({ text, cause: error });
938
+ throw new JSONParseError$1({ text, cause: error });
939
939
  }
940
940
  }
941
- function safeParseJSON({
941
+ function safeParseJSON$1({
942
942
  text,
943
943
  schema
944
944
  }) {
945
945
  try {
946
- const value = SecureJSON.parse(text);
946
+ const value = SecureJSON$1.parse(text);
947
947
  if (schema == null) {
948
948
  return { success: true, value, rawValue: value };
949
949
  }
950
- const validationResult = safeValidateTypes({ value, schema });
950
+ const validationResult = safeValidateTypes$1({ value, schema });
951
951
  return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
952
952
  } catch (error) {
953
953
  return {
954
954
  success: false,
955
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
955
+ error: JSONParseError$1.isInstance(error) ? error : new JSONParseError$1({ text, cause: error })
956
956
  };
957
957
  }
958
958
  }
959
- function isParsableJson(input) {
959
+ function isParsableJson$1(input) {
960
960
  try {
961
- SecureJSON.parse(input);
961
+ SecureJSON$1.parse(input);
962
962
  return true;
963
963
  } catch (e) {
964
964
  return false;
@@ -972,12 +972,12 @@ function parseProviderOptions({
972
972
  if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
973
973
  return void 0;
974
974
  }
975
- const parsedProviderOptions = safeValidateTypes({
975
+ const parsedProviderOptions = safeValidateTypes$1({
976
976
  value: providerOptions[provider],
977
977
  schema
978
978
  });
979
979
  if (!parsedProviderOptions.success) {
980
- throw new InvalidArgumentError({
980
+ throw new InvalidArgumentError$1({
981
981
  argument: "providerOptions",
982
982
  message: `invalid ${provider} provider options`,
983
983
  cause: parsedProviderOptions.error
@@ -985,8 +985,8 @@ function parseProviderOptions({
985
985
  }
986
986
  return parsedProviderOptions.value;
987
987
  }
988
- var getOriginalFetch2 = () => globalThis.fetch;
989
- var postJsonToApi = async ({
988
+ var getOriginalFetch2$1 = () => globalThis.fetch;
989
+ var postJsonToApi$1 = async ({
990
990
  url,
991
991
  headers,
992
992
  body,
@@ -994,7 +994,7 @@ var postJsonToApi = async ({
994
994
  successfulResponseHandler,
995
995
  abortSignal,
996
996
  fetch
997
- }) => postToApi({
997
+ }) => postToApi$1({
998
998
  url,
999
999
  headers: {
1000
1000
  "Content-Type": "application/json",
@@ -1017,7 +1017,7 @@ var postFormDataToApi = async ({
1017
1017
  successfulResponseHandler,
1018
1018
  abortSignal,
1019
1019
  fetch
1020
- }) => postToApi({
1020
+ }) => postToApi$1({
1021
1021
  url,
1022
1022
  headers,
1023
1023
  body: {
@@ -1029,23 +1029,23 @@ var postFormDataToApi = async ({
1029
1029
  abortSignal,
1030
1030
  fetch
1031
1031
  });
1032
- var postToApi = async ({
1032
+ var postToApi$1 = async ({
1033
1033
  url,
1034
1034
  headers = {},
1035
1035
  body,
1036
1036
  successfulResponseHandler,
1037
1037
  failedResponseHandler,
1038
1038
  abortSignal,
1039
- fetch = getOriginalFetch2()
1039
+ fetch = getOriginalFetch2$1()
1040
1040
  }) => {
1041
1041
  try {
1042
1042
  const response = await fetch(url, {
1043
1043
  method: "POST",
1044
- headers: removeUndefinedEntries(headers),
1044
+ headers: removeUndefinedEntries$1(headers),
1045
1045
  body: body.content,
1046
1046
  signal: abortSignal
1047
1047
  });
1048
- const responseHeaders = extractResponseHeaders(response);
1048
+ const responseHeaders = extractResponseHeaders$1(response);
1049
1049
  if (!response.ok) {
1050
1050
  let errorInformation;
1051
1051
  try {
@@ -1055,10 +1055,10 @@ var postToApi = async ({
1055
1055
  requestBodyValues: body.values
1056
1056
  });
1057
1057
  } catch (error) {
1058
- if (isAbortError(error) || APICallError.isInstance(error)) {
1058
+ if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1059
1059
  throw error;
1060
1060
  }
1061
- throw new APICallError({
1061
+ throw new APICallError$1({
1062
1062
  message: "Failed to process error response",
1063
1063
  cause: error,
1064
1064
  statusCode: response.status,
@@ -1077,11 +1077,11 @@ var postToApi = async ({
1077
1077
  });
1078
1078
  } catch (error) {
1079
1079
  if (error instanceof Error) {
1080
- if (isAbortError(error) || APICallError.isInstance(error)) {
1080
+ if (isAbortError$1(error) || APICallError$1.isInstance(error)) {
1081
1081
  throw error;
1082
1082
  }
1083
1083
  }
1084
- throw new APICallError({
1084
+ throw new APICallError$1({
1085
1085
  message: "Failed to process successful response",
1086
1086
  cause: error,
1087
1087
  statusCode: response.status,
@@ -1091,13 +1091,13 @@ var postToApi = async ({
1091
1091
  });
1092
1092
  }
1093
1093
  } catch (error) {
1094
- if (isAbortError(error)) {
1094
+ if (isAbortError$1(error)) {
1095
1095
  throw error;
1096
1096
  }
1097
1097
  if (error instanceof TypeError && error.message === "fetch failed") {
1098
1098
  const cause = error.cause;
1099
1099
  if (cause != null) {
1100
- throw new APICallError({
1100
+ throw new APICallError$1({
1101
1101
  message: `Cannot connect to API: ${cause.message}`,
1102
1102
  cause,
1103
1103
  url,
@@ -1118,17 +1118,17 @@ async function resolve(value) {
1118
1118
  }
1119
1119
  return Promise.resolve(value);
1120
1120
  }
1121
- var createJsonErrorResponseHandler = ({
1121
+ var createJsonErrorResponseHandler$1 = ({
1122
1122
  errorSchema,
1123
1123
  errorToMessage,
1124
1124
  isRetryable
1125
1125
  }) => async ({ response, url, requestBodyValues }) => {
1126
1126
  const responseBody = await response.text();
1127
- const responseHeaders = extractResponseHeaders(response);
1127
+ const responseHeaders = extractResponseHeaders$1(response);
1128
1128
  if (responseBody.trim() === "") {
1129
1129
  return {
1130
1130
  responseHeaders,
1131
- value: new APICallError({
1131
+ value: new APICallError$1({
1132
1132
  message: response.statusText,
1133
1133
  url,
1134
1134
  requestBodyValues,
@@ -1140,13 +1140,13 @@ var createJsonErrorResponseHandler = ({
1140
1140
  };
1141
1141
  }
1142
1142
  try {
1143
- const parsedError = parseJSON({
1143
+ const parsedError = parseJSON$1({
1144
1144
  text: responseBody,
1145
1145
  schema: errorSchema
1146
1146
  });
1147
1147
  return {
1148
1148
  responseHeaders,
1149
- value: new APICallError({
1149
+ value: new APICallError$1({
1150
1150
  message: errorToMessage(parsedError),
1151
1151
  url,
1152
1152
  requestBodyValues,
@@ -1160,7 +1160,7 @@ var createJsonErrorResponseHandler = ({
1160
1160
  } catch (parseError) {
1161
1161
  return {
1162
1162
  responseHeaders,
1163
- value: new APICallError({
1163
+ value: new APICallError$1({
1164
1164
  message: response.statusText,
1165
1165
  url,
1166
1166
  requestBodyValues,
@@ -1172,10 +1172,10 @@ var createJsonErrorResponseHandler = ({
1172
1172
  };
1173
1173
  }
1174
1174
  };
1175
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
1176
- const responseHeaders = extractResponseHeaders(response);
1175
+ var createEventSourceResponseHandler$1 = (chunkSchema) => async ({ response }) => {
1176
+ const responseHeaders = extractResponseHeaders$1(response);
1177
1177
  if (response.body == null) {
1178
- throw new EmptyResponseBodyError({});
1178
+ throw new EmptyResponseBodyError$1({});
1179
1179
  }
1180
1180
  return {
1181
1181
  responseHeaders,
@@ -1186,7 +1186,7 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
1186
1186
  return;
1187
1187
  }
1188
1188
  controller.enqueue(
1189
- safeParseJSON({
1189
+ safeParseJSON$1({
1190
1190
  text: data,
1191
1191
  schema: chunkSchema
1192
1192
  })
@@ -1196,15 +1196,15 @@ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) =>
1196
1196
  )
1197
1197
  };
1198
1198
  };
1199
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1199
+ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, requestBodyValues }) => {
1200
1200
  const responseBody = await response.text();
1201
- const parsedResult = safeParseJSON({
1201
+ const parsedResult = safeParseJSON$1({
1202
1202
  text: responseBody,
1203
1203
  schema: responseSchema
1204
1204
  });
1205
- const responseHeaders = extractResponseHeaders(response);
1205
+ const responseHeaders = extractResponseHeaders$1(response);
1206
1206
  if (!parsedResult.success) {
1207
- throw new APICallError({
1207
+ throw new APICallError$1({
1208
1208
  message: "Invalid JSON response",
1209
1209
  cause: parsedResult.error,
1210
1210
  statusCode: response.status,
@@ -1221,9 +1221,9 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
1221
1221
  };
1222
1222
  };
1223
1223
  var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
1224
- const responseHeaders = extractResponseHeaders(response);
1224
+ const responseHeaders = extractResponseHeaders$1(response);
1225
1225
  if (!response.body) {
1226
- throw new APICallError({
1226
+ throw new APICallError$1({
1227
1227
  message: "Response body is empty",
1228
1228
  url,
1229
1229
  requestBodyValues,
@@ -1239,7 +1239,7 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1239
1239
  value: new Uint8Array(buffer)
1240
1240
  };
1241
1241
  } catch (error) {
1242
- throw new APICallError({
1242
+ throw new APICallError$1({
1243
1243
  message: "Failed to read response as array buffer",
1244
1244
  url,
1245
1245
  requestBodyValues,
@@ -1252,22 +1252,22 @@ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValue
1252
1252
  };
1253
1253
 
1254
1254
  // src/uint8-utils.ts
1255
- var { btoa, atob: atob$1 } = globalThis;
1255
+ var { btoa: btoa$1, atob: atob$1 } = globalThis;
1256
1256
  function convertBase64ToUint8Array(base64String) {
1257
1257
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
1258
1258
  const latin1string = atob$1(base64Url);
1259
1259
  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
1260
1260
  }
1261
- function convertUint8ArrayToBase64(array) {
1261
+ function convertUint8ArrayToBase64$1(array) {
1262
1262
  let latin1string = "";
1263
1263
  for (let i = 0; i < array.length; i++) {
1264
1264
  latin1string += String.fromCodePoint(array[i]);
1265
1265
  }
1266
- return btoa(latin1string);
1266
+ return btoa$1(latin1string);
1267
1267
  }
1268
1268
 
1269
1269
  // src/without-trailing-slash.ts
1270
- function withoutTrailingSlash(url) {
1270
+ function withoutTrailingSlash$1(url) {
1271
1271
  return url == null ? void 0 : url.replace(/\/$/, "");
1272
1272
  }
1273
1273
 
@@ -5725,7 +5725,7 @@ function convertToOpenAIChatMessages({
5725
5725
  return {
5726
5726
  type: "image_url",
5727
5727
  image_url: {
5728
- url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
5728
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
5729
5729
  // OpenAI specific extension: image detail
5730
5730
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
5731
5731
  }
@@ -5733,7 +5733,7 @@ function convertToOpenAIChatMessages({
5733
5733
  }
5734
5734
  case "file": {
5735
5735
  if (part.data instanceof URL) {
5736
- throw new UnsupportedFunctionalityError({
5736
+ throw new UnsupportedFunctionalityError$1({
5737
5737
  functionality: "'File content parts with URL data' functionality not supported."
5738
5738
  });
5739
5739
  }
@@ -5761,7 +5761,7 @@ function convertToOpenAIChatMessages({
5761
5761
  };
5762
5762
  }
5763
5763
  default: {
5764
- throw new UnsupportedFunctionalityError({
5764
+ throw new UnsupportedFunctionalityError$1({
5765
5765
  functionality: `File content part type ${part.mimeType} in user messages`
5766
5766
  });
5767
5767
  }
@@ -5796,7 +5796,7 @@ function convertToOpenAIChatMessages({
5796
5796
  }
5797
5797
  if (useLegacyFunctionCalling) {
5798
5798
  if (toolCalls.length > 1) {
5799
- throw new UnsupportedFunctionalityError({
5799
+ throw new UnsupportedFunctionalityError$1({
5800
5800
  functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
5801
5801
  });
5802
5802
  }
@@ -5881,7 +5881,7 @@ var openaiErrorDataSchema = z.object({
5881
5881
  code: z.union([z.string(), z.number()]).nullish()
5882
5882
  })
5883
5883
  });
5884
- var openaiFailedResponseHandler = createJsonErrorResponseHandler({
5884
+ var openaiFailedResponseHandler = createJsonErrorResponseHandler$1({
5885
5885
  errorSchema: openaiErrorDataSchema,
5886
5886
  errorToMessage: (data) => data.error.message
5887
5887
  });
@@ -5941,7 +5941,7 @@ function prepareTools$3({
5941
5941
  toolWarnings
5942
5942
  };
5943
5943
  case "required":
5944
- throw new UnsupportedFunctionalityError({
5944
+ throw new UnsupportedFunctionalityError$1({
5945
5945
  functionality: "useLegacyFunctionCalling and toolChoice: required"
5946
5946
  });
5947
5947
  default:
@@ -5990,7 +5990,7 @@ function prepareTools$3({
5990
5990
  };
5991
5991
  default: {
5992
5992
  const _exhaustiveCheck = type;
5993
- throw new UnsupportedFunctionalityError({
5993
+ throw new UnsupportedFunctionalityError$1({
5994
5994
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
5995
5995
  });
5996
5996
  }
@@ -6053,12 +6053,12 @@ var OpenAIChatLanguageModel = class {
6053
6053
  }
6054
6054
  const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
6055
6055
  if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
6056
- throw new UnsupportedFunctionalityError({
6056
+ throw new UnsupportedFunctionalityError$1({
6057
6057
  functionality: "useLegacyFunctionCalling with parallelToolCalls"
6058
6058
  });
6059
6059
  }
6060
6060
  if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
6061
- throw new UnsupportedFunctionalityError({
6061
+ throw new UnsupportedFunctionalityError$1({
6062
6062
  functionality: "structuredOutputs with useLegacyFunctionCalling"
6063
6063
  });
6064
6064
  }
@@ -6259,15 +6259,15 @@ var OpenAIChatLanguageModel = class {
6259
6259
  responseHeaders,
6260
6260
  value: response,
6261
6261
  rawValue: rawResponse
6262
- } = await postJsonToApi({
6262
+ } = await postJsonToApi$1({
6263
6263
  url: this.config.url({
6264
6264
  path: "/chat/completions",
6265
6265
  modelId: this.modelId
6266
6266
  }),
6267
- headers: combineHeaders(this.config.headers(), options.headers),
6267
+ headers: combineHeaders$1(this.config.headers(), options.headers),
6268
6268
  body,
6269
6269
  failedResponseHandler: openaiFailedResponseHandler,
6270
- successfulResponseHandler: createJsonResponseHandler(
6270
+ successfulResponseHandler: createJsonResponseHandler$1(
6271
6271
  openaiChatResponseSchema
6272
6272
  ),
6273
6273
  abortSignal: options.abortSignal,
@@ -6295,7 +6295,7 @@ var OpenAIChatLanguageModel = class {
6295
6295
  toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
6296
6296
  {
6297
6297
  toolCallType: "function",
6298
- toolCallId: generateId(),
6298
+ toolCallId: generateId$1(),
6299
6299
  toolName: choice.message.function_call.name,
6300
6300
  args: choice.message.function_call.arguments
6301
6301
  }
@@ -6303,7 +6303,7 @@ var OpenAIChatLanguageModel = class {
6303
6303
  var _a2;
6304
6304
  return {
6305
6305
  toolCallType: "function",
6306
- toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
6306
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId$1(),
6307
6307
  toolName: toolCall.function.name,
6308
6308
  args: toolCall.function.arguments
6309
6309
  };
@@ -6373,15 +6373,15 @@ var OpenAIChatLanguageModel = class {
6373
6373
  // only include stream_options when in strict compatibility mode:
6374
6374
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
6375
6375
  };
6376
- const { responseHeaders, value: response } = await postJsonToApi({
6376
+ const { responseHeaders, value: response } = await postJsonToApi$1({
6377
6377
  url: this.config.url({
6378
6378
  path: "/chat/completions",
6379
6379
  modelId: this.modelId
6380
6380
  }),
6381
- headers: combineHeaders(this.config.headers(), options.headers),
6381
+ headers: combineHeaders$1(this.config.headers(), options.headers),
6382
6382
  body,
6383
6383
  failedResponseHandler: openaiFailedResponseHandler,
6384
- successfulResponseHandler: createEventSourceResponseHandler(
6384
+ successfulResponseHandler: createEventSourceResponseHandler$1(
6385
6385
  openaiChatChunkSchema
6386
6386
  ),
6387
6387
  abortSignal: options.abortSignal,
@@ -6469,7 +6469,7 @@ var OpenAIChatLanguageModel = class {
6469
6469
  const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
6470
6470
  {
6471
6471
  type: "function",
6472
- id: generateId(),
6472
+ id: generateId$1(),
6473
6473
  function: delta.function_call,
6474
6474
  index: 0
6475
6475
  }
@@ -6479,19 +6479,19 @@ var OpenAIChatLanguageModel = class {
6479
6479
  const index = toolCallDelta.index;
6480
6480
  if (toolCalls[index] == null) {
6481
6481
  if (toolCallDelta.type !== "function") {
6482
- throw new InvalidResponseDataError({
6482
+ throw new InvalidResponseDataError$1({
6483
6483
  data: toolCallDelta,
6484
6484
  message: `Expected 'function' type.`
6485
6485
  });
6486
6486
  }
6487
6487
  if (toolCallDelta.id == null) {
6488
- throw new InvalidResponseDataError({
6488
+ throw new InvalidResponseDataError$1({
6489
6489
  data: toolCallDelta,
6490
6490
  message: `Expected 'id' to be a string.`
6491
6491
  });
6492
6492
  }
6493
6493
  if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
6494
- throw new InvalidResponseDataError({
6494
+ throw new InvalidResponseDataError$1({
6495
6495
  data: toolCallDelta,
6496
6496
  message: `Expected 'function.name' to be a string.`
6497
6497
  });
@@ -6516,11 +6516,11 @@ var OpenAIChatLanguageModel = class {
6516
6516
  argsTextDelta: toolCall2.function.arguments
6517
6517
  });
6518
6518
  }
6519
- if (isParsableJson(toolCall2.function.arguments)) {
6519
+ if (isParsableJson$1(toolCall2.function.arguments)) {
6520
6520
  controller.enqueue({
6521
6521
  type: "tool-call",
6522
6522
  toolCallType: "function",
6523
- toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
6523
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId$1(),
6524
6524
  toolName: toolCall2.function.name,
6525
6525
  args: toolCall2.function.arguments
6526
6526
  });
@@ -6543,11 +6543,11 @@ var OpenAIChatLanguageModel = class {
6543
6543
  toolName: toolCall.function.name,
6544
6544
  argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
6545
6545
  });
6546
- if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
6546
+ 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
6547
  controller.enqueue({
6548
6548
  type: "tool-call",
6549
6549
  toolCallType: "function",
6550
- toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
6550
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId$1(),
6551
6551
  toolName: toolCall.function.name,
6552
6552
  args: toolCall.function.arguments
6553
6553
  });
@@ -6734,7 +6734,7 @@ function convertToOpenAICompletionPrompt({
6734
6734
  for (const { role, content } of prompt) {
6735
6735
  switch (role) {
6736
6736
  case "system": {
6737
- throw new InvalidPromptError({
6737
+ throw new InvalidPromptError$1({
6738
6738
  message: "Unexpected system message in prompt: ${content}",
6739
6739
  prompt
6740
6740
  });
@@ -6746,7 +6746,7 @@ function convertToOpenAICompletionPrompt({
6746
6746
  return part.text;
6747
6747
  }
6748
6748
  case "image": {
6749
- throw new UnsupportedFunctionalityError({
6749
+ throw new UnsupportedFunctionalityError$1({
6750
6750
  functionality: "images"
6751
6751
  });
6752
6752
  }
@@ -6765,7 +6765,7 @@ ${userMessage}
6765
6765
  return part.text;
6766
6766
  }
6767
6767
  case "tool-call": {
6768
- throw new UnsupportedFunctionalityError({
6768
+ throw new UnsupportedFunctionalityError$1({
6769
6769
  functionality: "tool-call messages"
6770
6770
  });
6771
6771
  }
@@ -6778,7 +6778,7 @@ ${assistantMessage}
6778
6778
  break;
6779
6779
  }
6780
6780
  case "tool": {
6781
- throw new UnsupportedFunctionalityError({
6781
+ throw new UnsupportedFunctionalityError$1({
6782
6782
  functionality: "tool messages"
6783
6783
  });
6784
6784
  }
@@ -6879,24 +6879,24 @@ var OpenAICompletionLanguageModel = class {
6879
6879
  switch (type) {
6880
6880
  case "regular": {
6881
6881
  if ((_a = mode.tools) == null ? void 0 : _a.length) {
6882
- throw new UnsupportedFunctionalityError({
6882
+ throw new UnsupportedFunctionalityError$1({
6883
6883
  functionality: "tools"
6884
6884
  });
6885
6885
  }
6886
6886
  if (mode.toolChoice) {
6887
- throw new UnsupportedFunctionalityError({
6887
+ throw new UnsupportedFunctionalityError$1({
6888
6888
  functionality: "toolChoice"
6889
6889
  });
6890
6890
  }
6891
6891
  return { args: baseArgs, warnings };
6892
6892
  }
6893
6893
  case "object-json": {
6894
- throw new UnsupportedFunctionalityError({
6894
+ throw new UnsupportedFunctionalityError$1({
6895
6895
  functionality: "object-json mode"
6896
6896
  });
6897
6897
  }
6898
6898
  case "object-tool": {
6899
- throw new UnsupportedFunctionalityError({
6899
+ throw new UnsupportedFunctionalityError$1({
6900
6900
  functionality: "object-tool mode"
6901
6901
  });
6902
6902
  }
@@ -6912,15 +6912,15 @@ var OpenAICompletionLanguageModel = class {
6912
6912
  responseHeaders,
6913
6913
  value: response,
6914
6914
  rawValue: rawResponse
6915
- } = await postJsonToApi({
6915
+ } = await postJsonToApi$1({
6916
6916
  url: this.config.url({
6917
6917
  path: "/completions",
6918
6918
  modelId: this.modelId
6919
6919
  }),
6920
- headers: combineHeaders(this.config.headers(), options.headers),
6920
+ headers: combineHeaders$1(this.config.headers(), options.headers),
6921
6921
  body: args,
6922
6922
  failedResponseHandler: openaiFailedResponseHandler,
6923
- successfulResponseHandler: createJsonResponseHandler(
6923
+ successfulResponseHandler: createJsonResponseHandler$1(
6924
6924
  openaiCompletionResponseSchema
6925
6925
  ),
6926
6926
  abortSignal: options.abortSignal,
@@ -6951,15 +6951,15 @@ var OpenAICompletionLanguageModel = class {
6951
6951
  // only include stream_options when in strict compatibility mode:
6952
6952
  stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
6953
6953
  };
6954
- const { responseHeaders, value: response } = await postJsonToApi({
6954
+ const { responseHeaders, value: response } = await postJsonToApi$1({
6955
6955
  url: this.config.url({
6956
6956
  path: "/completions",
6957
6957
  modelId: this.modelId
6958
6958
  }),
6959
- headers: combineHeaders(this.config.headers(), options.headers),
6959
+ headers: combineHeaders$1(this.config.headers(), options.headers),
6960
6960
  body,
6961
6961
  failedResponseHandler: openaiFailedResponseHandler,
6962
- successfulResponseHandler: createEventSourceResponseHandler(
6962
+ successfulResponseHandler: createEventSourceResponseHandler$1(
6963
6963
  openaiCompletionChunkSchema
6964
6964
  ),
6965
6965
  abortSignal: options.abortSignal,
@@ -7111,12 +7111,12 @@ var OpenAIEmbeddingModel = class {
7111
7111
  values
7112
7112
  });
7113
7113
  }
7114
- const { responseHeaders, value: response } = await postJsonToApi({
7114
+ const { responseHeaders, value: response } = await postJsonToApi$1({
7115
7115
  url: this.config.url({
7116
7116
  path: "/embeddings",
7117
7117
  modelId: this.modelId
7118
7118
  }),
7119
- headers: combineHeaders(this.config.headers(), headers),
7119
+ headers: combineHeaders$1(this.config.headers(), headers),
7120
7120
  body: {
7121
7121
  model: this.modelId,
7122
7122
  input: values,
@@ -7125,7 +7125,7 @@ var OpenAIEmbeddingModel = class {
7125
7125
  user: this.settings.user
7126
7126
  },
7127
7127
  failedResponseHandler: openaiFailedResponseHandler,
7128
- successfulResponseHandler: createJsonResponseHandler(
7128
+ successfulResponseHandler: createJsonResponseHandler$1(
7129
7129
  openaiTextEmbeddingResponseSchema
7130
7130
  ),
7131
7131
  abortSignal,
@@ -7189,12 +7189,12 @@ var OpenAIImageModel = class {
7189
7189
  warnings.push({ type: "unsupported-setting", setting: "seed" });
7190
7190
  }
7191
7191
  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({
7192
+ const { value: response, responseHeaders } = await postJsonToApi$1({
7193
7193
  url: this.config.url({
7194
7194
  path: "/images/generations",
7195
7195
  modelId: this.modelId
7196
7196
  }),
7197
- headers: combineHeaders(this.config.headers(), headers),
7197
+ headers: combineHeaders$1(this.config.headers(), headers),
7198
7198
  body: {
7199
7199
  model: this.modelId,
7200
7200
  prompt,
@@ -7204,7 +7204,7 @@ var OpenAIImageModel = class {
7204
7204
  ...!hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}
7205
7205
  },
7206
7206
  failedResponseHandler: openaiFailedResponseHandler,
7207
- successfulResponseHandler: createJsonResponseHandler(
7207
+ successfulResponseHandler: createJsonResponseHandler$1(
7208
7208
  openaiImageResponseSchema
7209
7209
  ),
7210
7210
  abortSignal,
@@ -7348,10 +7348,10 @@ var OpenAITranscriptionModel = class {
7348
7348
  path: "/audio/transcriptions",
7349
7349
  modelId: this.modelId
7350
7350
  }),
7351
- headers: combineHeaders(this.config.headers(), options.headers),
7351
+ headers: combineHeaders$1(this.config.headers(), options.headers),
7352
7352
  formData,
7353
7353
  failedResponseHandler: openaiFailedResponseHandler,
7354
- successfulResponseHandler: createJsonResponseHandler(
7354
+ successfulResponseHandler: createJsonResponseHandler$1(
7355
7355
  openaiTranscriptionResponseSchema
7356
7356
  ),
7357
7357
  abortSignal: options.abortSignal,
@@ -7435,14 +7435,14 @@ function convertToOpenAIResponsesMessages({
7435
7435
  case "image": {
7436
7436
  return {
7437
7437
  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)}`,
7438
+ image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64$1(part.image)}`,
7439
7439
  // OpenAI specific extension: image detail
7440
7440
  detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail
7441
7441
  };
7442
7442
  }
7443
7443
  case "file": {
7444
7444
  if (part.data instanceof URL) {
7445
- throw new UnsupportedFunctionalityError({
7445
+ throw new UnsupportedFunctionalityError$1({
7446
7446
  functionality: "File URLs in user messages"
7447
7447
  });
7448
7448
  }
@@ -7455,7 +7455,7 @@ function convertToOpenAIResponsesMessages({
7455
7455
  };
7456
7456
  }
7457
7457
  default: {
7458
- throw new UnsupportedFunctionalityError({
7458
+ throw new UnsupportedFunctionalityError$1({
7459
7459
  functionality: "Only PDF files are supported in user messages"
7460
7460
  });
7461
7461
  }
@@ -7597,7 +7597,7 @@ function prepareResponsesTools({
7597
7597
  }
7598
7598
  default: {
7599
7599
  const _exhaustiveCheck = type;
7600
- throw new UnsupportedFunctionalityError({
7600
+ throw new UnsupportedFunctionalityError$1({
7601
7601
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
7602
7602
  });
7603
7603
  }
@@ -7796,15 +7796,15 @@ var OpenAIResponsesLanguageModel = class {
7796
7796
  responseHeaders,
7797
7797
  value: response,
7798
7798
  rawValue: rawResponse
7799
- } = await postJsonToApi({
7799
+ } = await postJsonToApi$1({
7800
7800
  url: this.config.url({
7801
7801
  path: "/responses",
7802
7802
  modelId: this.modelId
7803
7803
  }),
7804
- headers: combineHeaders(this.config.headers(), options.headers),
7804
+ headers: combineHeaders$1(this.config.headers(), options.headers),
7805
7805
  body,
7806
7806
  failedResponseHandler: openaiFailedResponseHandler,
7807
- successfulResponseHandler: createJsonResponseHandler(
7807
+ successfulResponseHandler: createJsonResponseHandler$1(
7808
7808
  z.object({
7809
7809
  id: z.string(),
7810
7810
  created_at: z.number(),
@@ -7875,7 +7875,7 @@ var OpenAIResponsesLanguageModel = class {
7875
7875
  var _a2, _b2, _c2;
7876
7876
  return {
7877
7877
  sourceType: "url",
7878
- id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId(),
7878
+ id: (_c2 = (_b2 = (_a2 = this.config).generateId) == null ? void 0 : _b2.call(_a2)) != null ? _c2 : generateId$1(),
7879
7879
  url: annotation.url,
7880
7880
  title: annotation.title
7881
7881
  };
@@ -7922,18 +7922,18 @@ var OpenAIResponsesLanguageModel = class {
7922
7922
  }
7923
7923
  async doStream(options) {
7924
7924
  const { args: body, warnings } = this.getArgs(options);
7925
- const { responseHeaders, value: response } = await postJsonToApi({
7925
+ const { responseHeaders, value: response } = await postJsonToApi$1({
7926
7926
  url: this.config.url({
7927
7927
  path: "/responses",
7928
7928
  modelId: this.modelId
7929
7929
  }),
7930
- headers: combineHeaders(this.config.headers(), options.headers),
7930
+ headers: combineHeaders$1(this.config.headers(), options.headers),
7931
7931
  body: {
7932
7932
  ...body,
7933
7933
  stream: true
7934
7934
  },
7935
7935
  failedResponseHandler: openaiFailedResponseHandler,
7936
- successfulResponseHandler: createEventSourceResponseHandler(
7936
+ successfulResponseHandler: createEventSourceResponseHandler$1(
7937
7937
  openaiResponsesChunkSchema
7938
7938
  ),
7939
7939
  abortSignal: options.abortSignal,
@@ -8026,7 +8026,7 @@ var OpenAIResponsesLanguageModel = class {
8026
8026
  type: "source",
8027
8027
  source: {
8028
8028
  sourceType: "url",
8029
- id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(),
8029
+ id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId$1(),
8030
8030
  url: value.annotation.url,
8031
8031
  title: value.annotation.title
8032
8032
  }
@@ -8294,12 +8294,12 @@ var OpenAISpeechModel = class {
8294
8294
  value: audio,
8295
8295
  responseHeaders,
8296
8296
  rawValue: rawResponse
8297
- } = await postJsonToApi({
8297
+ } = await postJsonToApi$1({
8298
8298
  url: this.config.url({
8299
8299
  path: "/audio/speech",
8300
8300
  modelId: this.modelId
8301
8301
  }),
8302
- headers: combineHeaders(this.config.headers(), options.headers),
8302
+ headers: combineHeaders$1(this.config.headers(), options.headers),
8303
8303
  body: requestBody,
8304
8304
  failedResponseHandler: openaiFailedResponseHandler,
8305
8305
  successfulResponseHandler: createBinaryResponseHandler(),
@@ -8325,11 +8325,11 @@ var OpenAISpeechModel = class {
8325
8325
  // src/openai-provider.ts
8326
8326
  function createOpenAI(options = {}) {
8327
8327
  var _a, _b, _c;
8328
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8328
+ const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.openai.com/v1";
8329
8329
  const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
8330
8330
  const providerName = (_c = options.name) != null ? _c : "openai";
8331
8331
  const getHeaders = () => ({
8332
- Authorization: `Bearer ${loadApiKey({
8332
+ Authorization: `Bearer ${loadApiKey$1({
8333
8333
  apiKey: options.apiKey,
8334
8334
  environmentVariableName: "OPENAI_API_KEY",
8335
8335
  description: "OpenAI"
@@ -8657,7 +8657,7 @@ var anthropicErrorDataSchema = z.object({
8657
8657
  message: z.string()
8658
8658
  })
8659
8659
  });
8660
- var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
8660
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler$1({
8661
8661
  errorSchema: anthropicErrorDataSchema,
8662
8662
  errorToMessage: (data) => data.error.message
8663
8663
  });
@@ -8775,7 +8775,7 @@ function prepareTools$2(mode) {
8775
8775
  };
8776
8776
  default: {
8777
8777
  const _exhaustiveCheck = type;
8778
- throw new UnsupportedFunctionalityError({
8778
+ throw new UnsupportedFunctionalityError$1({
8779
8779
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
8780
8780
  });
8781
8781
  }
@@ -8804,7 +8804,7 @@ function convertToAnthropicMessagesPrompt({
8804
8804
  switch (type) {
8805
8805
  case "system": {
8806
8806
  if (system != null) {
8807
- throw new UnsupportedFunctionalityError({
8807
+ throw new UnsupportedFunctionalityError$1({
8808
8808
  functionality: "Multiple system messages that are separated by user/assistant messages"
8809
8809
  });
8810
8810
  }
@@ -8843,7 +8843,7 @@ function convertToAnthropicMessagesPrompt({
8843
8843
  } : {
8844
8844
  type: "base64",
8845
8845
  media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
8846
- data: convertUint8ArrayToBase64(part.image)
8846
+ data: convertUint8ArrayToBase64$1(part.image)
8847
8847
  },
8848
8848
  cache_control: cacheControl
8849
8849
  });
@@ -8851,7 +8851,7 @@ function convertToAnthropicMessagesPrompt({
8851
8851
  }
8852
8852
  case "file": {
8853
8853
  if (part.mimeType !== "application/pdf") {
8854
- throw new UnsupportedFunctionalityError({
8854
+ throw new UnsupportedFunctionalityError$1({
8855
8855
  functionality: "Non-PDF files in user messages"
8856
8856
  });
8857
8857
  }
@@ -9148,7 +9148,7 @@ var AnthropicMessagesLanguageModel = class {
9148
9148
  };
9149
9149
  if (isThinking) {
9150
9150
  if (thinkingBudget == null) {
9151
- throw new UnsupportedFunctionalityError({
9151
+ throw new UnsupportedFunctionalityError$1({
9152
9152
  functionality: "thinking requires a budget"
9153
9153
  });
9154
9154
  }
@@ -9193,7 +9193,7 @@ var AnthropicMessagesLanguageModel = class {
9193
9193
  };
9194
9194
  }
9195
9195
  case "object-json": {
9196
- throw new UnsupportedFunctionalityError({
9196
+ throw new UnsupportedFunctionalityError$1({
9197
9197
  functionality: "json-mode object generation"
9198
9198
  });
9199
9199
  }
@@ -9219,7 +9219,7 @@ var AnthropicMessagesLanguageModel = class {
9219
9219
  betas,
9220
9220
  headers
9221
9221
  }) {
9222
- return combineHeaders(
9222
+ return combineHeaders$1(
9223
9223
  await resolve(this.config.headers),
9224
9224
  betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
9225
9225
  headers
@@ -9240,12 +9240,12 @@ var AnthropicMessagesLanguageModel = class {
9240
9240
  responseHeaders,
9241
9241
  value: response,
9242
9242
  rawValue: rawResponse
9243
- } = await postJsonToApi({
9243
+ } = await postJsonToApi$1({
9244
9244
  url: this.buildRequestUrl(false),
9245
9245
  headers: await this.getHeaders({ betas, headers: options.headers }),
9246
9246
  body: this.transformRequestBody(args),
9247
9247
  failedResponseHandler: anthropicFailedResponseHandler,
9248
- successfulResponseHandler: createJsonResponseHandler(
9248
+ successfulResponseHandler: createJsonResponseHandler$1(
9249
9249
  anthropicMessagesResponseSchema
9250
9250
  ),
9251
9251
  abortSignal: options.abortSignal,
@@ -9315,12 +9315,12 @@ var AnthropicMessagesLanguageModel = class {
9315
9315
  async doStream(options) {
9316
9316
  const { args, warnings, betas } = await this.getArgs(options);
9317
9317
  const body = { ...args, stream: true };
9318
- const { responseHeaders, value: response } = await postJsonToApi({
9318
+ const { responseHeaders, value: response } = await postJsonToApi$1({
9319
9319
  url: this.buildRequestUrl(true),
9320
9320
  headers: await this.getHeaders({ betas, headers: options.headers }),
9321
9321
  body: this.transformRequestBody(body),
9322
9322
  failedResponseHandler: anthropicFailedResponseHandler,
9323
- successfulResponseHandler: createEventSourceResponseHandler(
9323
+ successfulResponseHandler: createEventSourceResponseHandler$1(
9324
9324
  anthropicMessagesChunkSchema
9325
9325
  ),
9326
9326
  abortSignal: options.abortSignal,
@@ -9761,10 +9761,10 @@ var anthropicTools = {
9761
9761
  // src/anthropic-provider.ts
9762
9762
  function createAnthropic(options = {}) {
9763
9763
  var _a;
9764
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9764
+ const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
9765
9765
  const getHeaders = () => ({
9766
9766
  "anthropic-version": "2023-06-01",
9767
- "x-api-key": loadApiKey({
9767
+ "x-api-key": loadApiKey$1({
9768
9768
  apiKey: options.apiKey,
9769
9769
  environmentVariableName: "ANTHROPIC_API_KEY",
9770
9770
  description: "Anthropic"
@@ -9904,7 +9904,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9904
9904
  switch (role) {
9905
9905
  case "system": {
9906
9906
  if (!systemMessagesAllowed) {
9907
- throw new UnsupportedFunctionalityError({
9907
+ throw new UnsupportedFunctionalityError$1({
9908
9908
  functionality: "system messages are only supported at the beginning of the conversation"
9909
9909
  });
9910
9910
  }
@@ -9930,7 +9930,7 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9930
9930
  } : {
9931
9931
  inlineData: {
9932
9932
  mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
9933
- data: convertUint8ArrayToBase64(part.image)
9933
+ data: convertUint8ArrayToBase64$1(part.image)
9934
9934
  }
9935
9935
  }
9936
9936
  );
@@ -9968,12 +9968,12 @@ function convertToGoogleGenerativeAIMessages(prompt) {
9968
9968
  }
9969
9969
  case "file": {
9970
9970
  if (part.mimeType !== "image/png") {
9971
- throw new UnsupportedFunctionalityError({
9971
+ throw new UnsupportedFunctionalityError$1({
9972
9972
  functionality: "Only PNG images are supported in assistant messages"
9973
9973
  });
9974
9974
  }
9975
9975
  if (part.data instanceof URL) {
9976
- throw new UnsupportedFunctionalityError({
9976
+ throw new UnsupportedFunctionalityError$1({
9977
9977
  functionality: "File data URLs in assistant messages are not supported"
9978
9978
  });
9979
9979
  }
@@ -10032,7 +10032,7 @@ var googleErrorDataSchema = z.object({
10032
10032
  status: z.string()
10033
10033
  })
10034
10034
  });
10035
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
10035
+ var googleFailedResponseHandler = createJsonErrorResponseHandler$1({
10036
10036
  errorSchema: googleErrorDataSchema,
10037
10037
  errorToMessage: (data) => data.error.message
10038
10038
  });
@@ -10107,7 +10107,7 @@ function prepareTools$1(mode, useSearchGrounding, dynamicRetrievalConfig, modelI
10107
10107
  };
10108
10108
  default: {
10109
10109
  const _exhaustiveCheck = type;
10110
- throw new UnsupportedFunctionalityError({
10110
+ throw new UnsupportedFunctionalityError$1({
10111
10111
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
10112
10112
  });
10113
10113
  }
@@ -10278,7 +10278,7 @@ var GoogleGenerativeAILanguageModel = class {
10278
10278
  var _a, _b, _c, _d, _e;
10279
10279
  const { args, warnings } = await this.getArgs(options);
10280
10280
  const body = JSON.stringify(args);
10281
- const mergedHeaders = combineHeaders(
10281
+ const mergedHeaders = combineHeaders$1(
10282
10282
  await resolve(this.config.headers),
10283
10283
  options.headers
10284
10284
  );
@@ -10286,14 +10286,14 @@ var GoogleGenerativeAILanguageModel = class {
10286
10286
  responseHeaders,
10287
10287
  value: response,
10288
10288
  rawValue: rawResponse
10289
- } = await postJsonToApi({
10289
+ } = await postJsonToApi$1({
10290
10290
  url: `${this.config.baseURL}/${getModelPath(
10291
10291
  this.modelId
10292
10292
  )}:generateContent`,
10293
10293
  headers: mergedHeaders,
10294
10294
  body: args,
10295
10295
  failedResponseHandler: googleFailedResponseHandler,
10296
- successfulResponseHandler: createJsonResponseHandler(responseSchema),
10296
+ successfulResponseHandler: createJsonResponseHandler$1(responseSchema),
10297
10297
  abortSignal: options.abortSignal,
10298
10298
  fetch: this.config.fetch
10299
10299
  });
@@ -10339,18 +10339,18 @@ var GoogleGenerativeAILanguageModel = class {
10339
10339
  async doStream(options) {
10340
10340
  const { args, warnings } = await this.getArgs(options);
10341
10341
  const body = JSON.stringify(args);
10342
- const headers = combineHeaders(
10342
+ const headers = combineHeaders$1(
10343
10343
  await resolve(this.config.headers),
10344
10344
  options.headers
10345
10345
  );
10346
- const { responseHeaders, value: response } = await postJsonToApi({
10346
+ const { responseHeaders, value: response } = await postJsonToApi$1({
10347
10347
  url: `${this.config.baseURL}/${getModelPath(
10348
10348
  this.modelId
10349
10349
  )}:streamGenerateContent?alt=sse`,
10350
10350
  headers,
10351
10351
  body: args,
10352
10352
  failedResponseHandler: googleFailedResponseHandler,
10353
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
10353
+ successfulResponseHandler: createEventSourceResponseHandler$1(chunkSchema),
10354
10354
  abortSignal: options.abortSignal,
10355
10355
  fetch: this.config.fetch
10356
10356
  });
@@ -10626,11 +10626,11 @@ var GoogleGenerativeAIEmbeddingModel = class {
10626
10626
  values
10627
10627
  });
10628
10628
  }
10629
- const mergedHeaders = combineHeaders(
10629
+ const mergedHeaders = combineHeaders$1(
10630
10630
  await resolve(this.config.headers),
10631
10631
  headers
10632
10632
  );
10633
- const { responseHeaders, value: response } = await postJsonToApi({
10633
+ const { responseHeaders, value: response } = await postJsonToApi$1({
10634
10634
  url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
10635
10635
  headers: mergedHeaders,
10636
10636
  body: {
@@ -10642,7 +10642,7 @@ var GoogleGenerativeAIEmbeddingModel = class {
10642
10642
  }))
10643
10643
  },
10644
10644
  failedResponseHandler: googleFailedResponseHandler,
10645
- successfulResponseHandler: createJsonResponseHandler(
10645
+ successfulResponseHandler: createJsonResponseHandler$1(
10646
10646
  googleGenerativeAITextEmbeddingResponseSchema
10647
10647
  ),
10648
10648
  abortSignal,
@@ -10667,9 +10667,9 @@ function isSupportedFileUrl(url) {
10667
10667
  // src/google-provider.ts
10668
10668
  function createGoogleGenerativeAI(options = {}) {
10669
10669
  var _a;
10670
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10670
+ const baseURL = (_a = withoutTrailingSlash$1(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
10671
10671
  const getHeaders = () => ({
10672
- "x-goog-api-key": loadApiKey({
10672
+ "x-goog-api-key": loadApiKey$1({
10673
10673
  apiKey: options.apiKey,
10674
10674
  environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
10675
10675
  description: "Google Generative AI"
@@ -10682,7 +10682,7 @@ function createGoogleGenerativeAI(options = {}) {
10682
10682
  provider: "google.generative-ai",
10683
10683
  baseURL,
10684
10684
  headers: getHeaders,
10685
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
10685
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId$1,
10686
10686
  isSupportedUrl: isSupportedFileUrl,
10687
10687
  fetch: options.fetch
10688
10688
  });
@@ -11491,9 +11491,9 @@ var BedrockErrorSchema = z.object({
11491
11491
  type: z.string().nullish()
11492
11492
  });
11493
11493
  var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response }) => {
11494
- const responseHeaders = extractResponseHeaders(response);
11494
+ const responseHeaders = extractResponseHeaders$1(response);
11495
11495
  if (response.body == null) {
11496
- throw new EmptyResponseBodyError({});
11496
+ throw new EmptyResponseBodyError$1({});
11497
11497
  }
11498
11498
  const codec = new EventStreamCodec(toUtf8, fromUtf8);
11499
11499
  let buffer = new Uint8Array(0);
@@ -11523,7 +11523,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11523
11523
  buffer = buffer.slice(totalLength);
11524
11524
  if (((_a = decoded.headers[":message-type"]) == null ? void 0 : _a.value) === "event") {
11525
11525
  const data = textDecoder.decode(decoded.body);
11526
- const parsedDataResult = safeParseJSON({ text: data });
11526
+ const parsedDataResult = safeParseJSON$1({ text: data });
11527
11527
  if (!parsedDataResult.success) {
11528
11528
  controller.enqueue(parsedDataResult);
11529
11529
  break;
@@ -11532,7 +11532,7 @@ var createBedrockEventStreamResponseHandler = (chunkSchema) => async ({ response
11532
11532
  let wrappedData = {
11533
11533
  [(_b = decoded.headers[":event-type"]) == null ? void 0 : _b.value]: parsedDataResult.value
11534
11534
  };
11535
- const validatedWrappedData = safeValidateTypes({
11535
+ const validatedWrappedData = safeValidateTypes$1({
11536
11536
  value: wrappedData,
11537
11537
  schema: chunkSchema
11538
11538
  });
@@ -11615,13 +11615,13 @@ function prepareTools(mode) {
11615
11615
  };
11616
11616
  default: {
11617
11617
  const _exhaustiveCheck = type;
11618
- throw new UnsupportedFunctionalityError({
11618
+ throw new UnsupportedFunctionalityError$1({
11619
11619
  functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
11620
11620
  });
11621
11621
  }
11622
11622
  }
11623
11623
  }
11624
- var generateFileId = createIdGenerator({ prefix: "file", size: 16 });
11624
+ var generateFileId = createIdGenerator$1({ prefix: "file", size: 16 });
11625
11625
  function getCachePoint(providerMetadata) {
11626
11626
  var _a;
11627
11627
  return (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.cachePoint;
@@ -11638,7 +11638,7 @@ function convertToBedrockChatMessages(prompt) {
11638
11638
  switch (type) {
11639
11639
  case "system": {
11640
11640
  if (messages.length > 0) {
11641
- throw new UnsupportedFunctionalityError({
11641
+ throw new UnsupportedFunctionalityError$1({
11642
11642
  functionality: "Multiple system messages that are separated by user/assistant messages"
11643
11643
  });
11644
11644
  }
@@ -11667,7 +11667,7 @@ function convertToBedrockChatMessages(prompt) {
11667
11667
  }
11668
11668
  case "image": {
11669
11669
  if (part.image instanceof URL) {
11670
- throw new UnsupportedFunctionalityError({
11670
+ throw new UnsupportedFunctionalityError$1({
11671
11671
  functionality: "Image URLs in user messages"
11672
11672
  });
11673
11673
  }
@@ -11677,7 +11677,7 @@ function convertToBedrockChatMessages(prompt) {
11677
11677
  "/"
11678
11678
  )) == null ? void 0 : _b[1],
11679
11679
  source: {
11680
- bytes: convertUint8ArrayToBase64(
11680
+ bytes: convertUint8ArrayToBase64$1(
11681
11681
  (_c = part.image) != null ? _c : part.image
11682
11682
  )
11683
11683
  }
@@ -11687,7 +11687,7 @@ function convertToBedrockChatMessages(prompt) {
11687
11687
  }
11688
11688
  case "file": {
11689
11689
  if (part.data instanceof URL) {
11690
- throw new UnsupportedFunctionalityError({
11690
+ throw new UnsupportedFunctionalityError$1({
11691
11691
  functionality: "File URLs in user messages"
11692
11692
  });
11693
11693
  }
@@ -11977,7 +11977,7 @@ var BedrockChatLanguageModel = class {
11977
11977
  (_a = providerMetadata == null ? void 0 : providerMetadata.bedrock) == null ? void 0 : _a.reasoning_config
11978
11978
  );
11979
11979
  if (!reasoningConfigOptions.success) {
11980
- throw new InvalidArgumentError({
11980
+ throw new InvalidArgumentError$1({
11981
11981
  argument: "providerOptions.bedrock.reasoning_config",
11982
11982
  message: "invalid reasoning configuration options",
11983
11983
  cause: reasoningConfigOptions.error
@@ -12042,7 +12042,7 @@ var BedrockChatLanguageModel = class {
12042
12042
  };
12043
12043
  }
12044
12044
  case "object-json": {
12045
- throw new UnsupportedFunctionalityError({
12045
+ throw new UnsupportedFunctionalityError$1({
12046
12046
  functionality: "json-mode object generation"
12047
12047
  });
12048
12048
  }
@@ -12078,21 +12078,21 @@ var BedrockChatLanguageModel = class {
12078
12078
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
12079
12079
  const { command: args, warnings } = this.getArgs(options);
12080
12080
  const url = `${this.getUrl(this.modelId)}/converse`;
12081
- const { value: response, responseHeaders } = await postJsonToApi({
12081
+ const { value: response, responseHeaders } = await postJsonToApi$1({
12082
12082
  url,
12083
- headers: combineHeaders(
12083
+ headers: combineHeaders$1(
12084
12084
  await resolve(this.config.headers),
12085
12085
  options.headers
12086
12086
  ),
12087
12087
  body: args,
12088
- failedResponseHandler: createJsonErrorResponseHandler({
12088
+ failedResponseHandler: createJsonErrorResponseHandler$1({
12089
12089
  errorSchema: BedrockErrorSchema,
12090
12090
  errorToMessage: (error) => {
12091
12091
  var _a2;
12092
12092
  return `${(_a2 = error.message) != null ? _a2 : "Unknown error"}`;
12093
12093
  }
12094
12094
  }),
12095
- successfulResponseHandler: createJsonResponseHandler(
12095
+ successfulResponseHandler: createJsonResponseHandler$1(
12096
12096
  BedrockResponseSchema
12097
12097
  ),
12098
12098
  abortSignal: options.abortSignal,
@@ -12160,14 +12160,14 @@ var BedrockChatLanguageModel = class {
12160
12160
  async doStream(options) {
12161
12161
  const { command: args, warnings } = this.getArgs(options);
12162
12162
  const url = `${this.getUrl(this.modelId)}/converse-stream`;
12163
- const { value: response, responseHeaders } = await postJsonToApi({
12163
+ const { value: response, responseHeaders } = await postJsonToApi$1({
12164
12164
  url,
12165
- headers: combineHeaders(
12165
+ headers: combineHeaders$1(
12166
12166
  await resolve(this.config.headers),
12167
12167
  options.headers
12168
12168
  ),
12169
12169
  body: args,
12170
- failedResponseHandler: createJsonErrorResponseHandler({
12170
+ failedResponseHandler: createJsonErrorResponseHandler$1({
12171
12171
  errorSchema: BedrockErrorSchema,
12172
12172
  errorToMessage: (error) => `${error.type}: ${error.message}`
12173
12173
  }),
@@ -12450,17 +12450,17 @@ var BedrockEmbeddingModel = class {
12450
12450
  normalize: this.settings.normalize
12451
12451
  };
12452
12452
  const url = this.getUrl(this.modelId);
12453
- const { value: response } = await postJsonToApi({
12453
+ const { value: response } = await postJsonToApi$1({
12454
12454
  url,
12455
12455
  headers: await resolve(
12456
- combineHeaders(await resolve(this.config.headers), headers)
12456
+ combineHeaders$1(await resolve(this.config.headers), headers)
12457
12457
  ),
12458
12458
  body: args,
12459
- failedResponseHandler: createJsonErrorResponseHandler({
12459
+ failedResponseHandler: createJsonErrorResponseHandler$1({
12460
12460
  errorSchema: BedrockErrorSchema,
12461
12461
  errorToMessage: (error) => `${error.type}: ${error.message}`
12462
12462
  }),
12463
- successfulResponseHandler: createJsonResponseHandler(
12463
+ successfulResponseHandler: createJsonResponseHandler$1(
12464
12464
  BedrockEmbeddingResponseSchema
12465
12465
  ),
12466
12466
  fetch: this.config.fetch,
@@ -12545,17 +12545,17 @@ var BedrockImageModel = class {
12545
12545
  });
12546
12546
  }
12547
12547
  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({
12548
+ const { value: response, responseHeaders } = await postJsonToApi$1({
12549
12549
  url: this.getUrl(this.modelId),
12550
12550
  headers: await resolve(
12551
- combineHeaders(await resolve(this.config.headers), headers)
12551
+ combineHeaders$1(await resolve(this.config.headers), headers)
12552
12552
  ),
12553
12553
  body: args,
12554
- failedResponseHandler: createJsonErrorResponseHandler({
12554
+ failedResponseHandler: createJsonErrorResponseHandler$1({
12555
12555
  errorSchema: BedrockErrorSchema,
12556
12556
  errorToMessage: (error) => `${error.type}: ${error.message}`
12557
12557
  }),
12558
- successfulResponseHandler: createJsonResponseHandler(
12558
+ successfulResponseHandler: createJsonResponseHandler$1(
12559
12559
  bedrockImageResponseSchema
12560
12560
  ),
12561
12561
  abortSignal,
@@ -12614,7 +12614,7 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12614
12614
  const signer = new AwsV4Signer({
12615
12615
  url,
12616
12616
  method: "POST",
12617
- headers: Object.entries(removeUndefinedEntries(originalHeaders)),
12617
+ headers: Object.entries(removeUndefinedEntries$1(originalHeaders)),
12618
12618
  body,
12619
12619
  region: credentials.region,
12620
12620
  accessKeyId: credentials.accessKeyId,
@@ -12627,8 +12627,8 @@ function createSigV4FetchFunction(getCredentials, fetch = globalThis.fetch) {
12627
12627
  return fetch(input, {
12628
12628
  ...init,
12629
12629
  body,
12630
- headers: removeUndefinedEntries(
12631
- combineHeaders(originalHeaders, signedHeaders)
12630
+ headers: removeUndefinedEntries$1(
12631
+ combineHeaders$1(originalHeaders, signedHeaders)
12632
12632
  )
12633
12633
  });
12634
12634
  };
@@ -12682,7 +12682,7 @@ function createAmazonBedrock(options = {}) {
12682
12682
  }, options.fetch);
12683
12683
  const getBaseUrl = () => {
12684
12684
  var _a, _b;
12685
- return (_b = withoutTrailingSlash(
12685
+ return (_b = withoutTrailingSlash$1(
12686
12686
  (_a = options.baseURL) != null ? _a : `https://bedrock-runtime.${loadSetting({
12687
12687
  settingValue: options.region,
12688
12688
  settingName: "region",
@@ -12697,7 +12697,7 @@ function createAmazonBedrock(options = {}) {
12697
12697
  baseUrl: getBaseUrl,
12698
12698
  headers: (_a = options.headers) != null ? _a : {},
12699
12699
  fetch: sigv4Fetch,
12700
- generateId
12700
+ generateId: generateId$1
12701
12701
  });
12702
12702
  };
12703
12703
  const provider = function(modelId, settings) {
@@ -12734,29 +12734,2065 @@ function createAmazonBedrock(options = {}) {
12734
12734
  }
12735
12735
  createAmazonBedrock();
12736
12736
 
12737
- class RetryLanguageModel {
12738
- constructor(llms, names, stream_first_timeout) {
12739
- this.llms = llms;
12740
- this.names = names || [];
12741
- this.stream_first_timeout = stream_first_timeout || 30000;
12742
- if (this.names.indexOf("default") == -1) {
12743
- this.names.push("default");
12744
- }
12745
- }
12746
- async call(request) {
12747
- return await this.doGenerate({
12748
- inputFormat: "messages",
12749
- mode: {
12750
- type: "regular",
12751
- tools: request.tools,
12752
- toolChoice: request.toolChoice,
12753
- },
12754
- prompt: request.messages,
12755
- maxTokens: request.maxTokens || config.maxTokens,
12756
- temperature: request.temperature,
12757
- topP: request.topP,
12758
- topK: request.topK,
12759
- providerMetadata: {},
12737
+ // src/errors/ai-sdk-error.ts
12738
+ var marker = "vercel.ai.error";
12739
+ var symbol = Symbol.for(marker);
12740
+ var _a;
12741
+ var _AISDKError = class _AISDKError extends Error {
12742
+ /**
12743
+ * Creates an AI SDK Error.
12744
+ *
12745
+ * @param {Object} params - The parameters for creating the error.
12746
+ * @param {string} params.name - The name of the error.
12747
+ * @param {string} params.message - The error message.
12748
+ * @param {unknown} [params.cause] - The underlying cause of the error.
12749
+ */
12750
+ constructor({
12751
+ name: name14,
12752
+ message,
12753
+ cause
12754
+ }) {
12755
+ super(message);
12756
+ this[_a] = true;
12757
+ this.name = name14;
12758
+ this.cause = cause;
12759
+ }
12760
+ /**
12761
+ * Checks if the given error is an AI SDK Error.
12762
+ * @param {unknown} error - The error to check.
12763
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
12764
+ */
12765
+ static isInstance(error) {
12766
+ return _AISDKError.hasMarker(error, marker);
12767
+ }
12768
+ static hasMarker(error, marker15) {
12769
+ const markerSymbol = Symbol.for(marker15);
12770
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
12771
+ }
12772
+ };
12773
+ _a = symbol;
12774
+ var AISDKError = _AISDKError;
12775
+
12776
+ // src/errors/api-call-error.ts
12777
+ var name = "AI_APICallError";
12778
+ var marker2 = `vercel.ai.error.${name}`;
12779
+ var symbol2 = Symbol.for(marker2);
12780
+ var _a2;
12781
+ var APICallError = class extends AISDKError {
12782
+ constructor({
12783
+ message,
12784
+ url,
12785
+ requestBodyValues,
12786
+ statusCode,
12787
+ responseHeaders,
12788
+ responseBody,
12789
+ cause,
12790
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
12791
+ statusCode === 409 || // conflict
12792
+ statusCode === 429 || // too many requests
12793
+ statusCode >= 500),
12794
+ // server error
12795
+ data
12796
+ }) {
12797
+ super({ name, message, cause });
12798
+ this[_a2] = true;
12799
+ this.url = url;
12800
+ this.requestBodyValues = requestBodyValues;
12801
+ this.statusCode = statusCode;
12802
+ this.responseHeaders = responseHeaders;
12803
+ this.responseBody = responseBody;
12804
+ this.isRetryable = isRetryable;
12805
+ this.data = data;
12806
+ }
12807
+ static isInstance(error) {
12808
+ return AISDKError.hasMarker(error, marker2);
12809
+ }
12810
+ };
12811
+ _a2 = symbol2;
12812
+
12813
+ // src/errors/empty-response-body-error.ts
12814
+ var name2 = "AI_EmptyResponseBodyError";
12815
+ var marker3 = `vercel.ai.error.${name2}`;
12816
+ var symbol3 = Symbol.for(marker3);
12817
+ var _a3;
12818
+ var EmptyResponseBodyError = class extends AISDKError {
12819
+ // used in isInstance
12820
+ constructor({ message = "Empty response body" } = {}) {
12821
+ super({ name: name2, message });
12822
+ this[_a3] = true;
12823
+ }
12824
+ static isInstance(error) {
12825
+ return AISDKError.hasMarker(error, marker3);
12826
+ }
12827
+ };
12828
+ _a3 = symbol3;
12829
+
12830
+ // src/errors/get-error-message.ts
12831
+ function getErrorMessage(error) {
12832
+ if (error == null) {
12833
+ return "unknown error";
12834
+ }
12835
+ if (typeof error === "string") {
12836
+ return error;
12837
+ }
12838
+ if (error instanceof Error) {
12839
+ return error.message;
12840
+ }
12841
+ return JSON.stringify(error);
12842
+ }
12843
+
12844
+ // src/errors/invalid-argument-error.ts
12845
+ var name3 = "AI_InvalidArgumentError";
12846
+ var marker4 = `vercel.ai.error.${name3}`;
12847
+ var symbol4 = Symbol.for(marker4);
12848
+ var _a4;
12849
+ var InvalidArgumentError = class extends AISDKError {
12850
+ constructor({
12851
+ message,
12852
+ cause,
12853
+ argument
12854
+ }) {
12855
+ super({ name: name3, message, cause });
12856
+ this[_a4] = true;
12857
+ this.argument = argument;
12858
+ }
12859
+ static isInstance(error) {
12860
+ return AISDKError.hasMarker(error, marker4);
12861
+ }
12862
+ };
12863
+ _a4 = symbol4;
12864
+
12865
+ // src/errors/invalid-prompt-error.ts
12866
+ var name4 = "AI_InvalidPromptError";
12867
+ var marker5 = `vercel.ai.error.${name4}`;
12868
+ var symbol5 = Symbol.for(marker5);
12869
+ var _a5;
12870
+ var InvalidPromptError = class extends AISDKError {
12871
+ constructor({
12872
+ prompt,
12873
+ message,
12874
+ cause
12875
+ }) {
12876
+ super({ name: name4, message: `Invalid prompt: ${message}`, cause });
12877
+ this[_a5] = true;
12878
+ this.prompt = prompt;
12879
+ }
12880
+ static isInstance(error) {
12881
+ return AISDKError.hasMarker(error, marker5);
12882
+ }
12883
+ };
12884
+ _a5 = symbol5;
12885
+
12886
+ // src/errors/invalid-response-data-error.ts
12887
+ var name5 = "AI_InvalidResponseDataError";
12888
+ var marker6 = `vercel.ai.error.${name5}`;
12889
+ var symbol6 = Symbol.for(marker6);
12890
+ var _a6;
12891
+ var InvalidResponseDataError = class extends AISDKError {
12892
+ constructor({
12893
+ data,
12894
+ message = `Invalid response data: ${JSON.stringify(data)}.`
12895
+ }) {
12896
+ super({ name: name5, message });
12897
+ this[_a6] = true;
12898
+ this.data = data;
12899
+ }
12900
+ static isInstance(error) {
12901
+ return AISDKError.hasMarker(error, marker6);
12902
+ }
12903
+ };
12904
+ _a6 = symbol6;
12905
+
12906
+ // src/errors/json-parse-error.ts
12907
+ var name6 = "AI_JSONParseError";
12908
+ var marker7 = `vercel.ai.error.${name6}`;
12909
+ var symbol7 = Symbol.for(marker7);
12910
+ var _a7;
12911
+ var JSONParseError = class extends AISDKError {
12912
+ constructor({ text, cause }) {
12913
+ super({
12914
+ name: name6,
12915
+ message: `JSON parsing failed: Text: ${text}.
12916
+ Error message: ${getErrorMessage(cause)}`,
12917
+ cause
12918
+ });
12919
+ this[_a7] = true;
12920
+ this.text = text;
12921
+ }
12922
+ static isInstance(error) {
12923
+ return AISDKError.hasMarker(error, marker7);
12924
+ }
12925
+ };
12926
+ _a7 = symbol7;
12927
+
12928
+ // src/errors/load-api-key-error.ts
12929
+ var name7 = "AI_LoadAPIKeyError";
12930
+ var marker8 = `vercel.ai.error.${name7}`;
12931
+ var symbol8 = Symbol.for(marker8);
12932
+ var _a8;
12933
+ var LoadAPIKeyError = class extends AISDKError {
12934
+ // used in isInstance
12935
+ constructor({ message }) {
12936
+ super({ name: name7, message });
12937
+ this[_a8] = true;
12938
+ }
12939
+ static isInstance(error) {
12940
+ return AISDKError.hasMarker(error, marker8);
12941
+ }
12942
+ };
12943
+ _a8 = symbol8;
12944
+
12945
+ // src/errors/type-validation-error.ts
12946
+ var name12 = "AI_TypeValidationError";
12947
+ var marker13 = `vercel.ai.error.${name12}`;
12948
+ var symbol13 = Symbol.for(marker13);
12949
+ var _a13;
12950
+ var _TypeValidationError = class _TypeValidationError extends AISDKError {
12951
+ constructor({ value, cause }) {
12952
+ super({
12953
+ name: name12,
12954
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
12955
+ Error message: ${getErrorMessage(cause)}`,
12956
+ cause
12957
+ });
12958
+ this[_a13] = true;
12959
+ this.value = value;
12960
+ }
12961
+ static isInstance(error) {
12962
+ return AISDKError.hasMarker(error, marker13);
12963
+ }
12964
+ /**
12965
+ * Wraps an error into a TypeValidationError.
12966
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
12967
+ * Otherwise, it creates a new TypeValidationError.
12968
+ *
12969
+ * @param {Object} params - The parameters for wrapping the error.
12970
+ * @param {unknown} params.value - The value that failed validation.
12971
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
12972
+ * @returns {TypeValidationError} A TypeValidationError instance.
12973
+ */
12974
+ static wrap({
12975
+ value,
12976
+ cause
12977
+ }) {
12978
+ return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause });
12979
+ }
12980
+ };
12981
+ _a13 = symbol13;
12982
+ var TypeValidationError = _TypeValidationError;
12983
+
12984
+ // src/errors/unsupported-functionality-error.ts
12985
+ var name13 = "AI_UnsupportedFunctionalityError";
12986
+ var marker14 = `vercel.ai.error.${name13}`;
12987
+ var symbol14 = Symbol.for(marker14);
12988
+ var _a14;
12989
+ var UnsupportedFunctionalityError = class extends AISDKError {
12990
+ constructor({
12991
+ functionality,
12992
+ message = `'${functionality}' functionality not supported.`
12993
+ }) {
12994
+ super({ name: name13, message });
12995
+ this[_a14] = true;
12996
+ this.functionality = functionality;
12997
+ }
12998
+ static isInstance(error) {
12999
+ return AISDKError.hasMarker(error, marker14);
13000
+ }
13001
+ };
13002
+ _a14 = symbol14;
13003
+
13004
+ var secureJsonParse = {exports: {}};
13005
+
13006
+ var hasRequiredSecureJsonParse;
13007
+
13008
+ function requireSecureJsonParse () {
13009
+ if (hasRequiredSecureJsonParse) return secureJsonParse.exports;
13010
+ hasRequiredSecureJsonParse = 1;
13011
+
13012
+ const hasBuffer = typeof Buffer !== 'undefined';
13013
+ const suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
13014
+ 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*:/;
13015
+
13016
+ function _parse (text, reviver, options) {
13017
+ // Normalize arguments
13018
+ if (options == null) {
13019
+ if (reviver !== null && typeof reviver === 'object') {
13020
+ options = reviver;
13021
+ reviver = undefined;
13022
+ }
13023
+ }
13024
+
13025
+ if (hasBuffer && Buffer.isBuffer(text)) {
13026
+ text = text.toString();
13027
+ }
13028
+
13029
+ // BOM checker
13030
+ if (text && text.charCodeAt(0) === 0xFEFF) {
13031
+ text = text.slice(1);
13032
+ }
13033
+
13034
+ // Parse normally, allowing exceptions
13035
+ const obj = JSON.parse(text, reviver);
13036
+
13037
+ // Ignore null and non-objects
13038
+ if (obj === null || typeof obj !== 'object') {
13039
+ return obj
13040
+ }
13041
+
13042
+ const protoAction = (options && options.protoAction) || 'error';
13043
+ const constructorAction = (options && options.constructorAction) || 'error';
13044
+
13045
+ // options: 'error' (default) / 'remove' / 'ignore'
13046
+ if (protoAction === 'ignore' && constructorAction === 'ignore') {
13047
+ return obj
13048
+ }
13049
+
13050
+ if (protoAction !== 'ignore' && constructorAction !== 'ignore') {
13051
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
13052
+ return obj
13053
+ }
13054
+ } else if (protoAction !== 'ignore' && constructorAction === 'ignore') {
13055
+ if (suspectProtoRx.test(text) === false) {
13056
+ return obj
13057
+ }
13058
+ } else {
13059
+ if (suspectConstructorRx.test(text) === false) {
13060
+ return obj
13061
+ }
13062
+ }
13063
+
13064
+ // Scan result for proto keys
13065
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe })
13066
+ }
13067
+
13068
+ function filter (obj, { protoAction = 'error', constructorAction = 'error', safe } = {}) {
13069
+ let next = [obj];
13070
+
13071
+ while (next.length) {
13072
+ const nodes = next;
13073
+ next = [];
13074
+
13075
+ for (const node of nodes) {
13076
+ if (protoAction !== 'ignore' && Object.prototype.hasOwnProperty.call(node, '__proto__')) { // Avoid calling node.hasOwnProperty directly
13077
+ if (safe === true) {
13078
+ return null
13079
+ } else if (protoAction === 'error') {
13080
+ throw new SyntaxError('Object contains forbidden prototype property')
13081
+ }
13082
+
13083
+ delete node.__proto__; // eslint-disable-line no-proto
13084
+ }
13085
+
13086
+ if (constructorAction !== 'ignore' &&
13087
+ Object.prototype.hasOwnProperty.call(node, 'constructor') &&
13088
+ Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')) { // Avoid calling node.hasOwnProperty directly
13089
+ if (safe === true) {
13090
+ return null
13091
+ } else if (constructorAction === 'error') {
13092
+ throw new SyntaxError('Object contains forbidden prototype property')
13093
+ }
13094
+
13095
+ delete node.constructor;
13096
+ }
13097
+
13098
+ for (const key in node) {
13099
+ const value = node[key];
13100
+ if (value && typeof value === 'object') {
13101
+ next.push(value);
13102
+ }
13103
+ }
13104
+ }
13105
+ }
13106
+ return obj
13107
+ }
13108
+
13109
+ function parse (text, reviver, options) {
13110
+ const stackTraceLimit = Error.stackTraceLimit;
13111
+ Error.stackTraceLimit = 0;
13112
+ try {
13113
+ return _parse(text, reviver, options)
13114
+ } finally {
13115
+ Error.stackTraceLimit = stackTraceLimit;
13116
+ }
13117
+ }
13118
+
13119
+ function safeParse (text, reviver) {
13120
+ const stackTraceLimit = Error.stackTraceLimit;
13121
+ Error.stackTraceLimit = 0;
13122
+ try {
13123
+ return _parse(text, reviver, { safe: true })
13124
+ } catch (_e) {
13125
+ return null
13126
+ } finally {
13127
+ Error.stackTraceLimit = stackTraceLimit;
13128
+ }
13129
+ }
13130
+
13131
+ secureJsonParse.exports = parse;
13132
+ secureJsonParse.exports.default = parse;
13133
+ secureJsonParse.exports.parse = parse;
13134
+ secureJsonParse.exports.safeParse = safeParse;
13135
+ secureJsonParse.exports.scan = filter;
13136
+ return secureJsonParse.exports;
13137
+ }
13138
+
13139
+ var secureJsonParseExports = requireSecureJsonParse();
13140
+ var SecureJSON = /*@__PURE__*/getDefaultExportFromCjs(secureJsonParseExports);
13141
+
13142
+ class ParseError extends Error {
13143
+ constructor(message, options) {
13144
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
13145
+ }
13146
+ }
13147
+ function noop(_arg) {
13148
+ }
13149
+ function createParser(callbacks) {
13150
+ if (typeof callbacks == "function")
13151
+ throw new TypeError(
13152
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
13153
+ );
13154
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
13155
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
13156
+ function feed(newChunk) {
13157
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
13158
+ for (const line of complete)
13159
+ parseLine(line);
13160
+ incompleteLine = incomplete, isFirstChunk = false;
13161
+ }
13162
+ function parseLine(line) {
13163
+ if (line === "") {
13164
+ dispatchEvent();
13165
+ return;
13166
+ }
13167
+ if (line.startsWith(":")) {
13168
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
13169
+ return;
13170
+ }
13171
+ const fieldSeparatorIndex = line.indexOf(":");
13172
+ if (fieldSeparatorIndex !== -1) {
13173
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
13174
+ processField(field, value, line);
13175
+ return;
13176
+ }
13177
+ processField(line, "", line);
13178
+ }
13179
+ function processField(field, value, line) {
13180
+ switch (field) {
13181
+ case "event":
13182
+ eventType = value;
13183
+ break;
13184
+ case "data":
13185
+ data = `${data}${value}
13186
+ `;
13187
+ break;
13188
+ case "id":
13189
+ id = value.includes("\0") ? void 0 : value;
13190
+ break;
13191
+ case "retry":
13192
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
13193
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
13194
+ type: "invalid-retry",
13195
+ value,
13196
+ line
13197
+ })
13198
+ );
13199
+ break;
13200
+ default:
13201
+ onError(
13202
+ new ParseError(
13203
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
13204
+ { type: "unknown-field", field, value, line }
13205
+ )
13206
+ );
13207
+ break;
13208
+ }
13209
+ }
13210
+ function dispatchEvent() {
13211
+ data.length > 0 && onEvent({
13212
+ id,
13213
+ event: eventType || void 0,
13214
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
13215
+ // then remove the last character from the data buffer.
13216
+ data: data.endsWith(`
13217
+ `) ? data.slice(0, -1) : data
13218
+ }), id = void 0, data = "", eventType = "";
13219
+ }
13220
+ function reset(options = {}) {
13221
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
13222
+ }
13223
+ return { feed, reset };
13224
+ }
13225
+ function splitLines(chunk) {
13226
+ const lines = [];
13227
+ let incompleteLine = "", searchIndex = 0;
13228
+ for (; searchIndex < chunk.length; ) {
13229
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
13230
+ `, searchIndex);
13231
+ let lineEnd = -1;
13232
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
13233
+ incompleteLine = chunk.slice(searchIndex);
13234
+ break;
13235
+ } else {
13236
+ const line = chunk.slice(searchIndex, lineEnd);
13237
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
13238
+ ` && searchIndex++;
13239
+ }
13240
+ }
13241
+ return [lines, incompleteLine];
13242
+ }
13243
+
13244
+ class EventSourceParserStream extends TransformStream {
13245
+ constructor({ onError, onRetry, onComment } = {}) {
13246
+ let parser;
13247
+ super({
13248
+ start(controller) {
13249
+ parser = createParser({
13250
+ onEvent: (event) => {
13251
+ controller.enqueue(event);
13252
+ },
13253
+ onError(error) {
13254
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
13255
+ },
13256
+ onRetry,
13257
+ onComment
13258
+ });
13259
+ },
13260
+ transform(chunk) {
13261
+ parser.feed(chunk);
13262
+ }
13263
+ });
13264
+ }
13265
+ }
13266
+
13267
+ // src/combine-headers.ts
13268
+ function combineHeaders(...headers) {
13269
+ return headers.reduce(
13270
+ (combinedHeaders, currentHeaders) => ({
13271
+ ...combinedHeaders,
13272
+ ...currentHeaders != null ? currentHeaders : {}
13273
+ }),
13274
+ {}
13275
+ );
13276
+ }
13277
+
13278
+ // src/extract-response-headers.ts
13279
+ function extractResponseHeaders(response) {
13280
+ const headers = {};
13281
+ response.headers.forEach((value, key) => {
13282
+ headers[key] = value;
13283
+ });
13284
+ return headers;
13285
+ }
13286
+ var createIdGenerator = ({
13287
+ prefix,
13288
+ size: defaultSize = 16,
13289
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
13290
+ separator = "-"
13291
+ } = {}) => {
13292
+ const generator = customAlphabet(alphabet, defaultSize);
13293
+ if (prefix == null) {
13294
+ return generator;
13295
+ }
13296
+ if (alphabet.includes(separator)) {
13297
+ throw new InvalidArgumentError({
13298
+ argument: "separator",
13299
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
13300
+ });
13301
+ }
13302
+ return (size) => `${prefix}${separator}${generator(size)}`;
13303
+ };
13304
+ var generateId = createIdGenerator();
13305
+
13306
+ // src/remove-undefined-entries.ts
13307
+ function removeUndefinedEntries(record) {
13308
+ return Object.fromEntries(
13309
+ Object.entries(record).filter(([_key, value]) => value != null)
13310
+ );
13311
+ }
13312
+
13313
+ // src/is-abort-error.ts
13314
+ function isAbortError(error) {
13315
+ return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
13316
+ }
13317
+ function loadApiKey({
13318
+ apiKey,
13319
+ environmentVariableName,
13320
+ apiKeyParameterName = "apiKey",
13321
+ description
13322
+ }) {
13323
+ if (typeof apiKey === "string") {
13324
+ return apiKey;
13325
+ }
13326
+ if (apiKey != null) {
13327
+ throw new LoadAPIKeyError({
13328
+ message: `${description} API key must be a string.`
13329
+ });
13330
+ }
13331
+ if (typeof process === "undefined") {
13332
+ throw new LoadAPIKeyError({
13333
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
13334
+ });
13335
+ }
13336
+ apiKey = process.env[environmentVariableName];
13337
+ if (apiKey == null) {
13338
+ throw new LoadAPIKeyError({
13339
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
13340
+ });
13341
+ }
13342
+ if (typeof apiKey !== "string") {
13343
+ throw new LoadAPIKeyError({
13344
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
13345
+ });
13346
+ }
13347
+ return apiKey;
13348
+ }
13349
+
13350
+ // src/validator.ts
13351
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
13352
+ function validator(validate) {
13353
+ return { [validatorSymbol]: true, validate };
13354
+ }
13355
+ function isValidator(value) {
13356
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
13357
+ }
13358
+ function asValidator(value) {
13359
+ return isValidator(value) ? value : zodValidator(value);
13360
+ }
13361
+ function zodValidator(zodSchema) {
13362
+ return validator((value) => {
13363
+ const result = zodSchema.safeParse(value);
13364
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
13365
+ });
13366
+ }
13367
+
13368
+ // src/validate-types.ts
13369
+ function validateTypes({
13370
+ value,
13371
+ schema: inputSchema
13372
+ }) {
13373
+ const result = safeValidateTypes({ value, schema: inputSchema });
13374
+ if (!result.success) {
13375
+ throw TypeValidationError.wrap({ value, cause: result.error });
13376
+ }
13377
+ return result.value;
13378
+ }
13379
+ function safeValidateTypes({
13380
+ value,
13381
+ schema
13382
+ }) {
13383
+ const validator2 = asValidator(schema);
13384
+ try {
13385
+ if (validator2.validate == null) {
13386
+ return { success: true, value };
13387
+ }
13388
+ const result = validator2.validate(value);
13389
+ if (result.success) {
13390
+ return result;
13391
+ }
13392
+ return {
13393
+ success: false,
13394
+ error: TypeValidationError.wrap({ value, cause: result.error })
13395
+ };
13396
+ } catch (error) {
13397
+ return {
13398
+ success: false,
13399
+ error: TypeValidationError.wrap({ value, cause: error })
13400
+ };
13401
+ }
13402
+ }
13403
+
13404
+ // src/parse-json.ts
13405
+ function parseJSON({
13406
+ text,
13407
+ schema
13408
+ }) {
13409
+ try {
13410
+ const value = SecureJSON.parse(text);
13411
+ if (schema == null) {
13412
+ return value;
13413
+ }
13414
+ return validateTypes({ value, schema });
13415
+ } catch (error) {
13416
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
13417
+ throw error;
13418
+ }
13419
+ throw new JSONParseError({ text, cause: error });
13420
+ }
13421
+ }
13422
+ function safeParseJSON({
13423
+ text,
13424
+ schema
13425
+ }) {
13426
+ try {
13427
+ const value = SecureJSON.parse(text);
13428
+ if (schema == null) {
13429
+ return { success: true, value, rawValue: value };
13430
+ }
13431
+ const validationResult = safeValidateTypes({ value, schema });
13432
+ return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
13433
+ } catch (error) {
13434
+ return {
13435
+ success: false,
13436
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
13437
+ };
13438
+ }
13439
+ }
13440
+ function isParsableJson(input) {
13441
+ try {
13442
+ SecureJSON.parse(input);
13443
+ return true;
13444
+ } catch (e) {
13445
+ return false;
13446
+ }
13447
+ }
13448
+ var getOriginalFetch2 = () => globalThis.fetch;
13449
+ var postJsonToApi = async ({
13450
+ url,
13451
+ headers,
13452
+ body,
13453
+ failedResponseHandler,
13454
+ successfulResponseHandler,
13455
+ abortSignal,
13456
+ fetch
13457
+ }) => postToApi({
13458
+ url,
13459
+ headers: {
13460
+ "Content-Type": "application/json",
13461
+ ...headers
13462
+ },
13463
+ body: {
13464
+ content: JSON.stringify(body),
13465
+ values: body
13466
+ },
13467
+ failedResponseHandler,
13468
+ successfulResponseHandler,
13469
+ abortSignal,
13470
+ fetch
13471
+ });
13472
+ var postToApi = async ({
13473
+ url,
13474
+ headers = {},
13475
+ body,
13476
+ successfulResponseHandler,
13477
+ failedResponseHandler,
13478
+ abortSignal,
13479
+ fetch = getOriginalFetch2()
13480
+ }) => {
13481
+ try {
13482
+ const response = await fetch(url, {
13483
+ method: "POST",
13484
+ headers: removeUndefinedEntries(headers),
13485
+ body: body.content,
13486
+ signal: abortSignal
13487
+ });
13488
+ const responseHeaders = extractResponseHeaders(response);
13489
+ if (!response.ok) {
13490
+ let errorInformation;
13491
+ try {
13492
+ errorInformation = await failedResponseHandler({
13493
+ response,
13494
+ url,
13495
+ requestBodyValues: body.values
13496
+ });
13497
+ } catch (error) {
13498
+ if (isAbortError(error) || APICallError.isInstance(error)) {
13499
+ throw error;
13500
+ }
13501
+ throw new APICallError({
13502
+ message: "Failed to process error response",
13503
+ cause: error,
13504
+ statusCode: response.status,
13505
+ url,
13506
+ responseHeaders,
13507
+ requestBodyValues: body.values
13508
+ });
13509
+ }
13510
+ throw errorInformation.value;
13511
+ }
13512
+ try {
13513
+ return await successfulResponseHandler({
13514
+ response,
13515
+ url,
13516
+ requestBodyValues: body.values
13517
+ });
13518
+ } catch (error) {
13519
+ if (error instanceof Error) {
13520
+ if (isAbortError(error) || APICallError.isInstance(error)) {
13521
+ throw error;
13522
+ }
13523
+ }
13524
+ throw new APICallError({
13525
+ message: "Failed to process successful response",
13526
+ cause: error,
13527
+ statusCode: response.status,
13528
+ url,
13529
+ responseHeaders,
13530
+ requestBodyValues: body.values
13531
+ });
13532
+ }
13533
+ } catch (error) {
13534
+ if (isAbortError(error)) {
13535
+ throw error;
13536
+ }
13537
+ if (error instanceof TypeError && error.message === "fetch failed") {
13538
+ const cause = error.cause;
13539
+ if (cause != null) {
13540
+ throw new APICallError({
13541
+ message: `Cannot connect to API: ${cause.message}`,
13542
+ cause,
13543
+ url,
13544
+ requestBodyValues: body.values,
13545
+ isRetryable: true
13546
+ // retry when network error
13547
+ });
13548
+ }
13549
+ }
13550
+ throw error;
13551
+ }
13552
+ };
13553
+ var createJsonErrorResponseHandler = ({
13554
+ errorSchema,
13555
+ errorToMessage,
13556
+ isRetryable
13557
+ }) => async ({ response, url, requestBodyValues }) => {
13558
+ const responseBody = await response.text();
13559
+ const responseHeaders = extractResponseHeaders(response);
13560
+ if (responseBody.trim() === "") {
13561
+ return {
13562
+ responseHeaders,
13563
+ value: new APICallError({
13564
+ message: response.statusText,
13565
+ url,
13566
+ requestBodyValues,
13567
+ statusCode: response.status,
13568
+ responseHeaders,
13569
+ responseBody,
13570
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13571
+ })
13572
+ };
13573
+ }
13574
+ try {
13575
+ const parsedError = parseJSON({
13576
+ text: responseBody,
13577
+ schema: errorSchema
13578
+ });
13579
+ return {
13580
+ responseHeaders,
13581
+ value: new APICallError({
13582
+ message: errorToMessage(parsedError),
13583
+ url,
13584
+ requestBodyValues,
13585
+ statusCode: response.status,
13586
+ responseHeaders,
13587
+ responseBody,
13588
+ data: parsedError,
13589
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
13590
+ })
13591
+ };
13592
+ } catch (parseError) {
13593
+ return {
13594
+ responseHeaders,
13595
+ value: new APICallError({
13596
+ message: response.statusText,
13597
+ url,
13598
+ requestBodyValues,
13599
+ statusCode: response.status,
13600
+ responseHeaders,
13601
+ responseBody,
13602
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
13603
+ })
13604
+ };
13605
+ }
13606
+ };
13607
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
13608
+ const responseHeaders = extractResponseHeaders(response);
13609
+ if (response.body == null) {
13610
+ throw new EmptyResponseBodyError({});
13611
+ }
13612
+ return {
13613
+ responseHeaders,
13614
+ value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
13615
+ new TransformStream({
13616
+ transform({ data }, controller) {
13617
+ if (data === "[DONE]") {
13618
+ return;
13619
+ }
13620
+ controller.enqueue(
13621
+ safeParseJSON({
13622
+ text: data,
13623
+ schema: chunkSchema
13624
+ })
13625
+ );
13626
+ }
13627
+ })
13628
+ )
13629
+ };
13630
+ };
13631
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
13632
+ const responseBody = await response.text();
13633
+ const parsedResult = safeParseJSON({
13634
+ text: responseBody,
13635
+ schema: responseSchema
13636
+ });
13637
+ const responseHeaders = extractResponseHeaders(response);
13638
+ if (!parsedResult.success) {
13639
+ throw new APICallError({
13640
+ message: "Invalid JSON response",
13641
+ cause: parsedResult.error,
13642
+ statusCode: response.status,
13643
+ responseHeaders,
13644
+ responseBody,
13645
+ url,
13646
+ requestBodyValues
13647
+ });
13648
+ }
13649
+ return {
13650
+ responseHeaders,
13651
+ value: parsedResult.value,
13652
+ rawValue: parsedResult.rawValue
13653
+ };
13654
+ };
13655
+
13656
+ // src/uint8-utils.ts
13657
+ var { btoa} = globalThis;
13658
+ function convertUint8ArrayToBase64(array) {
13659
+ let latin1string = "";
13660
+ for (let i = 0; i < array.length; i++) {
13661
+ latin1string += String.fromCodePoint(array[i]);
13662
+ }
13663
+ return btoa(latin1string);
13664
+ }
13665
+
13666
+ // src/without-trailing-slash.ts
13667
+ function withoutTrailingSlash(url) {
13668
+ return url == null ? void 0 : url.replace(/\/$/, "");
13669
+ }
13670
+
13671
+ var __defProp = Object.defineProperty;
13672
+ var __defProps = Object.defineProperties;
13673
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
13674
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
13675
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13676
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
13677
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13678
+ var __spreadValues = (a, b) => {
13679
+ for (var prop in b || (b = {}))
13680
+ if (__hasOwnProp.call(b, prop))
13681
+ __defNormalProp(a, prop, b[prop]);
13682
+ if (__getOwnPropSymbols)
13683
+ for (var prop of __getOwnPropSymbols(b)) {
13684
+ if (__propIsEnum.call(b, prop))
13685
+ __defNormalProp(a, prop, b[prop]);
13686
+ }
13687
+ return a;
13688
+ };
13689
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
13690
+ var __objRest = (source, exclude) => {
13691
+ var target = {};
13692
+ for (var prop in source)
13693
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
13694
+ target[prop] = source[prop];
13695
+ if (source != null && __getOwnPropSymbols)
13696
+ for (var prop of __getOwnPropSymbols(source)) {
13697
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
13698
+ target[prop] = source[prop];
13699
+ }
13700
+ return target;
13701
+ };
13702
+ function getCacheControl(providerMetadata) {
13703
+ var _a, _b, _c;
13704
+ const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
13705
+ const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
13706
+ 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;
13707
+ }
13708
+ function convertToOpenRouterChatMessages(prompt) {
13709
+ var _a, _b, _c;
13710
+ const messages = [];
13711
+ for (const { role, content, providerMetadata } of prompt) {
13712
+ switch (role) {
13713
+ case "system": {
13714
+ messages.push({
13715
+ role: "system",
13716
+ content,
13717
+ cache_control: getCacheControl(providerMetadata)
13718
+ });
13719
+ break;
13720
+ }
13721
+ case "user": {
13722
+ if (content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
13723
+ messages.push({
13724
+ role: "user",
13725
+ content: content[0].text,
13726
+ cache_control: (_b = getCacheControl(providerMetadata)) != null ? _b : getCacheControl(content[0].providerMetadata)
13727
+ });
13728
+ break;
13729
+ }
13730
+ const messageCacheControl = getCacheControl(providerMetadata);
13731
+ const contentParts = content.map(
13732
+ (part) => {
13733
+ var _a2, _b2, _c2, _d;
13734
+ switch (part.type) {
13735
+ case "text":
13736
+ return {
13737
+ type: "text",
13738
+ text: part.text,
13739
+ // For text parts, only use part-specific cache control
13740
+ cache_control: (_a2 = getCacheControl(part.providerMetadata)) != null ? _a2 : messageCacheControl
13741
+ };
13742
+ case "image":
13743
+ return {
13744
+ type: "image_url",
13745
+ image_url: {
13746
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_b2 = part.mimeType) != null ? _b2 : "image/jpeg"};base64,${convertUint8ArrayToBase64(
13747
+ part.image
13748
+ )}`
13749
+ },
13750
+ // For image parts, use part-specific or message-level cache control
13751
+ cache_control: (_c2 = getCacheControl(part.providerMetadata)) != null ? _c2 : messageCacheControl
13752
+ };
13753
+ case "file":
13754
+ return {
13755
+ type: "text",
13756
+ text: part.data instanceof URL ? part.data.toString() : part.data,
13757
+ cache_control: (_d = getCacheControl(part.providerMetadata)) != null ? _d : messageCacheControl
13758
+ };
13759
+ default: {
13760
+ const _exhaustiveCheck = part;
13761
+ throw new Error(
13762
+ `Unsupported content part type: ${_exhaustiveCheck}`
13763
+ );
13764
+ }
13765
+ }
13766
+ }
13767
+ );
13768
+ messages.push({
13769
+ role: "user",
13770
+ content: contentParts
13771
+ });
13772
+ break;
13773
+ }
13774
+ case "assistant": {
13775
+ let text = "";
13776
+ const toolCalls = [];
13777
+ for (const part of content) {
13778
+ switch (part.type) {
13779
+ case "text": {
13780
+ text += part.text;
13781
+ break;
13782
+ }
13783
+ case "tool-call": {
13784
+ toolCalls.push({
13785
+ id: part.toolCallId,
13786
+ type: "function",
13787
+ function: {
13788
+ name: part.toolName,
13789
+ arguments: JSON.stringify(part.args)
13790
+ }
13791
+ });
13792
+ break;
13793
+ }
13794
+ // TODO: Handle reasoning and redacted-reasoning
13795
+ case "reasoning":
13796
+ case "redacted-reasoning":
13797
+ break;
13798
+ default: {
13799
+ const _exhaustiveCheck = part;
13800
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
13801
+ }
13802
+ }
13803
+ }
13804
+ messages.push({
13805
+ role: "assistant",
13806
+ content: text,
13807
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
13808
+ cache_control: getCacheControl(providerMetadata)
13809
+ });
13810
+ break;
13811
+ }
13812
+ case "tool": {
13813
+ for (const toolResponse of content) {
13814
+ messages.push({
13815
+ role: "tool",
13816
+ tool_call_id: toolResponse.toolCallId,
13817
+ content: JSON.stringify(toolResponse.result),
13818
+ cache_control: (_c = getCacheControl(providerMetadata)) != null ? _c : getCacheControl(toolResponse.providerMetadata)
13819
+ });
13820
+ }
13821
+ break;
13822
+ }
13823
+ default: {
13824
+ const _exhaustiveCheck = role;
13825
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
13826
+ }
13827
+ }
13828
+ }
13829
+ return messages;
13830
+ }
13831
+
13832
+ // src/map-openrouter-chat-logprobs.ts
13833
+ function mapOpenRouterChatLogProbsOutput(logprobs) {
13834
+ var _a, _b;
13835
+ return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
13836
+ token,
13837
+ logprob,
13838
+ topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
13839
+ token: token2,
13840
+ logprob: logprob2
13841
+ })) : []
13842
+ }))) != null ? _b : void 0;
13843
+ }
13844
+
13845
+ // src/map-openrouter-finish-reason.ts
13846
+ function mapOpenRouterFinishReason(finishReason) {
13847
+ switch (finishReason) {
13848
+ case "stop":
13849
+ return "stop";
13850
+ case "length":
13851
+ return "length";
13852
+ case "content_filter":
13853
+ return "content-filter";
13854
+ case "function_call":
13855
+ case "tool_calls":
13856
+ return "tool-calls";
13857
+ default:
13858
+ return "unknown";
13859
+ }
13860
+ }
13861
+ var OpenRouterErrorResponseSchema = z.object({
13862
+ error: z.object({
13863
+ message: z.string(),
13864
+ type: z.string(),
13865
+ param: z.any().nullable(),
13866
+ code: z.string().nullable()
13867
+ })
13868
+ });
13869
+ var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
13870
+ errorSchema: OpenRouterErrorResponseSchema,
13871
+ errorToMessage: (data) => data.error.message
13872
+ });
13873
+
13874
+ // src/openrouter-chat-language-model.ts
13875
+ function isFunctionTool(tool) {
13876
+ return "parameters" in tool;
13877
+ }
13878
+ var OpenRouterChatLanguageModel = class {
13879
+ constructor(modelId, settings, config) {
13880
+ this.specificationVersion = "v1";
13881
+ this.defaultObjectGenerationMode = "tool";
13882
+ this.modelId = modelId;
13883
+ this.settings = settings;
13884
+ this.config = config;
13885
+ }
13886
+ get provider() {
13887
+ return this.config.provider;
13888
+ }
13889
+ getArgs({
13890
+ mode,
13891
+ prompt,
13892
+ maxTokens,
13893
+ temperature,
13894
+ topP,
13895
+ frequencyPenalty,
13896
+ presencePenalty,
13897
+ seed,
13898
+ stopSequences,
13899
+ responseFormat,
13900
+ topK,
13901
+ providerMetadata
13902
+ }) {
13903
+ var _a;
13904
+ const type = mode.type;
13905
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
13906
+ const baseArgs = __spreadValues(__spreadValues(__spreadValues({
13907
+ // model id:
13908
+ model: this.modelId,
13909
+ models: this.settings.models,
13910
+ // model specific settings:
13911
+ logit_bias: this.settings.logitBias,
13912
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
13913
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
13914
+ user: this.settings.user,
13915
+ parallel_tool_calls: this.settings.parallelToolCalls,
13916
+ // standardized settings:
13917
+ max_tokens: maxTokens,
13918
+ temperature,
13919
+ top_p: topP,
13920
+ frequency_penalty: frequencyPenalty,
13921
+ presence_penalty: presencePenalty,
13922
+ seed,
13923
+ stop: stopSequences,
13924
+ response_format: responseFormat,
13925
+ top_k: topK,
13926
+ // messages:
13927
+ messages: convertToOpenRouterChatMessages(prompt),
13928
+ // OpenRouter specific settings:
13929
+ include_reasoning: this.settings.includeReasoning,
13930
+ reasoning: this.settings.reasoning
13931
+ }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
13932
+ switch (type) {
13933
+ case "regular": {
13934
+ return __spreadValues(__spreadValues({}, baseArgs), prepareToolsAndToolChoice(mode));
13935
+ }
13936
+ case "object-json": {
13937
+ return __spreadProps(__spreadValues({}, baseArgs), {
13938
+ response_format: { type: "json_object" }
13939
+ });
13940
+ }
13941
+ case "object-tool": {
13942
+ return __spreadProps(__spreadValues({}, baseArgs), {
13943
+ tool_choice: { type: "function", function: { name: mode.tool.name } },
13944
+ tools: [
13945
+ {
13946
+ type: "function",
13947
+ function: {
13948
+ name: mode.tool.name,
13949
+ description: mode.tool.description,
13950
+ parameters: mode.tool.parameters
13951
+ }
13952
+ }
13953
+ ]
13954
+ });
13955
+ }
13956
+ // Handle all non-text types with a single default case
13957
+ default: {
13958
+ const _exhaustiveCheck = type;
13959
+ throw new UnsupportedFunctionalityError({
13960
+ functionality: `${_exhaustiveCheck} mode`
13961
+ });
13962
+ }
13963
+ }
13964
+ }
13965
+ async doGenerate(options) {
13966
+ var _b, _c, _d, _e, _f, _g, _h;
13967
+ const args = this.getArgs(options);
13968
+ const { responseHeaders, value: response } = await postJsonToApi({
13969
+ url: this.config.url({
13970
+ path: "/chat/completions",
13971
+ modelId: this.modelId
13972
+ }),
13973
+ headers: combineHeaders(this.config.headers(), options.headers),
13974
+ body: args,
13975
+ failedResponseHandler: openrouterFailedResponseHandler,
13976
+ successfulResponseHandler: createJsonResponseHandler(
13977
+ OpenRouterNonStreamChatCompletionResponseSchema
13978
+ ),
13979
+ abortSignal: options.abortSignal,
13980
+ fetch: this.config.fetch
13981
+ });
13982
+ const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
13983
+ const choice = response.choices[0];
13984
+ if (!choice) {
13985
+ throw new Error("No choice in response");
13986
+ }
13987
+ return {
13988
+ response: {
13989
+ id: response.id,
13990
+ modelId: response.model
13991
+ },
13992
+ text: (_b = choice.message.content) != null ? _b : void 0,
13993
+ reasoning: (_c = choice.message.reasoning) != null ? _c : void 0,
13994
+ toolCalls: (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => {
13995
+ var _a2;
13996
+ return {
13997
+ toolCallType: "function",
13998
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
13999
+ toolName: toolCall.function.name,
14000
+ args: toolCall.function.arguments
14001
+ };
14002
+ }),
14003
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
14004
+ usage: {
14005
+ promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : 0,
14006
+ completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : 0
14007
+ },
14008
+ rawCall: { rawPrompt, rawSettings },
14009
+ rawResponse: { headers: responseHeaders },
14010
+ warnings: [],
14011
+ logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
14012
+ };
14013
+ }
14014
+ async doStream(options) {
14015
+ const args = this.getArgs(options);
14016
+ const { responseHeaders, value: response } = await postJsonToApi({
14017
+ url: this.config.url({
14018
+ path: "/chat/completions",
14019
+ modelId: this.modelId
14020
+ }),
14021
+ headers: combineHeaders(this.config.headers(), options.headers),
14022
+ body: __spreadProps(__spreadValues({}, args), {
14023
+ stream: true,
14024
+ // only include stream_options when in strict compatibility mode:
14025
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
14026
+ }),
14027
+ failedResponseHandler: openrouterFailedResponseHandler,
14028
+ successfulResponseHandler: createEventSourceResponseHandler(
14029
+ OpenRouterStreamChatCompletionChunkSchema
14030
+ ),
14031
+ abortSignal: options.abortSignal,
14032
+ fetch: this.config.fetch
14033
+ });
14034
+ const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
14035
+ const toolCalls = [];
14036
+ let finishReason = "other";
14037
+ let usage = {
14038
+ promptTokens: Number.NaN,
14039
+ completionTokens: Number.NaN
14040
+ };
14041
+ let logprobs;
14042
+ return {
14043
+ stream: response.pipeThrough(
14044
+ new TransformStream({
14045
+ transform(chunk, controller) {
14046
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
14047
+ if (!chunk.success) {
14048
+ finishReason = "error";
14049
+ controller.enqueue({ type: "error", error: chunk.error });
14050
+ return;
14051
+ }
14052
+ const value = chunk.value;
14053
+ if ("error" in value) {
14054
+ finishReason = "error";
14055
+ controller.enqueue({ type: "error", error: value.error });
14056
+ return;
14057
+ }
14058
+ if (value.id) {
14059
+ controller.enqueue({
14060
+ type: "response-metadata",
14061
+ id: value.id
14062
+ });
14063
+ }
14064
+ if (value.model) {
14065
+ controller.enqueue({
14066
+ type: "response-metadata",
14067
+ modelId: value.model
14068
+ });
14069
+ }
14070
+ if (value.usage != null) {
14071
+ usage = {
14072
+ promptTokens: value.usage.prompt_tokens,
14073
+ completionTokens: value.usage.completion_tokens
14074
+ };
14075
+ }
14076
+ const choice = value.choices[0];
14077
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
14078
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
14079
+ }
14080
+ if ((choice == null ? void 0 : choice.delta) == null) {
14081
+ return;
14082
+ }
14083
+ const delta = choice.delta;
14084
+ if (delta.content != null) {
14085
+ controller.enqueue({
14086
+ type: "text-delta",
14087
+ textDelta: delta.content
14088
+ });
14089
+ }
14090
+ if (delta.reasoning != null) {
14091
+ controller.enqueue({
14092
+ type: "reasoning",
14093
+ textDelta: delta.reasoning
14094
+ });
14095
+ }
14096
+ const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
14097
+ choice == null ? void 0 : choice.logprobs
14098
+ );
14099
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14100
+ if (logprobs === void 0) logprobs = [];
14101
+ logprobs.push(...mappedLogprobs);
14102
+ }
14103
+ if (delta.tool_calls != null) {
14104
+ for (const toolCallDelta of delta.tool_calls) {
14105
+ const index = toolCallDelta.index;
14106
+ if (toolCalls[index] == null) {
14107
+ if (toolCallDelta.type !== "function") {
14108
+ throw new InvalidResponseDataError({
14109
+ data: toolCallDelta,
14110
+ message: `Expected 'function' type.`
14111
+ });
14112
+ }
14113
+ if (toolCallDelta.id == null) {
14114
+ throw new InvalidResponseDataError({
14115
+ data: toolCallDelta,
14116
+ message: `Expected 'id' to be a string.`
14117
+ });
14118
+ }
14119
+ if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
14120
+ throw new InvalidResponseDataError({
14121
+ data: toolCallDelta,
14122
+ message: `Expected 'function.name' to be a string.`
14123
+ });
14124
+ }
14125
+ toolCalls[index] = {
14126
+ id: toolCallDelta.id,
14127
+ type: "function",
14128
+ function: {
14129
+ name: toolCallDelta.function.name,
14130
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
14131
+ },
14132
+ sent: false
14133
+ };
14134
+ const toolCall2 = toolCalls[index];
14135
+ if (toolCall2 == null) {
14136
+ throw new Error("Tool call is missing");
14137
+ }
14138
+ if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
14139
+ controller.enqueue({
14140
+ type: "tool-call-delta",
14141
+ toolCallType: "function",
14142
+ toolCallId: toolCall2.id,
14143
+ toolName: toolCall2.function.name,
14144
+ argsTextDelta: toolCall2.function.arguments
14145
+ });
14146
+ controller.enqueue({
14147
+ type: "tool-call",
14148
+ toolCallType: "function",
14149
+ toolCallId: (_e = toolCall2.id) != null ? _e : generateId(),
14150
+ toolName: toolCall2.function.name,
14151
+ args: toolCall2.function.arguments
14152
+ });
14153
+ toolCall2.sent = true;
14154
+ }
14155
+ continue;
14156
+ }
14157
+ const toolCall = toolCalls[index];
14158
+ if (toolCall == null) {
14159
+ throw new Error("Tool call is missing");
14160
+ }
14161
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
14162
+ toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
14163
+ }
14164
+ controller.enqueue({
14165
+ type: "tool-call-delta",
14166
+ toolCallType: "function",
14167
+ toolCallId: toolCall.id,
14168
+ toolName: toolCall.function.name,
14169
+ argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
14170
+ });
14171
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) {
14172
+ controller.enqueue({
14173
+ type: "tool-call",
14174
+ toolCallType: "function",
14175
+ toolCallId: (_l = toolCall.id) != null ? _l : generateId(),
14176
+ toolName: toolCall.function.name,
14177
+ args: toolCall.function.arguments
14178
+ });
14179
+ toolCall.sent = true;
14180
+ }
14181
+ }
14182
+ }
14183
+ },
14184
+ flush(controller) {
14185
+ var _a2;
14186
+ if (finishReason === "tool-calls") {
14187
+ for (const toolCall of toolCalls) {
14188
+ if (!toolCall.sent) {
14189
+ controller.enqueue({
14190
+ type: "tool-call",
14191
+ toolCallType: "function",
14192
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
14193
+ toolName: toolCall.function.name,
14194
+ // Coerce invalid arguments to an empty JSON object
14195
+ args: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}"
14196
+ });
14197
+ toolCall.sent = true;
14198
+ }
14199
+ }
14200
+ }
14201
+ controller.enqueue({
14202
+ type: "finish",
14203
+ finishReason,
14204
+ logprobs,
14205
+ usage
14206
+ });
14207
+ }
14208
+ })
14209
+ ),
14210
+ rawCall: { rawPrompt, rawSettings },
14211
+ rawResponse: { headers: responseHeaders },
14212
+ warnings: []
14213
+ };
14214
+ }
14215
+ };
14216
+ var OpenRouterChatCompletionBaseResponseSchema = z.object({
14217
+ id: z.string().optional(),
14218
+ model: z.string().optional(),
14219
+ usage: z.object({
14220
+ prompt_tokens: z.number(),
14221
+ completion_tokens: z.number(),
14222
+ total_tokens: z.number()
14223
+ }).nullish()
14224
+ });
14225
+ var OpenRouterNonStreamChatCompletionResponseSchema = OpenRouterChatCompletionBaseResponseSchema.extend({
14226
+ choices: z.array(
14227
+ z.object({
14228
+ message: z.object({
14229
+ role: z.literal("assistant"),
14230
+ content: z.string().nullable().optional(),
14231
+ reasoning: z.string().nullable().optional(),
14232
+ tool_calls: z.array(
14233
+ z.object({
14234
+ id: z.string().optional().nullable(),
14235
+ type: z.literal("function"),
14236
+ function: z.object({
14237
+ name: z.string(),
14238
+ arguments: z.string()
14239
+ })
14240
+ })
14241
+ ).optional()
14242
+ }),
14243
+ index: z.number(),
14244
+ logprobs: z.object({
14245
+ content: z.array(
14246
+ z.object({
14247
+ token: z.string(),
14248
+ logprob: z.number(),
14249
+ top_logprobs: z.array(
14250
+ z.object({
14251
+ token: z.string(),
14252
+ logprob: z.number()
14253
+ })
14254
+ )
14255
+ })
14256
+ ).nullable()
14257
+ }).nullable().optional(),
14258
+ finish_reason: z.string().optional().nullable()
14259
+ })
14260
+ )
14261
+ });
14262
+ var OpenRouterStreamChatCompletionChunkSchema = z.union([
14263
+ OpenRouterChatCompletionBaseResponseSchema.extend({
14264
+ choices: z.array(
14265
+ z.object({
14266
+ delta: z.object({
14267
+ role: z.enum(["assistant"]).optional(),
14268
+ content: z.string().nullish(),
14269
+ reasoning: z.string().nullish().optional(),
14270
+ tool_calls: z.array(
14271
+ z.object({
14272
+ index: z.number(),
14273
+ id: z.string().nullish(),
14274
+ type: z.literal("function").optional(),
14275
+ function: z.object({
14276
+ name: z.string().nullish(),
14277
+ arguments: z.string().nullish()
14278
+ })
14279
+ })
14280
+ ).nullish()
14281
+ }).nullish(),
14282
+ logprobs: z.object({
14283
+ content: z.array(
14284
+ z.object({
14285
+ token: z.string(),
14286
+ logprob: z.number(),
14287
+ top_logprobs: z.array(
14288
+ z.object({
14289
+ token: z.string(),
14290
+ logprob: z.number()
14291
+ })
14292
+ )
14293
+ })
14294
+ ).nullable()
14295
+ }).nullish(),
14296
+ finish_reason: z.string().nullable().optional(),
14297
+ index: z.number()
14298
+ })
14299
+ )
14300
+ }),
14301
+ OpenRouterErrorResponseSchema
14302
+ ]);
14303
+ function prepareToolsAndToolChoice(mode) {
14304
+ var _a;
14305
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
14306
+ if (tools == null) {
14307
+ return { tools: void 0, tool_choice: void 0 };
14308
+ }
14309
+ const mappedTools = tools.map((tool) => {
14310
+ if (isFunctionTool(tool)) {
14311
+ return {
14312
+ type: "function",
14313
+ function: {
14314
+ name: tool.name,
14315
+ description: tool.description,
14316
+ parameters: tool.parameters
14317
+ }
14318
+ };
14319
+ } else {
14320
+ return {
14321
+ type: "function",
14322
+ function: {
14323
+ name: tool.name
14324
+ }
14325
+ };
14326
+ }
14327
+ });
14328
+ const toolChoice = mode.toolChoice;
14329
+ if (toolChoice == null) {
14330
+ return { tools: mappedTools, tool_choice: void 0 };
14331
+ }
14332
+ const type = toolChoice.type;
14333
+ switch (type) {
14334
+ case "auto":
14335
+ case "none":
14336
+ case "required":
14337
+ return { tools: mappedTools, tool_choice: type };
14338
+ case "tool":
14339
+ return {
14340
+ tools: mappedTools,
14341
+ tool_choice: {
14342
+ type: "function",
14343
+ function: {
14344
+ name: toolChoice.toolName
14345
+ }
14346
+ }
14347
+ };
14348
+ default: {
14349
+ const _exhaustiveCheck = type;
14350
+ throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
14351
+ }
14352
+ }
14353
+ }
14354
+ function convertToOpenRouterCompletionPrompt({
14355
+ prompt,
14356
+ inputFormat,
14357
+ user = "user",
14358
+ assistant = "assistant"
14359
+ }) {
14360
+ 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") {
14361
+ return { prompt: prompt[0].content[0].text };
14362
+ }
14363
+ let text = "";
14364
+ if (prompt[0] && prompt[0].role === "system") {
14365
+ text += `${prompt[0].content}
14366
+
14367
+ `;
14368
+ prompt = prompt.slice(1);
14369
+ }
14370
+ for (const { role, content } of prompt) {
14371
+ switch (role) {
14372
+ case "system": {
14373
+ throw new InvalidPromptError({
14374
+ message: "Unexpected system message in prompt: ${content}",
14375
+ prompt
14376
+ });
14377
+ }
14378
+ case "user": {
14379
+ const userMessage = content.map((part) => {
14380
+ switch (part.type) {
14381
+ case "text": {
14382
+ return part.text;
14383
+ }
14384
+ case "image": {
14385
+ throw new UnsupportedFunctionalityError({
14386
+ functionality: "images"
14387
+ });
14388
+ }
14389
+ case "file": {
14390
+ throw new UnsupportedFunctionalityError({
14391
+ functionality: "file attachments"
14392
+ });
14393
+ }
14394
+ default: {
14395
+ const _exhaustiveCheck = part;
14396
+ throw new Error(
14397
+ `Unsupported content type: ${_exhaustiveCheck}`
14398
+ );
14399
+ }
14400
+ }
14401
+ }).join("");
14402
+ text += `${user}:
14403
+ ${userMessage}
14404
+
14405
+ `;
14406
+ break;
14407
+ }
14408
+ case "assistant": {
14409
+ const assistantMessage = content.map((part) => {
14410
+ switch (part.type) {
14411
+ case "text": {
14412
+ return part.text;
14413
+ }
14414
+ case "tool-call": {
14415
+ throw new UnsupportedFunctionalityError({
14416
+ functionality: "tool-call messages"
14417
+ });
14418
+ }
14419
+ case "reasoning": {
14420
+ throw new UnsupportedFunctionalityError({
14421
+ functionality: "reasoning messages"
14422
+ });
14423
+ }
14424
+ case "redacted-reasoning": {
14425
+ throw new UnsupportedFunctionalityError({
14426
+ functionality: "redacted reasoning messages"
14427
+ });
14428
+ }
14429
+ default: {
14430
+ const _exhaustiveCheck = part;
14431
+ throw new Error(
14432
+ `Unsupported content type: ${_exhaustiveCheck}`
14433
+ );
14434
+ }
14435
+ }
14436
+ }).join("");
14437
+ text += `${assistant}:
14438
+ ${assistantMessage}
14439
+
14440
+ `;
14441
+ break;
14442
+ }
14443
+ case "tool": {
14444
+ throw new UnsupportedFunctionalityError({
14445
+ functionality: "tool messages"
14446
+ });
14447
+ }
14448
+ default: {
14449
+ const _exhaustiveCheck = role;
14450
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
14451
+ }
14452
+ }
14453
+ }
14454
+ text += `${assistant}:
14455
+ `;
14456
+ return {
14457
+ prompt: text
14458
+ };
14459
+ }
14460
+
14461
+ // src/map-openrouter-completion-logprobs.ts
14462
+ function mapOpenRouterCompletionLogProbs(logprobs) {
14463
+ return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => {
14464
+ var _a, _b;
14465
+ return {
14466
+ token,
14467
+ logprob: (_a = logprobs.token_logprobs[index]) != null ? _a : 0,
14468
+ topLogprobs: logprobs.top_logprobs ? Object.entries((_b = logprobs.top_logprobs[index]) != null ? _b : {}).map(
14469
+ ([token2, logprob]) => ({
14470
+ token: token2,
14471
+ logprob
14472
+ })
14473
+ ) : []
14474
+ };
14475
+ });
14476
+ }
14477
+
14478
+ // src/openrouter-completion-language-model.ts
14479
+ var OpenRouterCompletionLanguageModel = class {
14480
+ constructor(modelId, settings, config) {
14481
+ this.specificationVersion = "v1";
14482
+ this.defaultObjectGenerationMode = void 0;
14483
+ this.modelId = modelId;
14484
+ this.settings = settings;
14485
+ this.config = config;
14486
+ }
14487
+ get provider() {
14488
+ return this.config.provider;
14489
+ }
14490
+ getArgs({
14491
+ mode,
14492
+ inputFormat,
14493
+ prompt,
14494
+ maxTokens,
14495
+ temperature,
14496
+ topP,
14497
+ frequencyPenalty,
14498
+ presencePenalty,
14499
+ seed,
14500
+ responseFormat,
14501
+ topK,
14502
+ stopSequences,
14503
+ providerMetadata
14504
+ }) {
14505
+ var _a, _b;
14506
+ const type = mode.type;
14507
+ const extraCallingBody = (_a = providerMetadata == null ? void 0 : providerMetadata["openrouter"]) != null ? _a : {};
14508
+ const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
14509
+ prompt,
14510
+ inputFormat
14511
+ });
14512
+ const baseArgs = __spreadValues(__spreadValues(__spreadValues({
14513
+ // model id:
14514
+ model: this.modelId,
14515
+ models: this.settings.models,
14516
+ // model specific settings:
14517
+ logit_bias: this.settings.logitBias,
14518
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
14519
+ suffix: this.settings.suffix,
14520
+ user: this.settings.user,
14521
+ // standardized settings:
14522
+ max_tokens: maxTokens,
14523
+ temperature,
14524
+ top_p: topP,
14525
+ frequency_penalty: frequencyPenalty,
14526
+ presence_penalty: presencePenalty,
14527
+ seed,
14528
+ stop: stopSequences,
14529
+ response_format: responseFormat,
14530
+ top_k: topK,
14531
+ // prompt:
14532
+ prompt: completionPrompt,
14533
+ // OpenRouter specific settings:
14534
+ include_reasoning: this.settings.includeReasoning,
14535
+ reasoning: this.settings.reasoning
14536
+ }, this.config.extraBody), this.settings.extraBody), extraCallingBody);
14537
+ switch (type) {
14538
+ case "regular": {
14539
+ if ((_b = mode.tools) == null ? void 0 : _b.length) {
14540
+ throw new UnsupportedFunctionalityError({
14541
+ functionality: "tools"
14542
+ });
14543
+ }
14544
+ if (mode.toolChoice) {
14545
+ throw new UnsupportedFunctionalityError({
14546
+ functionality: "toolChoice"
14547
+ });
14548
+ }
14549
+ return baseArgs;
14550
+ }
14551
+ case "object-json": {
14552
+ throw new UnsupportedFunctionalityError({
14553
+ functionality: "object-json mode"
14554
+ });
14555
+ }
14556
+ case "object-tool": {
14557
+ throw new UnsupportedFunctionalityError({
14558
+ functionality: "object-tool mode"
14559
+ });
14560
+ }
14561
+ // Handle all non-text types with a single default case
14562
+ default: {
14563
+ const _exhaustiveCheck = type;
14564
+ throw new UnsupportedFunctionalityError({
14565
+ functionality: `${_exhaustiveCheck} mode`
14566
+ });
14567
+ }
14568
+ }
14569
+ }
14570
+ async doGenerate(options) {
14571
+ var _b, _c, _d, _e, _f;
14572
+ const args = this.getArgs(options);
14573
+ const { responseHeaders, value: response } = await postJsonToApi({
14574
+ url: this.config.url({
14575
+ path: "/completions",
14576
+ modelId: this.modelId
14577
+ }),
14578
+ headers: combineHeaders(this.config.headers(), options.headers),
14579
+ body: args,
14580
+ failedResponseHandler: openrouterFailedResponseHandler,
14581
+ successfulResponseHandler: createJsonResponseHandler(
14582
+ OpenRouterCompletionChunkSchema
14583
+ ),
14584
+ abortSignal: options.abortSignal,
14585
+ fetch: this.config.fetch
14586
+ });
14587
+ const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
14588
+ if ("error" in response) {
14589
+ throw new Error(`${response.error.message}`);
14590
+ }
14591
+ const choice = response.choices[0];
14592
+ if (!choice) {
14593
+ throw new Error("No choice in OpenRouter completion response");
14594
+ }
14595
+ return {
14596
+ response: {
14597
+ id: response.id,
14598
+ modelId: response.model
14599
+ },
14600
+ text: (_b = choice.text) != null ? _b : "",
14601
+ reasoning: choice.reasoning || void 0,
14602
+ usage: {
14603
+ promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : 0,
14604
+ completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : 0
14605
+ },
14606
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
14607
+ logprobs: mapOpenRouterCompletionLogProbs(choice.logprobs),
14608
+ rawCall: { rawPrompt, rawSettings },
14609
+ rawResponse: { headers: responseHeaders },
14610
+ warnings: []
14611
+ };
14612
+ }
14613
+ async doStream(options) {
14614
+ const args = this.getArgs(options);
14615
+ const { responseHeaders, value: response } = await postJsonToApi({
14616
+ url: this.config.url({
14617
+ path: "/completions",
14618
+ modelId: this.modelId
14619
+ }),
14620
+ headers: combineHeaders(this.config.headers(), options.headers),
14621
+ body: __spreadProps(__spreadValues({}, this.getArgs(options)), {
14622
+ stream: true,
14623
+ // only include stream_options when in strict compatibility mode:
14624
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
14625
+ }),
14626
+ failedResponseHandler: openrouterFailedResponseHandler,
14627
+ successfulResponseHandler: createEventSourceResponseHandler(
14628
+ OpenRouterCompletionChunkSchema
14629
+ ),
14630
+ abortSignal: options.abortSignal,
14631
+ fetch: this.config.fetch
14632
+ });
14633
+ const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
14634
+ let finishReason = "other";
14635
+ let usage = {
14636
+ promptTokens: Number.NaN,
14637
+ completionTokens: Number.NaN
14638
+ };
14639
+ let logprobs;
14640
+ return {
14641
+ stream: response.pipeThrough(
14642
+ new TransformStream({
14643
+ transform(chunk, controller) {
14644
+ if (!chunk.success) {
14645
+ finishReason = "error";
14646
+ controller.enqueue({ type: "error", error: chunk.error });
14647
+ return;
14648
+ }
14649
+ const value = chunk.value;
14650
+ if ("error" in value) {
14651
+ finishReason = "error";
14652
+ controller.enqueue({ type: "error", error: value.error });
14653
+ return;
14654
+ }
14655
+ if (value.usage != null) {
14656
+ usage = {
14657
+ promptTokens: value.usage.prompt_tokens,
14658
+ completionTokens: value.usage.completion_tokens
14659
+ };
14660
+ }
14661
+ const choice = value.choices[0];
14662
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
14663
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
14664
+ }
14665
+ if ((choice == null ? void 0 : choice.text) != null) {
14666
+ controller.enqueue({
14667
+ type: "text-delta",
14668
+ textDelta: choice.text
14669
+ });
14670
+ }
14671
+ const mappedLogprobs = mapOpenRouterCompletionLogProbs(
14672
+ choice == null ? void 0 : choice.logprobs
14673
+ );
14674
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
14675
+ if (logprobs === void 0) logprobs = [];
14676
+ logprobs.push(...mappedLogprobs);
14677
+ }
14678
+ },
14679
+ flush(controller) {
14680
+ controller.enqueue({
14681
+ type: "finish",
14682
+ finishReason,
14683
+ logprobs,
14684
+ usage
14685
+ });
14686
+ }
14687
+ })
14688
+ ),
14689
+ rawCall: { rawPrompt, rawSettings },
14690
+ rawResponse: { headers: responseHeaders },
14691
+ warnings: []
14692
+ };
14693
+ }
14694
+ };
14695
+ var OpenRouterCompletionChunkSchema = z.union([
14696
+ z.object({
14697
+ id: z.string().optional(),
14698
+ model: z.string().optional(),
14699
+ choices: z.array(
14700
+ z.object({
14701
+ text: z.string(),
14702
+ reasoning: z.string().nullish().optional(),
14703
+ finish_reason: z.string().nullish(),
14704
+ index: z.number(),
14705
+ logprobs: z.object({
14706
+ tokens: z.array(z.string()),
14707
+ token_logprobs: z.array(z.number()),
14708
+ top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
14709
+ }).nullable().optional()
14710
+ })
14711
+ ),
14712
+ usage: z.object({
14713
+ prompt_tokens: z.number(),
14714
+ completion_tokens: z.number()
14715
+ }).optional().nullable()
14716
+ }),
14717
+ OpenRouterErrorResponseSchema
14718
+ ]);
14719
+ function createOpenRouter(options = {}) {
14720
+ var _a, _b, _c;
14721
+ const baseURL = (_b = withoutTrailingSlash((_a = options.baseURL) != null ? _a : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
14722
+ const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
14723
+ const getHeaders = () => __spreadValues({
14724
+ Authorization: `Bearer ${loadApiKey({
14725
+ apiKey: options.apiKey,
14726
+ environmentVariableName: "OPENROUTER_API_KEY",
14727
+ description: "OpenRouter"
14728
+ })}`
14729
+ }, options.headers);
14730
+ const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
14731
+ provider: "openrouter.chat",
14732
+ url: ({ path }) => `${baseURL}${path}`,
14733
+ headers: getHeaders,
14734
+ compatibility,
14735
+ fetch: options.fetch,
14736
+ extraBody: options.extraBody
14737
+ });
14738
+ const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
14739
+ provider: "openrouter.completion",
14740
+ url: ({ path }) => `${baseURL}${path}`,
14741
+ headers: getHeaders,
14742
+ compatibility,
14743
+ fetch: options.fetch,
14744
+ extraBody: options.extraBody
14745
+ });
14746
+ const createLanguageModel = (modelId, settings) => {
14747
+ if (new.target) {
14748
+ throw new Error(
14749
+ "The OpenRouter model function cannot be called with the new keyword."
14750
+ );
14751
+ }
14752
+ if (modelId === "openai/gpt-3.5-turbo-instruct") {
14753
+ return createCompletionModel(
14754
+ modelId,
14755
+ settings
14756
+ );
14757
+ }
14758
+ return createChatModel(modelId, settings);
14759
+ };
14760
+ const provider = function(modelId, settings) {
14761
+ return createLanguageModel(modelId, settings);
14762
+ };
14763
+ provider.languageModel = createLanguageModel;
14764
+ provider.chat = createChatModel;
14765
+ provider.completion = createCompletionModel;
14766
+ return provider;
14767
+ }
14768
+ createOpenRouter({
14769
+ compatibility: "strict"
14770
+ // strict for OpenRouter API
14771
+ });
14772
+
14773
+ class RetryLanguageModel {
14774
+ constructor(llms, names, stream_first_timeout) {
14775
+ this.llms = llms;
14776
+ this.names = names || [];
14777
+ this.stream_first_timeout = stream_first_timeout || 30000;
14778
+ if (this.names.indexOf("default") == -1) {
14779
+ this.names.push("default");
14780
+ }
14781
+ }
14782
+ async call(request) {
14783
+ return await this.doGenerate({
14784
+ inputFormat: "messages",
14785
+ mode: {
14786
+ type: "regular",
14787
+ tools: request.tools,
14788
+ toolChoice: request.toolChoice,
14789
+ },
14790
+ prompt: request.messages,
14791
+ maxTokens: request.maxTokens || config.maxTokens,
14792
+ temperature: request.temperature,
14793
+ topP: request.topP,
14794
+ topK: request.topK,
14795
+ providerMetadata: {},
12760
14796
  abortSignal: request.abortSignal,
12761
14797
  });
12762
14798
  }
@@ -12871,7 +14907,7 @@ class RetryLanguageModel {
12871
14907
  baseURL: llm.config?.baseURL,
12872
14908
  }).languageModel(llm.model, {
12873
14909
  // disable_parallel_tool_use
12874
- parallelToolCalls: false,
14910
+ parallelToolCalls: llm.config?.parallelToolCalls || false,
12875
14911
  });
12876
14912
  }
12877
14913
  else if (llm.provider == "anthropic") {
@@ -12889,10 +14925,16 @@ class RetryLanguageModel {
12889
14925
  else if (llm.provider == "aws") {
12890
14926
  let keys = llm.apiKey.split("=");
12891
14927
  return createAmazonBedrock({
12892
- region: llm.config?.region || "us-east-2",
12893
- baseURL: llm.config?.baseURL,
12894
14928
  accessKeyId: keys[0],
12895
14929
  secretAccessKey: keys[1],
14930
+ baseURL: llm.config?.baseURL,
14931
+ region: llm.config?.region || "us-east-1",
14932
+ }).languageModel(llm.model);
14933
+ }
14934
+ else if (llm.provider == "openrouter") {
14935
+ return createOpenRouter({
14936
+ apiKey: llm.apiKey,
14937
+ baseURL: llm.config?.baseURL,
12896
14938
  }).languageModel(llm.model);
12897
14939
  }
12898
14940
  else {