@apertis/ai-sdk-provider 2.0.0 → 2.1.0

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.cjs CHANGED
@@ -6,8 +6,8 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __export = (target, all) => {
9
- for (var name15 in all)
10
- __defProp(target, name15, { get: all[name15], enumerable: true });
9
+ for (var name14 in all)
10
+ __defProp(target, name14, { get: all[name14], enumerable: true });
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
@@ -31,12 +31,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  apertis: () => apertis,
34
- createApertis: () => createApertis,
35
- createApertisV3: () => createApertisV3
34
+ createApertis: () => createApertis
36
35
  });
37
36
  module.exports = __toCommonJS(index_exports);
38
37
 
39
- // node_modules/.pnpm/@ai-sdk+provider@3.0.4/node_modules/@ai-sdk/provider/dist/index.mjs
38
+ // node_modules/.pnpm/@ai-sdk+provider@2.0.1/node_modules/@ai-sdk/provider/dist/index.mjs
40
39
  var marker = "vercel.ai.error";
41
40
  var symbol = Symbol.for(marker);
42
41
  var _a;
@@ -51,13 +50,13 @@ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
51
50
  * @param {unknown} [params.cause] - The underlying cause of the error.
52
51
  */
53
52
  constructor({
54
- name: name142,
53
+ name: name14,
55
54
  message,
56
55
  cause
57
56
  }) {
58
57
  super(message);
59
58
  this[_a] = true;
60
- this.name = name142;
59
+ this.name = name14;
61
60
  this.cause = cause;
62
61
  }
63
62
  /**
@@ -68,8 +67,8 @@ var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
68
67
  static isInstance(error) {
69
68
  return _AISDKError.hasMarker(error, marker);
70
69
  }
71
- static hasMarker(error, marker152) {
72
- const markerSymbol = Symbol.for(marker152);
70
+ static hasMarker(error, marker15) {
71
+ const markerSymbol = Symbol.for(marker15);
73
72
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
74
73
  }
75
74
  };
@@ -355,12 +354,6 @@ var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = sym
355
354
  }
356
355
  };
357
356
 
358
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.8_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
359
- var z4 = __toESM(require("zod/v4"), 1);
360
- var import_v3 = require("zod/v3");
361
- var import_v32 = require("zod/v3");
362
- var import_v33 = require("zod/v3");
363
-
364
357
  // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
365
358
  var ParseError = class extends Error {
366
359
  constructor(message, options) {
@@ -488,34 +481,23 @@ var EventSourceParserStream = class extends TransformStream {
488
481
  }
489
482
  };
490
483
 
491
- // node_modules/.pnpm/@ai-sdk+provider-utils@4.0.8_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
484
+ // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.20_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
485
+ var z4 = __toESM(require("zod/v4"), 1);
486
+ var import_v3 = require("zod/v3");
487
+ var import_v32 = require("zod/v3");
488
+ var import_v33 = require("zod/v3");
489
+ function combineHeaders(...headers) {
490
+ return headers.reduce(
491
+ (combinedHeaders, currentHeaders) => ({
492
+ ...combinedHeaders,
493
+ ...currentHeaders != null ? currentHeaders : {}
494
+ }),
495
+ {}
496
+ );
497
+ }
492
498
  function extractResponseHeaders(response) {
493
499
  return Object.fromEntries([...response.headers]);
494
500
  }
495
- var { btoa, atob } = globalThis;
496
- var name14 = "AI_DownloadError";
497
- var marker15 = `vercel.ai.error.${name14}`;
498
- var symbol15 = Symbol.for(marker15);
499
- var _a15;
500
- var _b15;
501
- var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
502
- constructor({
503
- url,
504
- statusCode,
505
- statusText,
506
- cause,
507
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
508
- }) {
509
- super({ name: name14, message, cause });
510
- this[_a15] = true;
511
- this.url = url;
512
- this.statusCode = statusCode;
513
- this.statusText = statusText;
514
- }
515
- static isInstance(error) {
516
- return AISDKError.hasMarker(error, marker15);
517
- }
518
- };
519
501
  var createIdGenerator = ({
520
502
  prefix,
521
503
  size = 16,
@@ -571,14 +553,14 @@ function handleFetchError({
571
553
  return error;
572
554
  }
573
555
  function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
574
- var _a22, _b22, _c;
556
+ var _a15, _b15, _c;
575
557
  if (globalThisAny.window) {
576
558
  return `runtime/browser`;
577
559
  }
578
- if ((_a22 = globalThisAny.navigator) == null ? void 0 : _a22.userAgent) {
560
+ if ((_a15 = globalThisAny.navigator) == null ? void 0 : _a15.userAgent) {
579
561
  return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
580
562
  }
581
- if ((_c = (_b22 = globalThisAny.process) == null ? void 0 : _b22.versions) == null ? void 0 : _c.node) {
563
+ if ((_c = (_b15 = globalThisAny.process) == null ? void 0 : _b15.versions) == null ? void 0 : _c.node) {
582
564
  return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
583
565
  }
584
566
  if (globalThisAny.EdgeRuntime) {
@@ -616,39 +598,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
616
598
  );
617
599
  return Object.fromEntries(normalizedHeaders.entries());
618
600
  }
619
- var VERSION = true ? "4.0.8" : "0.0.0-test";
620
- function loadApiKey({
621
- apiKey,
622
- environmentVariableName,
623
- apiKeyParameterName = "apiKey",
624
- description
625
- }) {
626
- if (typeof apiKey === "string") {
627
- return apiKey;
628
- }
629
- if (apiKey != null) {
630
- throw new LoadAPIKeyError({
631
- message: `${description} API key must be a string.`
632
- });
633
- }
634
- if (typeof process === "undefined") {
635
- throw new LoadAPIKeyError({
636
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
637
- });
638
- }
639
- apiKey = process.env[environmentVariableName];
640
- if (apiKey == null) {
641
- throw new LoadAPIKeyError({
642
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
643
- });
644
- }
645
- if (typeof apiKey !== "string") {
646
- throw new LoadAPIKeyError({
647
- message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
648
- });
649
- }
650
- return apiKey;
651
- }
601
+ var VERSION = true ? "3.0.20" : "0.0.0-test";
652
602
  var suspectProtoRx = /"__proto__"\s*:/;
653
603
  var suspectConstructorRx = /"constructor"\s*:/;
654
604
  function _parse(text) {
@@ -696,1314 +646,142 @@ function secureJsonParse(text) {
696
646
  Error.stackTraceLimit = stackTraceLimit;
697
647
  }
698
648
  }
699
- function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
700
- if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
701
- jsonSchema2.additionalProperties = false;
702
- const { properties } = jsonSchema2;
703
- if (properties != null) {
704
- for (const key of Object.keys(properties)) {
705
- properties[key] = visit(properties[key]);
706
- }
707
- }
708
- }
709
- if (jsonSchema2.items != null) {
710
- jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
711
- }
712
- if (jsonSchema2.anyOf != null) {
713
- jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
714
- }
715
- if (jsonSchema2.allOf != null) {
716
- jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
717
- }
718
- if (jsonSchema2.oneOf != null) {
719
- jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
720
- }
721
- const { definitions } = jsonSchema2;
722
- if (definitions != null) {
723
- for (const key of Object.keys(definitions)) {
724
- definitions[key] = visit(definitions[key]);
725
- }
726
- }
727
- return jsonSchema2;
649
+ var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
650
+ function validator(validate) {
651
+ return { [validatorSymbol]: true, validate };
728
652
  }
729
- function visit(def) {
730
- if (typeof def === "boolean") return def;
731
- return addAdditionalPropertiesToJsonSchema(def);
653
+ function isValidator(value) {
654
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
732
655
  }
733
- var ignoreOverride = /* @__PURE__ */ Symbol(
734
- "Let zodToJsonSchema decide on which parser to use"
735
- );
736
- var defaultOptions = {
737
- name: void 0,
738
- $refStrategy: "root",
739
- basePath: ["#"],
740
- effectStrategy: "input",
741
- pipeStrategy: "all",
742
- dateStrategy: "format:date-time",
743
- mapStrategy: "entries",
744
- removeAdditionalStrategy: "passthrough",
745
- allowedAdditionalProperties: true,
746
- rejectedAdditionalProperties: false,
747
- definitionPath: "definitions",
748
- strictUnions: false,
749
- definitions: {},
750
- errorMessages: false,
751
- patternStrategy: "escape",
752
- applyRegexFlags: false,
753
- emailStrategy: "format:email",
754
- base64Strategy: "contentEncoding:base64",
755
- nameStrategy: "ref"
756
- };
757
- var getDefaultOptions = (options) => typeof options === "string" ? {
758
- ...defaultOptions,
759
- name: options
760
- } : {
761
- ...defaultOptions,
762
- ...options
763
- };
764
- function parseAnyDef() {
765
- return {};
656
+ function asValidator(value) {
657
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
766
658
  }
767
- function parseArrayDef(def, refs) {
768
- var _a22, _b22, _c;
769
- const res = {
770
- type: "array"
771
- };
772
- if (((_a22 = def.type) == null ? void 0 : _a22._def) && ((_c = (_b22 = def.type) == null ? void 0 : _b22._def) == null ? void 0 : _c.typeName) !== import_v32.ZodFirstPartyTypeKind.ZodAny) {
773
- res.items = parseDef(def.type._def, {
774
- ...refs,
775
- currentPath: [...refs.currentPath, "items"]
776
- });
777
- }
778
- if (def.minLength) {
779
- res.minItems = def.minLength.value;
780
- }
781
- if (def.maxLength) {
782
- res.maxItems = def.maxLength.value;
783
- }
784
- if (def.exactLength) {
785
- res.minItems = def.exactLength.value;
786
- res.maxItems = def.exactLength.value;
787
- }
788
- return res;
659
+ function standardSchemaValidator(standardSchema) {
660
+ return validator(async (value) => {
661
+ const result = await standardSchema["~standard"].validate(value);
662
+ return result.issues == null ? { success: true, value: result.value } : {
663
+ success: false,
664
+ error: new TypeValidationError({
665
+ value,
666
+ cause: result.issues
667
+ })
668
+ };
669
+ });
789
670
  }
790
- function parseBigintDef(def) {
791
- const res = {
792
- type: "integer",
793
- format: "int64"
794
- };
795
- if (!def.checks) return res;
796
- for (const check of def.checks) {
797
- switch (check.kind) {
798
- case "min":
799
- if (check.inclusive) {
800
- res.minimum = check.value;
801
- } else {
802
- res.exclusiveMinimum = check.value;
803
- }
804
- break;
805
- case "max":
806
- if (check.inclusive) {
807
- res.maximum = check.value;
808
- } else {
809
- res.exclusiveMaximum = check.value;
810
- }
811
- break;
812
- case "multipleOf":
813
- res.multipleOf = check.value;
814
- break;
815
- }
671
+ async function validateTypes({
672
+ value,
673
+ schema
674
+ }) {
675
+ const result = await safeValidateTypes({ value, schema });
676
+ if (!result.success) {
677
+ throw TypeValidationError.wrap({ value, cause: result.error });
816
678
  }
817
- return res;
818
- }
819
- function parseBooleanDef() {
820
- return { type: "boolean" };
821
- }
822
- function parseBrandedDef(_def, refs) {
823
- return parseDef(_def.type._def, refs);
679
+ return result.value;
824
680
  }
825
- var parseCatchDef = (def, refs) => {
826
- return parseDef(def.innerType._def, refs);
827
- };
828
- function parseDateDef(def, refs, overrideDateStrategy) {
829
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
830
- if (Array.isArray(strategy)) {
681
+ async function safeValidateTypes({
682
+ value,
683
+ schema
684
+ }) {
685
+ const validator2 = asValidator(schema);
686
+ try {
687
+ if (validator2.validate == null) {
688
+ return { success: true, value, rawValue: value };
689
+ }
690
+ const result = await validator2.validate(value);
691
+ if (result.success) {
692
+ return { success: true, value: result.value, rawValue: value };
693
+ }
831
694
  return {
832
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
695
+ success: false,
696
+ error: TypeValidationError.wrap({ value, cause: result.error }),
697
+ rawValue: value
698
+ };
699
+ } catch (error) {
700
+ return {
701
+ success: false,
702
+ error: TypeValidationError.wrap({ value, cause: error }),
703
+ rawValue: value
833
704
  };
834
- }
835
- switch (strategy) {
836
- case "string":
837
- case "format:date-time":
838
- return {
839
- type: "string",
840
- format: "date-time"
841
- };
842
- case "format:date":
843
- return {
844
- type: "string",
845
- format: "date"
846
- };
847
- case "integer":
848
- return integerDateParser(def);
849
705
  }
850
706
  }
851
- var integerDateParser = (def) => {
852
- const res = {
853
- type: "integer",
854
- format: "unix-time"
855
- };
856
- for (const check of def.checks) {
857
- switch (check.kind) {
858
- case "min":
859
- res.minimum = check.value;
860
- break;
861
- case "max":
862
- res.maximum = check.value;
863
- break;
707
+ async function parseJSON({
708
+ text,
709
+ schema
710
+ }) {
711
+ try {
712
+ const value = secureJsonParse(text);
713
+ if (schema == null) {
714
+ return value;
715
+ }
716
+ return validateTypes({ value, schema });
717
+ } catch (error) {
718
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
719
+ throw error;
864
720
  }
721
+ throw new JSONParseError({ text, cause: error });
865
722
  }
866
- return res;
867
- };
868
- function parseDefaultDef(_def, refs) {
869
- return {
870
- ...parseDef(_def.innerType._def, refs),
871
- default: _def.defaultValue()
872
- };
873
723
  }
874
- function parseEffectsDef(_def, refs) {
875
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
876
- }
877
- function parseEnumDef(def) {
878
- return {
879
- type: "string",
880
- enum: Array.from(def.values)
881
- };
882
- }
883
- var isJsonSchema7AllOfType = (type) => {
884
- if ("type" in type && type.type === "string") return false;
885
- return "allOf" in type;
886
- };
887
- function parseIntersectionDef(def, refs) {
888
- const allOf = [
889
- parseDef(def.left._def, {
890
- ...refs,
891
- currentPath: [...refs.currentPath, "allOf", "0"]
892
- }),
893
- parseDef(def.right._def, {
894
- ...refs,
895
- currentPath: [...refs.currentPath, "allOf", "1"]
896
- })
897
- ].filter((x) => !!x);
898
- const mergedAllOf = [];
899
- allOf.forEach((schema) => {
900
- if (isJsonSchema7AllOfType(schema)) {
901
- mergedAllOf.push(...schema.allOf);
902
- } else {
903
- let nestedSchema = schema;
904
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
905
- const { additionalProperties, ...rest } = schema;
906
- nestedSchema = rest;
907
- }
908
- mergedAllOf.push(nestedSchema);
724
+ async function safeParseJSON({
725
+ text,
726
+ schema
727
+ }) {
728
+ try {
729
+ const value = secureJsonParse(text);
730
+ if (schema == null) {
731
+ return { success: true, value, rawValue: value };
909
732
  }
910
- });
911
- return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
912
- }
913
- function parseLiteralDef(def) {
914
- const parsedType = typeof def.value;
915
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
733
+ return await safeValidateTypes({ value, schema });
734
+ } catch (error) {
916
735
  return {
917
- type: Array.isArray(def.value) ? "array" : "object"
736
+ success: false,
737
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
738
+ rawValue: void 0
918
739
  };
919
740
  }
920
- return {
921
- type: parsedType === "bigint" ? "integer" : parsedType,
922
- const: def.value
923
- };
924
741
  }
925
- var emojiRegex = void 0;
926
- var zodPatterns = {
927
- /**
928
- * `c` was changed to `[cC]` to replicate /i flag
929
- */
930
- cuid: /^[cC][^\s-]{8,}$/,
931
- cuid2: /^[0-9a-z]+$/,
932
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
933
- /**
934
- * `a-z` was added to replicate /i flag
935
- */
936
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
937
- /**
938
- * Constructed a valid Unicode RegExp
939
- *
940
- * Lazily instantiate since this type of regex isn't supported
941
- * in all envs (e.g. React Native).
942
- *
943
- * See:
944
- * https://github.com/colinhacks/zod/issues/2433
945
- * Fix in Zod:
946
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
947
- */
948
- emoji: () => {
949
- if (emojiRegex === void 0) {
950
- emojiRegex = RegExp(
951
- "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
952
- "u"
953
- );
954
- }
955
- return emojiRegex;
956
- },
957
- /**
958
- * Unused
959
- */
960
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
961
- /**
962
- * Unused
963
- */
964
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
965
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
966
- /**
967
- * Unused
968
- */
969
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
970
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
971
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
972
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
973
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
974
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
975
- };
976
- function parseStringDef(def, refs) {
977
- const res = {
978
- type: "string"
979
- };
980
- if (def.checks) {
981
- for (const check of def.checks) {
982
- switch (check.kind) {
983
- case "min":
984
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
985
- break;
986
- case "max":
987
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
988
- break;
989
- case "email":
990
- switch (refs.emailStrategy) {
991
- case "format:email":
992
- addFormat(res, "email", check.message, refs);
993
- break;
994
- case "format:idn-email":
995
- addFormat(res, "idn-email", check.message, refs);
996
- break;
997
- case "pattern:zod":
998
- addPattern(res, zodPatterns.email, check.message, refs);
999
- break;
1000
- }
1001
- break;
1002
- case "url":
1003
- addFormat(res, "uri", check.message, refs);
1004
- break;
1005
- case "uuid":
1006
- addFormat(res, "uuid", check.message, refs);
1007
- break;
1008
- case "regex":
1009
- addPattern(res, check.regex, check.message, refs);
1010
- break;
1011
- case "cuid":
1012
- addPattern(res, zodPatterns.cuid, check.message, refs);
1013
- break;
1014
- case "cuid2":
1015
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1016
- break;
1017
- case "startsWith":
1018
- addPattern(
1019
- res,
1020
- RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1021
- check.message,
1022
- refs
1023
- );
1024
- break;
1025
- case "endsWith":
1026
- addPattern(
1027
- res,
1028
- RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1029
- check.message,
1030
- refs
1031
- );
1032
- break;
1033
- case "datetime":
1034
- addFormat(res, "date-time", check.message, refs);
1035
- break;
1036
- case "date":
1037
- addFormat(res, "date", check.message, refs);
1038
- break;
1039
- case "time":
1040
- addFormat(res, "time", check.message, refs);
1041
- break;
1042
- case "duration":
1043
- addFormat(res, "duration", check.message, refs);
1044
- break;
1045
- case "length":
1046
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1047
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1048
- break;
1049
- case "includes": {
1050
- addPattern(
1051
- res,
1052
- RegExp(escapeLiteralCheckValue(check.value, refs)),
1053
- check.message,
1054
- refs
1055
- );
1056
- break;
1057
- }
1058
- case "ip": {
1059
- if (check.version !== "v6") {
1060
- addFormat(res, "ipv4", check.message, refs);
1061
- }
1062
- if (check.version !== "v4") {
1063
- addFormat(res, "ipv6", check.message, refs);
1064
- }
1065
- break;
1066
- }
1067
- case "base64url":
1068
- addPattern(res, zodPatterns.base64url, check.message, refs);
1069
- break;
1070
- case "jwt":
1071
- addPattern(res, zodPatterns.jwt, check.message, refs);
1072
- break;
1073
- case "cidr": {
1074
- if (check.version !== "v6") {
1075
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1076
- }
1077
- if (check.version !== "v4") {
1078
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1079
- }
1080
- break;
1081
- }
1082
- case "emoji":
1083
- addPattern(res, zodPatterns.emoji(), check.message, refs);
1084
- break;
1085
- case "ulid": {
1086
- addPattern(res, zodPatterns.ulid, check.message, refs);
1087
- break;
1088
- }
1089
- case "base64": {
1090
- switch (refs.base64Strategy) {
1091
- case "format:binary": {
1092
- addFormat(res, "binary", check.message, refs);
1093
- break;
1094
- }
1095
- case "contentEncoding:base64": {
1096
- res.contentEncoding = "base64";
1097
- break;
1098
- }
1099
- case "pattern:zod": {
1100
- addPattern(res, zodPatterns.base64, check.message, refs);
1101
- break;
1102
- }
1103
- }
1104
- break;
1105
- }
1106
- case "nanoid": {
1107
- addPattern(res, zodPatterns.nanoid, check.message, refs);
1108
- }
1109
- case "toLowerCase":
1110
- case "toUpperCase":
1111
- case "trim":
1112
- break;
1113
- default:
1114
- /* @__PURE__ */ ((_) => {
1115
- })(check);
1116
- }
1117
- }
742
+ function isParsableJson(input) {
743
+ try {
744
+ secureJsonParse(input);
745
+ return true;
746
+ } catch (e) {
747
+ return false;
1118
748
  }
1119
- return res;
1120
749
  }
1121
- function escapeLiteralCheckValue(literal, refs) {
1122
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1123
- }
1124
- var ALPHA_NUMERIC = new Set(
1125
- "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1126
- );
1127
- function escapeNonAlphaNumeric(source) {
1128
- let result = "";
1129
- for (let i = 0; i < source.length; i++) {
1130
- if (!ALPHA_NUMERIC.has(source[i])) {
1131
- result += "\\";
1132
- }
1133
- result += source[i];
1134
- }
1135
- return result;
750
+ function parseJsonEventStream({
751
+ stream,
752
+ schema
753
+ }) {
754
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
755
+ new TransformStream({
756
+ async transform({ data }, controller) {
757
+ if (data === "[DONE]") {
758
+ return;
759
+ }
760
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
761
+ }
762
+ })
763
+ );
1136
764
  }
1137
- function addFormat(schema, value, message, refs) {
1138
- var _a22;
1139
- if (schema.format || ((_a22 = schema.anyOf) == null ? void 0 : _a22.some((x) => x.format))) {
1140
- if (!schema.anyOf) {
1141
- schema.anyOf = [];
1142
- }
1143
- if (schema.format) {
1144
- schema.anyOf.push({
1145
- format: schema.format
1146
- });
1147
- delete schema.format;
1148
- }
1149
- schema.anyOf.push({
1150
- format: value,
1151
- ...message && refs.errorMessages && { errorMessage: { format: message } }
1152
- });
1153
- } else {
1154
- schema.format = value;
765
+ async function parseProviderOptions({
766
+ provider,
767
+ providerOptions,
768
+ schema
769
+ }) {
770
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
771
+ return void 0;
1155
772
  }
1156
- }
1157
- function addPattern(schema, regex, message, refs) {
1158
- var _a22;
1159
- if (schema.pattern || ((_a22 = schema.allOf) == null ? void 0 : _a22.some((x) => x.pattern))) {
1160
- if (!schema.allOf) {
1161
- schema.allOf = [];
1162
- }
1163
- if (schema.pattern) {
1164
- schema.allOf.push({
1165
- pattern: schema.pattern
1166
- });
1167
- delete schema.pattern;
1168
- }
1169
- schema.allOf.push({
1170
- pattern: stringifyRegExpWithFlags(regex, refs),
1171
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
773
+ const parsedProviderOptions = await safeValidateTypes({
774
+ value: providerOptions[provider],
775
+ schema
776
+ });
777
+ if (!parsedProviderOptions.success) {
778
+ throw new InvalidArgumentError({
779
+ argument: "providerOptions",
780
+ message: `invalid ${provider} provider options`,
781
+ cause: parsedProviderOptions.error
1172
782
  });
1173
- } else {
1174
- schema.pattern = stringifyRegExpWithFlags(regex, refs);
1175
783
  }
1176
- }
1177
- function stringifyRegExpWithFlags(regex, refs) {
1178
- var _a22;
1179
- if (!refs.applyRegexFlags || !regex.flags) {
1180
- return regex.source;
1181
- }
1182
- const flags = {
1183
- i: regex.flags.includes("i"),
1184
- // Case-insensitive
1185
- m: regex.flags.includes("m"),
1186
- // `^` and `$` matches adjacent to newline characters
1187
- s: regex.flags.includes("s")
1188
- // `.` matches newlines
1189
- };
1190
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
1191
- let pattern = "";
1192
- let isEscaped = false;
1193
- let inCharGroup = false;
1194
- let inCharRange = false;
1195
- for (let i = 0; i < source.length; i++) {
1196
- if (isEscaped) {
1197
- pattern += source[i];
1198
- isEscaped = false;
1199
- continue;
1200
- }
1201
- if (flags.i) {
1202
- if (inCharGroup) {
1203
- if (source[i].match(/[a-z]/)) {
1204
- if (inCharRange) {
1205
- pattern += source[i];
1206
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1207
- inCharRange = false;
1208
- } else if (source[i + 1] === "-" && ((_a22 = source[i + 2]) == null ? void 0 : _a22.match(/[a-z]/))) {
1209
- pattern += source[i];
1210
- inCharRange = true;
1211
- } else {
1212
- pattern += `${source[i]}${source[i].toUpperCase()}`;
1213
- }
1214
- continue;
1215
- }
1216
- } else if (source[i].match(/[a-z]/)) {
1217
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1218
- continue;
1219
- }
1220
- }
1221
- if (flags.m) {
1222
- if (source[i] === "^") {
1223
- pattern += `(^|(?<=[\r
1224
- ]))`;
1225
- continue;
1226
- } else if (source[i] === "$") {
1227
- pattern += `($|(?=[\r
1228
- ]))`;
1229
- continue;
1230
- }
1231
- }
1232
- if (flags.s && source[i] === ".") {
1233
- pattern += inCharGroup ? `${source[i]}\r
1234
- ` : `[${source[i]}\r
1235
- ]`;
1236
- continue;
1237
- }
1238
- pattern += source[i];
1239
- if (source[i] === "\\") {
1240
- isEscaped = true;
1241
- } else if (inCharGroup && source[i] === "]") {
1242
- inCharGroup = false;
1243
- } else if (!inCharGroup && source[i] === "[") {
1244
- inCharGroup = true;
1245
- }
1246
- }
1247
- try {
1248
- new RegExp(pattern);
1249
- } catch (e) {
1250
- console.warn(
1251
- `Could not convert regex pattern at ${refs.currentPath.join(
1252
- "/"
1253
- )} to a flag-independent form! Falling back to the flag-ignorant source`
1254
- );
1255
- return regex.source;
1256
- }
1257
- return pattern;
1258
- }
1259
- function parseRecordDef(def, refs) {
1260
- var _a22, _b22, _c, _d, _e, _f;
1261
- const schema = {
1262
- type: "object",
1263
- additionalProperties: (_a22 = parseDef(def.valueType._def, {
1264
- ...refs,
1265
- currentPath: [...refs.currentPath, "additionalProperties"]
1266
- })) != null ? _a22 : refs.allowedAdditionalProperties
1267
- };
1268
- if (((_b22 = def.keyType) == null ? void 0 : _b22._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1269
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1270
- return {
1271
- ...schema,
1272
- propertyNames: keyType
1273
- };
1274
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodEnum) {
1275
- return {
1276
- ...schema,
1277
- propertyNames: {
1278
- enum: def.keyType._def.values
1279
- }
1280
- };
1281
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === import_v33.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === import_v33.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1282
- const { type, ...keyType } = parseBrandedDef(
1283
- def.keyType._def,
1284
- refs
1285
- );
1286
- return {
1287
- ...schema,
1288
- propertyNames: keyType
1289
- };
1290
- }
1291
- return schema;
1292
- }
1293
- function parseMapDef(def, refs) {
1294
- if (refs.mapStrategy === "record") {
1295
- return parseRecordDef(def, refs);
1296
- }
1297
- const keys = parseDef(def.keyType._def, {
1298
- ...refs,
1299
- currentPath: [...refs.currentPath, "items", "items", "0"]
1300
- }) || parseAnyDef();
1301
- const values = parseDef(def.valueType._def, {
1302
- ...refs,
1303
- currentPath: [...refs.currentPath, "items", "items", "1"]
1304
- }) || parseAnyDef();
1305
- return {
1306
- type: "array",
1307
- maxItems: 125,
1308
- items: {
1309
- type: "array",
1310
- items: [keys, values],
1311
- minItems: 2,
1312
- maxItems: 2
1313
- }
1314
- };
1315
- }
1316
- function parseNativeEnumDef(def) {
1317
- const object = def.values;
1318
- const actualKeys = Object.keys(def.values).filter((key) => {
1319
- return typeof object[object[key]] !== "number";
1320
- });
1321
- const actualValues = actualKeys.map((key) => object[key]);
1322
- const parsedTypes = Array.from(
1323
- new Set(actualValues.map((values) => typeof values))
1324
- );
1325
- return {
1326
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1327
- enum: actualValues
1328
- };
1329
- }
1330
- function parseNeverDef() {
1331
- return { not: parseAnyDef() };
1332
- }
1333
- function parseNullDef() {
1334
- return {
1335
- type: "null"
1336
- };
1337
- }
1338
- var primitiveMappings = {
1339
- ZodString: "string",
1340
- ZodNumber: "number",
1341
- ZodBigInt: "integer",
1342
- ZodBoolean: "boolean",
1343
- ZodNull: "null"
1344
- };
1345
- function parseUnionDef(def, refs) {
1346
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1347
- if (options.every(
1348
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1349
- )) {
1350
- const types = options.reduce((types2, x) => {
1351
- const type = primitiveMappings[x._def.typeName];
1352
- return type && !types2.includes(type) ? [...types2, type] : types2;
1353
- }, []);
1354
- return {
1355
- type: types.length > 1 ? types : types[0]
1356
- };
1357
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1358
- const types = options.reduce(
1359
- (acc, x) => {
1360
- const type = typeof x._def.value;
1361
- switch (type) {
1362
- case "string":
1363
- case "number":
1364
- case "boolean":
1365
- return [...acc, type];
1366
- case "bigint":
1367
- return [...acc, "integer"];
1368
- case "object":
1369
- if (x._def.value === null) return [...acc, "null"];
1370
- case "symbol":
1371
- case "undefined":
1372
- case "function":
1373
- default:
1374
- return acc;
1375
- }
1376
- },
1377
- []
1378
- );
1379
- if (types.length === options.length) {
1380
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1381
- return {
1382
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1383
- enum: options.reduce(
1384
- (acc, x) => {
1385
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1386
- },
1387
- []
1388
- )
1389
- };
1390
- }
1391
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1392
- return {
1393
- type: "string",
1394
- enum: options.reduce(
1395
- (acc, x) => [
1396
- ...acc,
1397
- ...x._def.values.filter((x2) => !acc.includes(x2))
1398
- ],
1399
- []
1400
- )
1401
- };
1402
- }
1403
- return asAnyOf(def, refs);
1404
- }
1405
- var asAnyOf = (def, refs) => {
1406
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1407
- (x, i) => parseDef(x._def, {
1408
- ...refs,
1409
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
1410
- })
1411
- ).filter(
1412
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1413
- );
1414
- return anyOf.length ? { anyOf } : void 0;
1415
- };
1416
- function parseNullableDef(def, refs) {
1417
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1418
- def.innerType._def.typeName
1419
- ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1420
- return {
1421
- type: [
1422
- primitiveMappings[def.innerType._def.typeName],
1423
- "null"
1424
- ]
1425
- };
1426
- }
1427
- const base = parseDef(def.innerType._def, {
1428
- ...refs,
1429
- currentPath: [...refs.currentPath, "anyOf", "0"]
1430
- });
1431
- return base && { anyOf: [base, { type: "null" }] };
1432
- }
1433
- function parseNumberDef(def) {
1434
- const res = {
1435
- type: "number"
1436
- };
1437
- if (!def.checks) return res;
1438
- for (const check of def.checks) {
1439
- switch (check.kind) {
1440
- case "int":
1441
- res.type = "integer";
1442
- break;
1443
- case "min":
1444
- if (check.inclusive) {
1445
- res.minimum = check.value;
1446
- } else {
1447
- res.exclusiveMinimum = check.value;
1448
- }
1449
- break;
1450
- case "max":
1451
- if (check.inclusive) {
1452
- res.maximum = check.value;
1453
- } else {
1454
- res.exclusiveMaximum = check.value;
1455
- }
1456
- break;
1457
- case "multipleOf":
1458
- res.multipleOf = check.value;
1459
- break;
1460
- }
1461
- }
1462
- return res;
1463
- }
1464
- function parseObjectDef(def, refs) {
1465
- const result = {
1466
- type: "object",
1467
- properties: {}
1468
- };
1469
- const required = [];
1470
- const shape = def.shape();
1471
- for (const propName in shape) {
1472
- let propDef = shape[propName];
1473
- if (propDef === void 0 || propDef._def === void 0) {
1474
- continue;
1475
- }
1476
- const propOptional = safeIsOptional(propDef);
1477
- const parsedDef = parseDef(propDef._def, {
1478
- ...refs,
1479
- currentPath: [...refs.currentPath, "properties", propName],
1480
- propertyPath: [...refs.currentPath, "properties", propName]
1481
- });
1482
- if (parsedDef === void 0) {
1483
- continue;
1484
- }
1485
- result.properties[propName] = parsedDef;
1486
- if (!propOptional) {
1487
- required.push(propName);
1488
- }
1489
- }
1490
- if (required.length) {
1491
- result.required = required;
1492
- }
1493
- const additionalProperties = decideAdditionalProperties(def, refs);
1494
- if (additionalProperties !== void 0) {
1495
- result.additionalProperties = additionalProperties;
1496
- }
1497
- return result;
1498
- }
1499
- function decideAdditionalProperties(def, refs) {
1500
- if (def.catchall._def.typeName !== "ZodNever") {
1501
- return parseDef(def.catchall._def, {
1502
- ...refs,
1503
- currentPath: [...refs.currentPath, "additionalProperties"]
1504
- });
1505
- }
1506
- switch (def.unknownKeys) {
1507
- case "passthrough":
1508
- return refs.allowedAdditionalProperties;
1509
- case "strict":
1510
- return refs.rejectedAdditionalProperties;
1511
- case "strip":
1512
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1513
- }
1514
- }
1515
- function safeIsOptional(schema) {
1516
- try {
1517
- return schema.isOptional();
1518
- } catch (e) {
1519
- return true;
1520
- }
1521
- }
1522
- var parseOptionalDef = (def, refs) => {
1523
- var _a22;
1524
- if (refs.currentPath.toString() === ((_a22 = refs.propertyPath) == null ? void 0 : _a22.toString())) {
1525
- return parseDef(def.innerType._def, refs);
1526
- }
1527
- const innerSchema = parseDef(def.innerType._def, {
1528
- ...refs,
1529
- currentPath: [...refs.currentPath, "anyOf", "1"]
1530
- });
1531
- return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1532
- };
1533
- var parsePipelineDef = (def, refs) => {
1534
- if (refs.pipeStrategy === "input") {
1535
- return parseDef(def.in._def, refs);
1536
- } else if (refs.pipeStrategy === "output") {
1537
- return parseDef(def.out._def, refs);
1538
- }
1539
- const a = parseDef(def.in._def, {
1540
- ...refs,
1541
- currentPath: [...refs.currentPath, "allOf", "0"]
1542
- });
1543
- const b = parseDef(def.out._def, {
1544
- ...refs,
1545
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1546
- });
1547
- return {
1548
- allOf: [a, b].filter((x) => x !== void 0)
1549
- };
1550
- };
1551
- function parsePromiseDef(def, refs) {
1552
- return parseDef(def.type._def, refs);
1553
- }
1554
- function parseSetDef(def, refs) {
1555
- const items = parseDef(def.valueType._def, {
1556
- ...refs,
1557
- currentPath: [...refs.currentPath, "items"]
1558
- });
1559
- const schema = {
1560
- type: "array",
1561
- uniqueItems: true,
1562
- items
1563
- };
1564
- if (def.minSize) {
1565
- schema.minItems = def.minSize.value;
1566
- }
1567
- if (def.maxSize) {
1568
- schema.maxItems = def.maxSize.value;
1569
- }
1570
- return schema;
1571
- }
1572
- function parseTupleDef(def, refs) {
1573
- if (def.rest) {
1574
- return {
1575
- type: "array",
1576
- minItems: def.items.length,
1577
- items: def.items.map(
1578
- (x, i) => parseDef(x._def, {
1579
- ...refs,
1580
- currentPath: [...refs.currentPath, "items", `${i}`]
1581
- })
1582
- ).reduce(
1583
- (acc, x) => x === void 0 ? acc : [...acc, x],
1584
- []
1585
- ),
1586
- additionalItems: parseDef(def.rest._def, {
1587
- ...refs,
1588
- currentPath: [...refs.currentPath, "additionalItems"]
1589
- })
1590
- };
1591
- } else {
1592
- return {
1593
- type: "array",
1594
- minItems: def.items.length,
1595
- maxItems: def.items.length,
1596
- items: def.items.map(
1597
- (x, i) => parseDef(x._def, {
1598
- ...refs,
1599
- currentPath: [...refs.currentPath, "items", `${i}`]
1600
- })
1601
- ).reduce(
1602
- (acc, x) => x === void 0 ? acc : [...acc, x],
1603
- []
1604
- )
1605
- };
1606
- }
1607
- }
1608
- function parseUndefinedDef() {
1609
- return {
1610
- not: parseAnyDef()
1611
- };
1612
- }
1613
- function parseUnknownDef() {
1614
- return parseAnyDef();
1615
- }
1616
- var parseReadonlyDef = (def, refs) => {
1617
- return parseDef(def.innerType._def, refs);
1618
- };
1619
- var selectParser = (def, typeName, refs) => {
1620
- switch (typeName) {
1621
- case import_v3.ZodFirstPartyTypeKind.ZodString:
1622
- return parseStringDef(def, refs);
1623
- case import_v3.ZodFirstPartyTypeKind.ZodNumber:
1624
- return parseNumberDef(def);
1625
- case import_v3.ZodFirstPartyTypeKind.ZodObject:
1626
- return parseObjectDef(def, refs);
1627
- case import_v3.ZodFirstPartyTypeKind.ZodBigInt:
1628
- return parseBigintDef(def);
1629
- case import_v3.ZodFirstPartyTypeKind.ZodBoolean:
1630
- return parseBooleanDef();
1631
- case import_v3.ZodFirstPartyTypeKind.ZodDate:
1632
- return parseDateDef(def, refs);
1633
- case import_v3.ZodFirstPartyTypeKind.ZodUndefined:
1634
- return parseUndefinedDef();
1635
- case import_v3.ZodFirstPartyTypeKind.ZodNull:
1636
- return parseNullDef();
1637
- case import_v3.ZodFirstPartyTypeKind.ZodArray:
1638
- return parseArrayDef(def, refs);
1639
- case import_v3.ZodFirstPartyTypeKind.ZodUnion:
1640
- case import_v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1641
- return parseUnionDef(def, refs);
1642
- case import_v3.ZodFirstPartyTypeKind.ZodIntersection:
1643
- return parseIntersectionDef(def, refs);
1644
- case import_v3.ZodFirstPartyTypeKind.ZodTuple:
1645
- return parseTupleDef(def, refs);
1646
- case import_v3.ZodFirstPartyTypeKind.ZodRecord:
1647
- return parseRecordDef(def, refs);
1648
- case import_v3.ZodFirstPartyTypeKind.ZodLiteral:
1649
- return parseLiteralDef(def);
1650
- case import_v3.ZodFirstPartyTypeKind.ZodEnum:
1651
- return parseEnumDef(def);
1652
- case import_v3.ZodFirstPartyTypeKind.ZodNativeEnum:
1653
- return parseNativeEnumDef(def);
1654
- case import_v3.ZodFirstPartyTypeKind.ZodNullable:
1655
- return parseNullableDef(def, refs);
1656
- case import_v3.ZodFirstPartyTypeKind.ZodOptional:
1657
- return parseOptionalDef(def, refs);
1658
- case import_v3.ZodFirstPartyTypeKind.ZodMap:
1659
- return parseMapDef(def, refs);
1660
- case import_v3.ZodFirstPartyTypeKind.ZodSet:
1661
- return parseSetDef(def, refs);
1662
- case import_v3.ZodFirstPartyTypeKind.ZodLazy:
1663
- return () => def.getter()._def;
1664
- case import_v3.ZodFirstPartyTypeKind.ZodPromise:
1665
- return parsePromiseDef(def, refs);
1666
- case import_v3.ZodFirstPartyTypeKind.ZodNaN:
1667
- case import_v3.ZodFirstPartyTypeKind.ZodNever:
1668
- return parseNeverDef();
1669
- case import_v3.ZodFirstPartyTypeKind.ZodEffects:
1670
- return parseEffectsDef(def, refs);
1671
- case import_v3.ZodFirstPartyTypeKind.ZodAny:
1672
- return parseAnyDef();
1673
- case import_v3.ZodFirstPartyTypeKind.ZodUnknown:
1674
- return parseUnknownDef();
1675
- case import_v3.ZodFirstPartyTypeKind.ZodDefault:
1676
- return parseDefaultDef(def, refs);
1677
- case import_v3.ZodFirstPartyTypeKind.ZodBranded:
1678
- return parseBrandedDef(def, refs);
1679
- case import_v3.ZodFirstPartyTypeKind.ZodReadonly:
1680
- return parseReadonlyDef(def, refs);
1681
- case import_v3.ZodFirstPartyTypeKind.ZodCatch:
1682
- return parseCatchDef(def, refs);
1683
- case import_v3.ZodFirstPartyTypeKind.ZodPipeline:
1684
- return parsePipelineDef(def, refs);
1685
- case import_v3.ZodFirstPartyTypeKind.ZodFunction:
1686
- case import_v3.ZodFirstPartyTypeKind.ZodVoid:
1687
- case import_v3.ZodFirstPartyTypeKind.ZodSymbol:
1688
- return void 0;
1689
- default:
1690
- return /* @__PURE__ */ ((_) => void 0)(typeName);
1691
- }
1692
- };
1693
- var getRelativePath = (pathA, pathB) => {
1694
- let i = 0;
1695
- for (; i < pathA.length && i < pathB.length; i++) {
1696
- if (pathA[i] !== pathB[i]) break;
1697
- }
1698
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1699
- };
1700
- function parseDef(def, refs, forceResolution = false) {
1701
- var _a22;
1702
- const seenItem = refs.seen.get(def);
1703
- if (refs.override) {
1704
- const overrideResult = (_a22 = refs.override) == null ? void 0 : _a22.call(
1705
- refs,
1706
- def,
1707
- refs,
1708
- seenItem,
1709
- forceResolution
1710
- );
1711
- if (overrideResult !== ignoreOverride) {
1712
- return overrideResult;
1713
- }
1714
- }
1715
- if (seenItem && !forceResolution) {
1716
- const seenSchema = get$ref(seenItem, refs);
1717
- if (seenSchema !== void 0) {
1718
- return seenSchema;
1719
- }
1720
- }
1721
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1722
- refs.seen.set(def, newItem);
1723
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1724
- const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1725
- if (jsonSchema2) {
1726
- addMeta(def, refs, jsonSchema2);
1727
- }
1728
- if (refs.postProcess) {
1729
- const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1730
- newItem.jsonSchema = jsonSchema2;
1731
- return postProcessResult;
1732
- }
1733
- newItem.jsonSchema = jsonSchema2;
1734
- return jsonSchema2;
1735
- }
1736
- var get$ref = (item, refs) => {
1737
- switch (refs.$refStrategy) {
1738
- case "root":
1739
- return { $ref: item.path.join("/") };
1740
- case "relative":
1741
- return { $ref: getRelativePath(refs.currentPath, item.path) };
1742
- case "none":
1743
- case "seen": {
1744
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1745
- console.warn(
1746
- `Recursive reference detected at ${refs.currentPath.join(
1747
- "/"
1748
- )}! Defaulting to any`
1749
- );
1750
- return parseAnyDef();
1751
- }
1752
- return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1753
- }
1754
- }
1755
- };
1756
- var addMeta = (def, refs, jsonSchema2) => {
1757
- if (def.description) {
1758
- jsonSchema2.description = def.description;
1759
- }
1760
- return jsonSchema2;
1761
- };
1762
- var getRefs = (options) => {
1763
- const _options = getDefaultOptions(options);
1764
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1765
- return {
1766
- ..._options,
1767
- currentPath,
1768
- propertyPath: void 0,
1769
- seen: new Map(
1770
- Object.entries(_options.definitions).map(([name22, def]) => [
1771
- def._def,
1772
- {
1773
- def: def._def,
1774
- path: [..._options.basePath, _options.definitionPath, name22],
1775
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1776
- jsonSchema: void 0
1777
- }
1778
- ])
1779
- )
1780
- };
1781
- };
1782
- var zod3ToJsonSchema = (schema, options) => {
1783
- var _a22;
1784
- const refs = getRefs(options);
1785
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1786
- (acc, [name32, schema2]) => {
1787
- var _a32;
1788
- return {
1789
- ...acc,
1790
- [name32]: (_a32 = parseDef(
1791
- schema2._def,
1792
- {
1793
- ...refs,
1794
- currentPath: [...refs.basePath, refs.definitionPath, name32]
1795
- },
1796
- true
1797
- )) != null ? _a32 : parseAnyDef()
1798
- };
1799
- },
1800
- {}
1801
- ) : void 0;
1802
- const name22 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1803
- const main = (_a22 = parseDef(
1804
- schema._def,
1805
- name22 === void 0 ? refs : {
1806
- ...refs,
1807
- currentPath: [...refs.basePath, refs.definitionPath, name22]
1808
- },
1809
- false
1810
- )) != null ? _a22 : parseAnyDef();
1811
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1812
- if (title !== void 0) {
1813
- main.title = title;
1814
- }
1815
- const combined = name22 === void 0 ? definitions ? {
1816
- ...main,
1817
- [refs.definitionPath]: definitions
1818
- } : main : {
1819
- $ref: [
1820
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1821
- refs.definitionPath,
1822
- name22
1823
- ].join("/"),
1824
- [refs.definitionPath]: {
1825
- ...definitions,
1826
- [name22]: main
1827
- }
1828
- };
1829
- combined.$schema = "http://json-schema.org/draft-07/schema#";
1830
- return combined;
1831
- };
1832
- var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1833
- function jsonSchema(jsonSchema2, {
1834
- validate
1835
- } = {}) {
1836
- return {
1837
- [schemaSymbol]: true,
1838
- _type: void 0,
1839
- // should never be used directly
1840
- get jsonSchema() {
1841
- if (typeof jsonSchema2 === "function") {
1842
- jsonSchema2 = jsonSchema2();
1843
- }
1844
- return jsonSchema2;
1845
- },
1846
- validate
1847
- };
1848
- }
1849
- function isSchema(value) {
1850
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1851
- }
1852
- function asSchema(schema) {
1853
- return schema == null ? jsonSchema({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
1854
- }
1855
- function standardSchema(standardSchema2) {
1856
- return jsonSchema(
1857
- () => addAdditionalPropertiesToJsonSchema(
1858
- standardSchema2["~standard"].jsonSchema.input({
1859
- target: "draft-07"
1860
- })
1861
- ),
1862
- {
1863
- validate: async (value) => {
1864
- const result = await standardSchema2["~standard"].validate(value);
1865
- return "value" in result ? { success: true, value: result.value } : {
1866
- success: false,
1867
- error: new TypeValidationError({
1868
- value,
1869
- cause: result.issues
1870
- })
1871
- };
1872
- }
1873
- }
1874
- );
1875
- }
1876
- function zod3Schema(zodSchema2, options) {
1877
- var _a22;
1878
- const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1879
- return jsonSchema(
1880
- // defer json schema creation to avoid unnecessary computation when only validation is needed
1881
- () => zod3ToJsonSchema(zodSchema2, {
1882
- $refStrategy: useReferences ? "root" : "none"
1883
- }),
1884
- {
1885
- validate: async (value) => {
1886
- const result = await zodSchema2.safeParseAsync(value);
1887
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1888
- }
1889
- }
1890
- );
1891
- }
1892
- function zod4Schema(zodSchema2, options) {
1893
- var _a22;
1894
- const useReferences = (_a22 = options == null ? void 0 : options.useReferences) != null ? _a22 : false;
1895
- return jsonSchema(
1896
- // defer json schema creation to avoid unnecessary computation when only validation is needed
1897
- () => addAdditionalPropertiesToJsonSchema(
1898
- z4.toJSONSchema(zodSchema2, {
1899
- target: "draft-7",
1900
- io: "input",
1901
- reused: useReferences ? "ref" : "inline"
1902
- })
1903
- ),
1904
- {
1905
- validate: async (value) => {
1906
- const result = await z4.safeParseAsync(zodSchema2, value);
1907
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1908
- }
1909
- }
1910
- );
1911
- }
1912
- function isZod4Schema(zodSchema2) {
1913
- return "_zod" in zodSchema2;
1914
- }
1915
- function zodSchema(zodSchema2, options) {
1916
- if (isZod4Schema(zodSchema2)) {
1917
- return zod4Schema(zodSchema2, options);
1918
- } else {
1919
- return zod3Schema(zodSchema2, options);
1920
- }
1921
- }
1922
- async function validateTypes({
1923
- value,
1924
- schema
1925
- }) {
1926
- const result = await safeValidateTypes({ value, schema });
1927
- if (!result.success) {
1928
- throw TypeValidationError.wrap({ value, cause: result.error });
1929
- }
1930
- return result.value;
1931
- }
1932
- async function safeValidateTypes({
1933
- value,
1934
- schema
1935
- }) {
1936
- const actualSchema = asSchema(schema);
1937
- try {
1938
- if (actualSchema.validate == null) {
1939
- return { success: true, value, rawValue: value };
1940
- }
1941
- const result = await actualSchema.validate(value);
1942
- if (result.success) {
1943
- return { success: true, value: result.value, rawValue: value };
1944
- }
1945
- return {
1946
- success: false,
1947
- error: TypeValidationError.wrap({ value, cause: result.error }),
1948
- rawValue: value
1949
- };
1950
- } catch (error) {
1951
- return {
1952
- success: false,
1953
- error: TypeValidationError.wrap({ value, cause: error }),
1954
- rawValue: value
1955
- };
1956
- }
1957
- }
1958
- async function parseJSON({
1959
- text,
1960
- schema
1961
- }) {
1962
- try {
1963
- const value = secureJsonParse(text);
1964
- if (schema == null) {
1965
- return value;
1966
- }
1967
- return validateTypes({ value, schema });
1968
- } catch (error) {
1969
- if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
1970
- throw error;
1971
- }
1972
- throw new JSONParseError({ text, cause: error });
1973
- }
1974
- }
1975
- async function safeParseJSON({
1976
- text,
1977
- schema
1978
- }) {
1979
- try {
1980
- const value = secureJsonParse(text);
1981
- if (schema == null) {
1982
- return { success: true, value, rawValue: value };
1983
- }
1984
- return await safeValidateTypes({ value, schema });
1985
- } catch (error) {
1986
- return {
1987
- success: false,
1988
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
1989
- rawValue: void 0
1990
- };
1991
- }
1992
- }
1993
- function parseJsonEventStream({
1994
- stream,
1995
- schema
1996
- }) {
1997
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
1998
- new TransformStream({
1999
- async transform({ data }, controller) {
2000
- if (data === "[DONE]") {
2001
- return;
2002
- }
2003
- controller.enqueue(await safeParseJSON({ text: data, schema }));
2004
- }
2005
- })
2006
- );
784
+ return parsedProviderOptions.value;
2007
785
  }
2008
786
  var getOriginalFetch2 = () => globalThis.fetch;
2009
787
  var postJsonToApi = async ({
@@ -2013,7 +791,7 @@ var postJsonToApi = async ({
2013
791
  failedResponseHandler,
2014
792
  successfulResponseHandler,
2015
793
  abortSignal,
2016
- fetch: fetch2
794
+ fetch
2017
795
  }) => postToApi({
2018
796
  url,
2019
797
  headers: {
@@ -2027,7 +805,7 @@ var postJsonToApi = async ({
2027
805
  failedResponseHandler,
2028
806
  successfulResponseHandler,
2029
807
  abortSignal,
2030
- fetch: fetch2
808
+ fetch
2031
809
  });
2032
810
  var postToApi = async ({
2033
811
  url,
@@ -2036,10 +814,10 @@ var postToApi = async ({
2036
814
  successfulResponseHandler,
2037
815
  failedResponseHandler,
2038
816
  abortSignal,
2039
- fetch: fetch2 = getOriginalFetch2()
817
+ fetch = getOriginalFetch2()
2040
818
  }) => {
2041
819
  try {
2042
- const response = await fetch2(url, {
820
+ const response = await fetch(url, {
2043
821
  method: "POST",
2044
822
  headers: withUserAgentSuffix(
2045
823
  headers,
@@ -2189,856 +967,1393 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
2189
967
  rawValue: parsedResult.rawValue
2190
968
  };
2191
969
  };
2192
- function withoutTrailingSlash(url) {
2193
- return url == null ? void 0 : url.replace(/\/$/, "");
2194
- }
2195
-
2196
- // src/apertis-error.ts
2197
- var import_zod = require("zod");
2198
- var apertisErrorSchema = import_zod.z.object({
2199
- error: import_zod.z.object({
2200
- message: import_zod.z.string(),
2201
- type: import_zod.z.string().optional(),
2202
- code: import_zod.z.string().nullable().optional(),
2203
- param: import_zod.z.string().nullable().optional()
2204
- })
2205
- });
2206
- var apertisFailedResponseHandler = createJsonErrorResponseHandler({
2207
- errorSchema: apertisErrorSchema,
2208
- errorToMessage: (error) => error.error.message
2209
- });
2210
-
2211
- // src/schemas/chat-response.ts
2212
- var import_zod2 = require("zod");
2213
- var openAIChatResponseSchema = import_zod2.z.object({
2214
- id: import_zod2.z.string().optional(),
2215
- object: import_zod2.z.literal("chat.completion").optional(),
2216
- created: import_zod2.z.number().optional(),
2217
- model: import_zod2.z.string().optional(),
2218
- choices: import_zod2.z.array(
2219
- import_zod2.z.object({
2220
- index: import_zod2.z.number(),
2221
- message: import_zod2.z.object({
2222
- role: import_zod2.z.literal("assistant"),
2223
- content: import_zod2.z.string().nullable(),
2224
- tool_calls: import_zod2.z.array(
2225
- import_zod2.z.object({
2226
- id: import_zod2.z.string(),
2227
- type: import_zod2.z.literal("function"),
2228
- function: import_zod2.z.object({
2229
- name: import_zod2.z.string(),
2230
- arguments: import_zod2.z.string()
2231
- })
2232
- })
2233
- ).optional()
2234
- }),
2235
- finish_reason: import_zod2.z.string().nullable(),
2236
- logprobs: import_zod2.z.any().nullable().optional()
2237
- })
2238
- ),
2239
- usage: import_zod2.z.object({
2240
- prompt_tokens: import_zod2.z.number(),
2241
- completion_tokens: import_zod2.z.number(),
2242
- total_tokens: import_zod2.z.number().optional()
2243
- }).optional()
2244
- });
2245
- var openAIChatChunkSchema = import_zod2.z.object({
2246
- id: import_zod2.z.string().optional(),
2247
- object: import_zod2.z.literal("chat.completion.chunk").optional(),
2248
- created: import_zod2.z.number().optional(),
2249
- model: import_zod2.z.string().optional(),
2250
- choices: import_zod2.z.array(
2251
- import_zod2.z.object({
2252
- index: import_zod2.z.number(),
2253
- delta: import_zod2.z.object({
2254
- role: import_zod2.z.literal("assistant").optional(),
2255
- content: import_zod2.z.string().nullable().optional(),
2256
- tool_calls: import_zod2.z.array(
2257
- import_zod2.z.object({
2258
- index: import_zod2.z.number(),
2259
- id: import_zod2.z.string().optional(),
2260
- type: import_zod2.z.literal("function").optional(),
2261
- function: import_zod2.z.object({
2262
- name: import_zod2.z.string().optional(),
2263
- arguments: import_zod2.z.string().optional()
2264
- }).optional()
2265
- })
2266
- ).optional()
2267
- }),
2268
- finish_reason: import_zod2.z.string().nullable().optional()
2269
- })
2270
- ),
2271
- usage: import_zod2.z.object({
2272
- prompt_tokens: import_zod2.z.number(),
2273
- completion_tokens: import_zod2.z.number()
2274
- }).nullish()
2275
- });
2276
-
2277
- // src/utils/map-finish-reason.ts
2278
- function normalizeFinishReason(finishReason) {
2279
- switch (finishReason) {
2280
- case "stop":
2281
- return "stop";
2282
- case "length":
2283
- return "length";
2284
- case "tool_calls":
2285
- return "tool-calls";
2286
- case "content_filter":
2287
- return "content-filter";
2288
- default:
2289
- return "other";
970
+ var ALPHA_NUMERIC = new Set(
971
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
972
+ );
973
+ var { btoa, atob } = globalThis;
974
+ function convertUint8ArrayToBase64(array) {
975
+ let latin1string = "";
976
+ for (let i = 0; i < array.length; i++) {
977
+ latin1string += String.fromCodePoint(array[i]);
2290
978
  }
979
+ return btoa(latin1string);
2291
980
  }
2292
- function mapApertisFinishReason(finishReason) {
2293
- return {
2294
- unified: normalizeFinishReason(finishReason),
2295
- raw: finishReason ?? void 0
2296
- };
981
+ function convertToBase64(value) {
982
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
2297
983
  }
2298
- function mapApertisFinishReasonV2(finishReason) {
2299
- return normalizeFinishReason(finishReason);
984
+ function withoutTrailingSlash(url) {
985
+ return url == null ? void 0 : url.replace(/\/$/, "");
2300
986
  }
2301
987
 
2302
- // src/utils/convert-to-openai-messages.ts
2303
- function convertToOpenAIMessages(prompt) {
988
+ // node_modules/.pnpm/@ai-sdk+openai-compatible@1.0.30_zod@3.25.76/node_modules/@ai-sdk/openai-compatible/dist/index.mjs
989
+ var import_v4 = require("zod/v4");
990
+ var import_v42 = require("zod/v4");
991
+ var import_v43 = require("zod/v4");
992
+ var import_v44 = require("zod/v4");
993
+ var import_v45 = require("zod/v4");
994
+ var import_v46 = require("zod/v4");
995
+ var import_v47 = require("zod/v4");
996
+ var import_v48 = require("zod/v4");
997
+ function getOpenAIMetadata(message) {
998
+ var _a15, _b15;
999
+ return (_b15 = (_a15 = message == null ? void 0 : message.providerOptions) == null ? void 0 : _a15.openaiCompatible) != null ? _b15 : {};
1000
+ }
1001
+ function convertToOpenAICompatibleChatMessages(prompt) {
2304
1002
  const messages = [];
2305
- for (const message of prompt) {
2306
- switch (message.role) {
2307
- case "system":
2308
- messages.push({ role: "system", content: message.content });
1003
+ for (const { role, content, ...message } of prompt) {
1004
+ const metadata = getOpenAIMetadata({ ...message });
1005
+ switch (role) {
1006
+ case "system": {
1007
+ messages.push({ role: "system", content, ...metadata });
2309
1008
  break;
2310
- case "user":
1009
+ }
1010
+ case "user": {
1011
+ if (content.length === 1 && content[0].type === "text") {
1012
+ messages.push({
1013
+ role: "user",
1014
+ content: content[0].text,
1015
+ ...getOpenAIMetadata(content[0])
1016
+ });
1017
+ break;
1018
+ }
2311
1019
  messages.push({
2312
1020
  role: "user",
2313
- content: message.content.map((part) => {
1021
+ content: content.map((part) => {
1022
+ const partMetadata = getOpenAIMetadata(part);
2314
1023
  switch (part.type) {
2315
- case "text":
2316
- return { type: "text", text: part.text };
1024
+ case "text": {
1025
+ return { type: "text", text: part.text, ...partMetadata };
1026
+ }
2317
1027
  case "file": {
2318
- if (part.mediaType?.startsWith("image/")) {
2319
- let url;
2320
- if (part.data instanceof URL) {
2321
- url = part.data.toString();
2322
- } else if (typeof part.data === "string") {
2323
- if (part.data.startsWith("http://") || part.data.startsWith("https://")) {
2324
- url = part.data;
2325
- } else {
2326
- url = `data:${part.mediaType};base64,${part.data}`;
2327
- }
2328
- } else {
2329
- url = `data:${part.mediaType};base64,${Buffer.from(part.data).toString("base64")}`;
2330
- }
1028
+ if (part.mediaType.startsWith("image/")) {
1029
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
2331
1030
  return {
2332
1031
  type: "image_url",
2333
- image_url: { url }
1032
+ image_url: {
1033
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
1034
+ },
1035
+ ...partMetadata
2334
1036
  };
1037
+ } else {
1038
+ throw new UnsupportedFunctionalityError({
1039
+ functionality: `file part media type ${part.mediaType}`
1040
+ });
2335
1041
  }
2336
- throw new Error(
2337
- `Unsupported file type: ${part.mediaType}. Only image/* is supported.`
2338
- );
2339
1042
  }
2340
- default:
2341
- throw new Error(
2342
- `Unsupported user content part type: ${part.type}`
2343
- );
2344
1043
  }
2345
- })
1044
+ }),
1045
+ ...metadata
2346
1046
  });
2347
1047
  break;
1048
+ }
2348
1049
  case "assistant": {
2349
- const textContent = message.content.filter((p) => p.type === "text").map((p) => p.text).join("");
2350
- const toolCalls = message.content.filter((p) => p.type === "tool-call").map((tc) => {
2351
- let arguments_str = "{}";
2352
- try {
2353
- arguments_str = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
2354
- } catch {
2355
- arguments_str = "{}";
1050
+ let text = "";
1051
+ const toolCalls = [];
1052
+ for (const part of content) {
1053
+ const partMetadata = getOpenAIMetadata(part);
1054
+ switch (part.type) {
1055
+ case "text": {
1056
+ text += part.text;
1057
+ break;
1058
+ }
1059
+ case "tool-call": {
1060
+ toolCalls.push({
1061
+ id: part.toolCallId,
1062
+ type: "function",
1063
+ function: {
1064
+ name: part.toolName,
1065
+ arguments: JSON.stringify(part.input)
1066
+ },
1067
+ ...partMetadata
1068
+ });
1069
+ break;
1070
+ }
2356
1071
  }
2357
- return {
2358
- id: tc.toolCallId,
2359
- type: "function",
2360
- function: { name: tc.toolName, arguments: arguments_str }
2361
- };
2362
- });
1072
+ }
2363
1073
  messages.push({
2364
1074
  role: "assistant",
2365
- content: textContent || null,
2366
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
1075
+ content: text,
1076
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
1077
+ ...metadata
1078
+ });
1079
+ break;
1080
+ }
1081
+ case "tool": {
1082
+ for (const toolResponse of content) {
1083
+ const output = toolResponse.output;
1084
+ let contentValue;
1085
+ switch (output.type) {
1086
+ case "text":
1087
+ case "error-text":
1088
+ contentValue = output.value;
1089
+ break;
1090
+ case "content":
1091
+ case "json":
1092
+ case "error-json":
1093
+ contentValue = JSON.stringify(output.value);
1094
+ break;
1095
+ }
1096
+ const toolResponseMetadata = getOpenAIMetadata(toolResponse);
1097
+ messages.push({
1098
+ role: "tool",
1099
+ tool_call_id: toolResponse.toolCallId,
1100
+ content: contentValue,
1101
+ ...toolResponseMetadata
1102
+ });
1103
+ }
1104
+ break;
1105
+ }
1106
+ default: {
1107
+ const _exhaustiveCheck = role;
1108
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1109
+ }
1110
+ }
1111
+ }
1112
+ return messages;
1113
+ }
1114
+ function getResponseMetadata({
1115
+ id,
1116
+ model,
1117
+ created
1118
+ }) {
1119
+ return {
1120
+ id: id != null ? id : void 0,
1121
+ modelId: model != null ? model : void 0,
1122
+ timestamp: created != null ? new Date(created * 1e3) : void 0
1123
+ };
1124
+ }
1125
+ function mapOpenAICompatibleFinishReason(finishReason) {
1126
+ switch (finishReason) {
1127
+ case "stop":
1128
+ return "stop";
1129
+ case "length":
1130
+ return "length";
1131
+ case "content_filter":
1132
+ return "content-filter";
1133
+ case "function_call":
1134
+ case "tool_calls":
1135
+ return "tool-calls";
1136
+ default:
1137
+ return "unknown";
1138
+ }
1139
+ }
1140
+ var openaiCompatibleProviderOptions = import_v42.z.object({
1141
+ /**
1142
+ * A unique identifier representing your end-user, which can help the provider to
1143
+ * monitor and detect abuse.
1144
+ */
1145
+ user: import_v42.z.string().optional(),
1146
+ /**
1147
+ * Reasoning effort for reasoning models. Defaults to `medium`.
1148
+ */
1149
+ reasoningEffort: import_v42.z.string().optional(),
1150
+ /**
1151
+ * Controls the verbosity of the generated text. Defaults to `medium`.
1152
+ */
1153
+ textVerbosity: import_v42.z.string().optional()
1154
+ });
1155
+ var openaiCompatibleErrorDataSchema = import_v43.z.object({
1156
+ error: import_v43.z.object({
1157
+ message: import_v43.z.string(),
1158
+ // The additional information below is handled loosely to support
1159
+ // OpenAI-compatible providers that have slightly different error
1160
+ // responses:
1161
+ type: import_v43.z.string().nullish(),
1162
+ param: import_v43.z.any().nullish(),
1163
+ code: import_v43.z.union([import_v43.z.string(), import_v43.z.number()]).nullish()
1164
+ })
1165
+ });
1166
+ var defaultOpenAICompatibleErrorStructure = {
1167
+ errorSchema: openaiCompatibleErrorDataSchema,
1168
+ errorToMessage: (data) => data.error.message
1169
+ };
1170
+ function prepareTools({
1171
+ tools,
1172
+ toolChoice
1173
+ }) {
1174
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1175
+ const toolWarnings = [];
1176
+ if (tools == null) {
1177
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
1178
+ }
1179
+ const openaiCompatTools = [];
1180
+ for (const tool of tools) {
1181
+ if (tool.type === "provider-defined") {
1182
+ toolWarnings.push({ type: "unsupported-tool", tool });
1183
+ } else {
1184
+ openaiCompatTools.push({
1185
+ type: "function",
1186
+ function: {
1187
+ name: tool.name,
1188
+ description: tool.description,
1189
+ parameters: tool.inputSchema
1190
+ }
1191
+ });
1192
+ }
1193
+ }
1194
+ if (toolChoice == null) {
1195
+ return { tools: openaiCompatTools, toolChoice: void 0, toolWarnings };
1196
+ }
1197
+ const type = toolChoice.type;
1198
+ switch (type) {
1199
+ case "auto":
1200
+ case "none":
1201
+ case "required":
1202
+ return { tools: openaiCompatTools, toolChoice: type, toolWarnings };
1203
+ case "tool":
1204
+ return {
1205
+ tools: openaiCompatTools,
1206
+ toolChoice: {
1207
+ type: "function",
1208
+ function: { name: toolChoice.toolName }
1209
+ },
1210
+ toolWarnings
1211
+ };
1212
+ default: {
1213
+ const _exhaustiveCheck = type;
1214
+ throw new UnsupportedFunctionalityError({
1215
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1216
+ });
1217
+ }
1218
+ }
1219
+ }
1220
+ var OpenAICompatibleChatLanguageModel = class {
1221
+ // type inferred via constructor
1222
+ constructor(modelId, config) {
1223
+ this.specificationVersion = "v2";
1224
+ var _a15, _b15;
1225
+ this.modelId = modelId;
1226
+ this.config = config;
1227
+ const errorStructure = (_a15 = config.errorStructure) != null ? _a15 : defaultOpenAICompatibleErrorStructure;
1228
+ this.chunkSchema = createOpenAICompatibleChatChunkSchema(
1229
+ errorStructure.errorSchema
1230
+ );
1231
+ this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
1232
+ this.supportsStructuredOutputs = (_b15 = config.supportsStructuredOutputs) != null ? _b15 : false;
1233
+ }
1234
+ get provider() {
1235
+ return this.config.provider;
1236
+ }
1237
+ get providerOptionsName() {
1238
+ return this.config.provider.split(".")[0].trim();
1239
+ }
1240
+ get supportedUrls() {
1241
+ var _a15, _b15, _c;
1242
+ return (_c = (_b15 = (_a15 = this.config).supportedUrls) == null ? void 0 : _b15.call(_a15)) != null ? _c : {};
1243
+ }
1244
+ async getArgs({
1245
+ prompt,
1246
+ maxOutputTokens,
1247
+ temperature,
1248
+ topP,
1249
+ topK,
1250
+ frequencyPenalty,
1251
+ presencePenalty,
1252
+ providerOptions,
1253
+ stopSequences,
1254
+ responseFormat,
1255
+ seed,
1256
+ toolChoice,
1257
+ tools
1258
+ }) {
1259
+ var _a15, _b15, _c, _d;
1260
+ const warnings = [];
1261
+ const compatibleOptions = Object.assign(
1262
+ (_a15 = await parseProviderOptions({
1263
+ provider: "openai-compatible",
1264
+ providerOptions,
1265
+ schema: openaiCompatibleProviderOptions
1266
+ })) != null ? _a15 : {},
1267
+ (_b15 = await parseProviderOptions({
1268
+ provider: this.providerOptionsName,
1269
+ providerOptions,
1270
+ schema: openaiCompatibleProviderOptions
1271
+ })) != null ? _b15 : {}
1272
+ );
1273
+ if (topK != null) {
1274
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
1275
+ }
1276
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
1277
+ warnings.push({
1278
+ type: "unsupported-setting",
1279
+ setting: "responseFormat",
1280
+ details: "JSON response format schema is only supported with structuredOutputs"
1281
+ });
1282
+ }
1283
+ const {
1284
+ tools: openaiTools,
1285
+ toolChoice: openaiToolChoice,
1286
+ toolWarnings
1287
+ } = prepareTools({
1288
+ tools,
1289
+ toolChoice
1290
+ });
1291
+ return {
1292
+ args: {
1293
+ // model id:
1294
+ model: this.modelId,
1295
+ // model specific settings:
1296
+ user: compatibleOptions.user,
1297
+ // standardized settings:
1298
+ max_tokens: maxOutputTokens,
1299
+ temperature,
1300
+ top_p: topP,
1301
+ frequency_penalty: frequencyPenalty,
1302
+ presence_penalty: presencePenalty,
1303
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? {
1304
+ type: "json_schema",
1305
+ json_schema: {
1306
+ schema: responseFormat.schema,
1307
+ name: (_c = responseFormat.name) != null ? _c : "response",
1308
+ description: responseFormat.description
1309
+ }
1310
+ } : { type: "json_object" } : void 0,
1311
+ stop: stopSequences,
1312
+ seed,
1313
+ ...Object.fromEntries(
1314
+ Object.entries(
1315
+ (_d = providerOptions == null ? void 0 : providerOptions[this.providerOptionsName]) != null ? _d : {}
1316
+ ).filter(
1317
+ ([key]) => !Object.keys(openaiCompatibleProviderOptions.shape).includes(key)
1318
+ )
1319
+ ),
1320
+ reasoning_effort: compatibleOptions.reasoningEffort,
1321
+ verbosity: compatibleOptions.textVerbosity,
1322
+ // messages:
1323
+ messages: convertToOpenAICompatibleChatMessages(prompt),
1324
+ // tools:
1325
+ tools: openaiTools,
1326
+ tool_choice: openaiToolChoice
1327
+ },
1328
+ warnings: [...warnings, ...toolWarnings]
1329
+ };
1330
+ }
1331
+ async doGenerate(options) {
1332
+ var _a15, _b15, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1333
+ const { args, warnings } = await this.getArgs({ ...options });
1334
+ const body = JSON.stringify(args);
1335
+ const {
1336
+ responseHeaders,
1337
+ value: responseBody,
1338
+ rawValue: rawResponse
1339
+ } = await postJsonToApi({
1340
+ url: this.config.url({
1341
+ path: "/chat/completions",
1342
+ modelId: this.modelId
1343
+ }),
1344
+ headers: combineHeaders(this.config.headers(), options.headers),
1345
+ body: args,
1346
+ failedResponseHandler: this.failedResponseHandler,
1347
+ successfulResponseHandler: createJsonResponseHandler(
1348
+ OpenAICompatibleChatResponseSchema
1349
+ ),
1350
+ abortSignal: options.abortSignal,
1351
+ fetch: this.config.fetch
1352
+ });
1353
+ const choice = responseBody.choices[0];
1354
+ const content = [];
1355
+ const text = choice.message.content;
1356
+ if (text != null && text.length > 0) {
1357
+ content.push({ type: "text", text });
1358
+ }
1359
+ const reasoning = (_a15 = choice.message.reasoning_content) != null ? _a15 : choice.message.reasoning;
1360
+ if (reasoning != null && reasoning.length > 0) {
1361
+ content.push({
1362
+ type: "reasoning",
1363
+ text: reasoning
1364
+ });
1365
+ }
1366
+ if (choice.message.tool_calls != null) {
1367
+ for (const toolCall of choice.message.tool_calls) {
1368
+ content.push({
1369
+ type: "tool-call",
1370
+ toolCallId: (_b15 = toolCall.id) != null ? _b15 : generateId(),
1371
+ toolName: toolCall.function.name,
1372
+ input: toolCall.function.arguments
1373
+ });
1374
+ }
1375
+ }
1376
+ const providerMetadata = {
1377
+ [this.providerOptionsName]: {},
1378
+ ...await ((_d = (_c = this.config.metadataExtractor) == null ? void 0 : _c.extractMetadata) == null ? void 0 : _d.call(_c, {
1379
+ parsedBody: rawResponse
1380
+ }))
1381
+ };
1382
+ const completionTokenDetails = (_e = responseBody.usage) == null ? void 0 : _e.completion_tokens_details;
1383
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) {
1384
+ providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens;
1385
+ }
1386
+ if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) {
1387
+ providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens;
1388
+ }
1389
+ return {
1390
+ content,
1391
+ finishReason: mapOpenAICompatibleFinishReason(choice.finish_reason),
1392
+ usage: {
1393
+ inputTokens: (_g = (_f = responseBody.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : void 0,
1394
+ outputTokens: (_i = (_h = responseBody.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : void 0,
1395
+ totalTokens: (_k = (_j = responseBody.usage) == null ? void 0 : _j.total_tokens) != null ? _k : void 0,
1396
+ reasoningTokens: (_n = (_m = (_l = responseBody.usage) == null ? void 0 : _l.completion_tokens_details) == null ? void 0 : _m.reasoning_tokens) != null ? _n : void 0,
1397
+ cachedInputTokens: (_q = (_p = (_o = responseBody.usage) == null ? void 0 : _o.prompt_tokens_details) == null ? void 0 : _p.cached_tokens) != null ? _q : void 0
1398
+ },
1399
+ providerMetadata,
1400
+ request: { body },
1401
+ response: {
1402
+ ...getResponseMetadata(responseBody),
1403
+ headers: responseHeaders,
1404
+ body: rawResponse
1405
+ },
1406
+ warnings
1407
+ };
1408
+ }
1409
+ async doStream(options) {
1410
+ var _a15;
1411
+ const { args, warnings } = await this.getArgs({ ...options });
1412
+ const body = {
1413
+ ...args,
1414
+ stream: true,
1415
+ // only include stream_options when in strict compatibility mode:
1416
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
1417
+ };
1418
+ const metadataExtractor = (_a15 = this.config.metadataExtractor) == null ? void 0 : _a15.createStreamExtractor();
1419
+ const { responseHeaders, value: response } = await postJsonToApi({
1420
+ url: this.config.url({
1421
+ path: "/chat/completions",
1422
+ modelId: this.modelId
1423
+ }),
1424
+ headers: combineHeaders(this.config.headers(), options.headers),
1425
+ body,
1426
+ failedResponseHandler: this.failedResponseHandler,
1427
+ successfulResponseHandler: createEventSourceResponseHandler(
1428
+ this.chunkSchema
1429
+ ),
1430
+ abortSignal: options.abortSignal,
1431
+ fetch: this.config.fetch
1432
+ });
1433
+ const toolCalls = [];
1434
+ let finishReason = "unknown";
1435
+ const usage = {
1436
+ completionTokens: void 0,
1437
+ completionTokensDetails: {
1438
+ reasoningTokens: void 0,
1439
+ acceptedPredictionTokens: void 0,
1440
+ rejectedPredictionTokens: void 0
1441
+ },
1442
+ promptTokens: void 0,
1443
+ promptTokensDetails: {
1444
+ cachedTokens: void 0
1445
+ },
1446
+ totalTokens: void 0
1447
+ };
1448
+ let isFirstChunk = true;
1449
+ const providerOptionsName = this.providerOptionsName;
1450
+ let isActiveReasoning = false;
1451
+ let isActiveText = false;
1452
+ return {
1453
+ stream: response.pipeThrough(
1454
+ new TransformStream({
1455
+ start(controller) {
1456
+ controller.enqueue({ type: "stream-start", warnings });
1457
+ },
1458
+ // TODO we lost type safety on Chunk, most likely due to the error schema. MUST FIX
1459
+ transform(chunk, controller) {
1460
+ var _a22, _b15, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1461
+ if (options.includeRawChunks) {
1462
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1463
+ }
1464
+ if (!chunk.success) {
1465
+ finishReason = "error";
1466
+ controller.enqueue({ type: "error", error: chunk.error });
1467
+ return;
1468
+ }
1469
+ const value = chunk.value;
1470
+ metadataExtractor == null ? void 0 : metadataExtractor.processChunk(chunk.rawValue);
1471
+ if ("error" in value) {
1472
+ finishReason = "error";
1473
+ controller.enqueue({ type: "error", error: value.error.message });
1474
+ return;
1475
+ }
1476
+ if (isFirstChunk) {
1477
+ isFirstChunk = false;
1478
+ controller.enqueue({
1479
+ type: "response-metadata",
1480
+ ...getResponseMetadata(value)
1481
+ });
1482
+ }
1483
+ if (value.usage != null) {
1484
+ const {
1485
+ prompt_tokens,
1486
+ completion_tokens,
1487
+ total_tokens,
1488
+ prompt_tokens_details,
1489
+ completion_tokens_details
1490
+ } = value.usage;
1491
+ usage.promptTokens = prompt_tokens != null ? prompt_tokens : void 0;
1492
+ usage.completionTokens = completion_tokens != null ? completion_tokens : void 0;
1493
+ usage.totalTokens = total_tokens != null ? total_tokens : void 0;
1494
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) {
1495
+ usage.completionTokensDetails.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens;
1496
+ }
1497
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) {
1498
+ usage.completionTokensDetails.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens;
1499
+ }
1500
+ if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) {
1501
+ usage.completionTokensDetails.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens;
1502
+ }
1503
+ if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) {
1504
+ usage.promptTokensDetails.cachedTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens;
1505
+ }
1506
+ }
1507
+ const choice = value.choices[0];
1508
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
1509
+ finishReason = mapOpenAICompatibleFinishReason(
1510
+ choice.finish_reason
1511
+ );
1512
+ }
1513
+ if ((choice == null ? void 0 : choice.delta) == null) {
1514
+ return;
1515
+ }
1516
+ const delta = choice.delta;
1517
+ const reasoningContent = (_a22 = delta.reasoning_content) != null ? _a22 : delta.reasoning;
1518
+ if (reasoningContent) {
1519
+ if (!isActiveReasoning) {
1520
+ controller.enqueue({
1521
+ type: "reasoning-start",
1522
+ id: "reasoning-0"
1523
+ });
1524
+ isActiveReasoning = true;
1525
+ }
1526
+ controller.enqueue({
1527
+ type: "reasoning-delta",
1528
+ id: "reasoning-0",
1529
+ delta: reasoningContent
1530
+ });
1531
+ }
1532
+ if (delta.content) {
1533
+ if (!isActiveText) {
1534
+ controller.enqueue({ type: "text-start", id: "txt-0" });
1535
+ isActiveText = true;
1536
+ }
1537
+ controller.enqueue({
1538
+ type: "text-delta",
1539
+ id: "txt-0",
1540
+ delta: delta.content
1541
+ });
1542
+ }
1543
+ if (delta.tool_calls != null) {
1544
+ for (const toolCallDelta of delta.tool_calls) {
1545
+ const index = toolCallDelta.index;
1546
+ if (toolCalls[index] == null) {
1547
+ if (toolCallDelta.id == null) {
1548
+ throw new InvalidResponseDataError({
1549
+ data: toolCallDelta,
1550
+ message: `Expected 'id' to be a string.`
1551
+ });
1552
+ }
1553
+ if (((_b15 = toolCallDelta.function) == null ? void 0 : _b15.name) == null) {
1554
+ throw new InvalidResponseDataError({
1555
+ data: toolCallDelta,
1556
+ message: `Expected 'function.name' to be a string.`
1557
+ });
1558
+ }
1559
+ controller.enqueue({
1560
+ type: "tool-input-start",
1561
+ id: toolCallDelta.id,
1562
+ toolName: toolCallDelta.function.name
1563
+ });
1564
+ toolCalls[index] = {
1565
+ id: toolCallDelta.id,
1566
+ type: "function",
1567
+ function: {
1568
+ name: toolCallDelta.function.name,
1569
+ arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
1570
+ },
1571
+ hasFinished: false
1572
+ };
1573
+ const toolCall2 = toolCalls[index];
1574
+ if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null) {
1575
+ if (toolCall2.function.arguments.length > 0) {
1576
+ controller.enqueue({
1577
+ type: "tool-input-delta",
1578
+ id: toolCall2.id,
1579
+ delta: toolCall2.function.arguments
1580
+ });
1581
+ }
1582
+ if (isParsableJson(toolCall2.function.arguments)) {
1583
+ controller.enqueue({
1584
+ type: "tool-input-end",
1585
+ id: toolCall2.id
1586
+ });
1587
+ controller.enqueue({
1588
+ type: "tool-call",
1589
+ toolCallId: (_f = toolCall2.id) != null ? _f : generateId(),
1590
+ toolName: toolCall2.function.name,
1591
+ input: toolCall2.function.arguments
1592
+ });
1593
+ toolCall2.hasFinished = true;
1594
+ }
1595
+ }
1596
+ continue;
1597
+ }
1598
+ const toolCall = toolCalls[index];
1599
+ if (toolCall.hasFinished) {
1600
+ continue;
1601
+ }
1602
+ if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) {
1603
+ toolCall.function.arguments += (_i = (_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null ? _i : "";
1604
+ }
1605
+ controller.enqueue({
1606
+ type: "tool-input-delta",
1607
+ id: toolCall.id,
1608
+ delta: (_j = toolCallDelta.function.arguments) != null ? _j : ""
1609
+ });
1610
+ if (((_k = toolCall.function) == null ? void 0 : _k.name) != null && ((_l = toolCall.function) == null ? void 0 : _l.arguments) != null && isParsableJson(toolCall.function.arguments)) {
1611
+ controller.enqueue({
1612
+ type: "tool-input-end",
1613
+ id: toolCall.id
1614
+ });
1615
+ controller.enqueue({
1616
+ type: "tool-call",
1617
+ toolCallId: (_m = toolCall.id) != null ? _m : generateId(),
1618
+ toolName: toolCall.function.name,
1619
+ input: toolCall.function.arguments
1620
+ });
1621
+ toolCall.hasFinished = true;
1622
+ }
1623
+ }
1624
+ }
1625
+ },
1626
+ flush(controller) {
1627
+ var _a22, _b15, _c, _d, _e, _f;
1628
+ if (isActiveReasoning) {
1629
+ controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
1630
+ }
1631
+ if (isActiveText) {
1632
+ controller.enqueue({ type: "text-end", id: "txt-0" });
1633
+ }
1634
+ for (const toolCall of toolCalls.filter(
1635
+ (toolCall2) => !toolCall2.hasFinished
1636
+ )) {
1637
+ controller.enqueue({
1638
+ type: "tool-input-end",
1639
+ id: toolCall.id
1640
+ });
1641
+ controller.enqueue({
1642
+ type: "tool-call",
1643
+ toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(),
1644
+ toolName: toolCall.function.name,
1645
+ input: toolCall.function.arguments
1646
+ });
1647
+ }
1648
+ const providerMetadata = {
1649
+ [providerOptionsName]: {},
1650
+ ...metadataExtractor == null ? void 0 : metadataExtractor.buildMetadata()
1651
+ };
1652
+ if (usage.completionTokensDetails.acceptedPredictionTokens != null) {
1653
+ providerMetadata[providerOptionsName].acceptedPredictionTokens = usage.completionTokensDetails.acceptedPredictionTokens;
1654
+ }
1655
+ if (usage.completionTokensDetails.rejectedPredictionTokens != null) {
1656
+ providerMetadata[providerOptionsName].rejectedPredictionTokens = usage.completionTokensDetails.rejectedPredictionTokens;
1657
+ }
1658
+ controller.enqueue({
1659
+ type: "finish",
1660
+ finishReason,
1661
+ usage: {
1662
+ inputTokens: (_b15 = usage.promptTokens) != null ? _b15 : void 0,
1663
+ outputTokens: (_c = usage.completionTokens) != null ? _c : void 0,
1664
+ totalTokens: (_d = usage.totalTokens) != null ? _d : void 0,
1665
+ reasoningTokens: (_e = usage.completionTokensDetails.reasoningTokens) != null ? _e : void 0,
1666
+ cachedInputTokens: (_f = usage.promptTokensDetails.cachedTokens) != null ? _f : void 0
1667
+ },
1668
+ providerMetadata
1669
+ });
1670
+ }
1671
+ })
1672
+ ),
1673
+ request: { body },
1674
+ response: { headers: responseHeaders }
1675
+ };
1676
+ }
1677
+ };
1678
+ var openaiCompatibleTokenUsageSchema = import_v4.z.object({
1679
+ prompt_tokens: import_v4.z.number().nullish(),
1680
+ completion_tokens: import_v4.z.number().nullish(),
1681
+ total_tokens: import_v4.z.number().nullish(),
1682
+ prompt_tokens_details: import_v4.z.object({
1683
+ cached_tokens: import_v4.z.number().nullish()
1684
+ }).nullish(),
1685
+ completion_tokens_details: import_v4.z.object({
1686
+ reasoning_tokens: import_v4.z.number().nullish(),
1687
+ accepted_prediction_tokens: import_v4.z.number().nullish(),
1688
+ rejected_prediction_tokens: import_v4.z.number().nullish()
1689
+ }).nullish()
1690
+ }).nullish();
1691
+ var OpenAICompatibleChatResponseSchema = import_v4.z.object({
1692
+ id: import_v4.z.string().nullish(),
1693
+ created: import_v4.z.number().nullish(),
1694
+ model: import_v4.z.string().nullish(),
1695
+ choices: import_v4.z.array(
1696
+ import_v4.z.object({
1697
+ message: import_v4.z.object({
1698
+ role: import_v4.z.literal("assistant").nullish(),
1699
+ content: import_v4.z.string().nullish(),
1700
+ reasoning_content: import_v4.z.string().nullish(),
1701
+ reasoning: import_v4.z.string().nullish(),
1702
+ tool_calls: import_v4.z.array(
1703
+ import_v4.z.object({
1704
+ id: import_v4.z.string().nullish(),
1705
+ function: import_v4.z.object({
1706
+ name: import_v4.z.string(),
1707
+ arguments: import_v4.z.string()
1708
+ })
1709
+ })
1710
+ ).nullish()
1711
+ }),
1712
+ finish_reason: import_v4.z.string().nullish()
1713
+ })
1714
+ ),
1715
+ usage: openaiCompatibleTokenUsageSchema
1716
+ });
1717
+ var createOpenAICompatibleChatChunkSchema = (errorSchema) => import_v4.z.union([
1718
+ import_v4.z.object({
1719
+ id: import_v4.z.string().nullish(),
1720
+ created: import_v4.z.number().nullish(),
1721
+ model: import_v4.z.string().nullish(),
1722
+ choices: import_v4.z.array(
1723
+ import_v4.z.object({
1724
+ delta: import_v4.z.object({
1725
+ role: import_v4.z.enum(["assistant"]).nullish(),
1726
+ content: import_v4.z.string().nullish(),
1727
+ // Most openai-compatible models set `reasoning_content`, but some
1728
+ // providers serving `gpt-oss` set `reasoning`. See #7866
1729
+ reasoning_content: import_v4.z.string().nullish(),
1730
+ reasoning: import_v4.z.string().nullish(),
1731
+ tool_calls: import_v4.z.array(
1732
+ import_v4.z.object({
1733
+ index: import_v4.z.number(),
1734
+ id: import_v4.z.string().nullish(),
1735
+ function: import_v4.z.object({
1736
+ name: import_v4.z.string().nullish(),
1737
+ arguments: import_v4.z.string().nullish()
1738
+ })
1739
+ })
1740
+ ).nullish()
1741
+ }).nullish(),
1742
+ finish_reason: import_v4.z.string().nullish()
1743
+ })
1744
+ ),
1745
+ usage: openaiCompatibleTokenUsageSchema
1746
+ }),
1747
+ errorSchema
1748
+ ]);
1749
+ function convertToOpenAICompatibleCompletionPrompt({
1750
+ prompt,
1751
+ user = "user",
1752
+ assistant = "assistant"
1753
+ }) {
1754
+ let text = "";
1755
+ if (prompt[0].role === "system") {
1756
+ text += `${prompt[0].content}
1757
+
1758
+ `;
1759
+ prompt = prompt.slice(1);
1760
+ }
1761
+ for (const { role, content } of prompt) {
1762
+ switch (role) {
1763
+ case "system": {
1764
+ throw new InvalidPromptError({
1765
+ message: "Unexpected system message in prompt: ${content}",
1766
+ prompt
2367
1767
  });
1768
+ }
1769
+ case "user": {
1770
+ const userMessage = content.map((part) => {
1771
+ switch (part.type) {
1772
+ case "text": {
1773
+ return part.text;
1774
+ }
1775
+ }
1776
+ }).filter(Boolean).join("");
1777
+ text += `${user}:
1778
+ ${userMessage}
1779
+
1780
+ `;
2368
1781
  break;
2369
1782
  }
2370
- case "tool":
2371
- for (const result of message.content) {
2372
- if (result.type !== "tool-result") continue;
2373
- let content = "{}";
2374
- const output = result.output;
2375
- if (typeof output === "string") {
2376
- content = output;
2377
- } else if (Array.isArray(output)) {
2378
- const textParts = output.filter((p) => p.type === "text").map((p) => p.text);
2379
- content = textParts.join("");
2380
- } else {
2381
- try {
2382
- content = JSON.stringify(output);
2383
- } catch {
2384
- content = "{}";
1783
+ case "assistant": {
1784
+ const assistantMessage = content.map((part) => {
1785
+ switch (part.type) {
1786
+ case "text": {
1787
+ return part.text;
1788
+ }
1789
+ case "tool-call": {
1790
+ throw new UnsupportedFunctionalityError({
1791
+ functionality: "tool-call messages"
1792
+ });
2385
1793
  }
2386
1794
  }
2387
- messages.push({
2388
- role: "tool",
2389
- tool_call_id: result.toolCallId,
2390
- content
2391
- });
2392
- }
1795
+ }).join("");
1796
+ text += `${assistant}:
1797
+ ${assistantMessage}
1798
+
1799
+ `;
2393
1800
  break;
1801
+ }
1802
+ case "tool": {
1803
+ throw new UnsupportedFunctionalityError({
1804
+ functionality: "tool messages"
1805
+ });
1806
+ }
1807
+ default: {
1808
+ const _exhaustiveCheck = role;
1809
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1810
+ }
2394
1811
  }
2395
1812
  }
2396
- return messages;
1813
+ text += `${assistant}:
1814
+ `;
1815
+ return {
1816
+ prompt: text,
1817
+ stopSequences: [`
1818
+ ${user}:`]
1819
+ };
2397
1820
  }
2398
-
2399
- // src/utils/convert-to-openai-tools.ts
2400
- function convertToOpenAITools(tools) {
2401
- if (!tools || tools.length === 0) return void 0;
2402
- return tools.map((tool) => ({
2403
- type: "function",
2404
- function: {
2405
- name: tool.name,
2406
- description: tool.description,
2407
- parameters: tool.inputSchema
2408
- }
2409
- }));
1821
+ function getResponseMetadata2({
1822
+ id,
1823
+ model,
1824
+ created
1825
+ }) {
1826
+ return {
1827
+ id: id != null ? id : void 0,
1828
+ modelId: model != null ? model : void 0,
1829
+ timestamp: created != null ? new Date(created * 1e3) : void 0
1830
+ };
2410
1831
  }
2411
- function convertToOpenAIToolChoice(toolChoice) {
2412
- if (!toolChoice) return void 0;
2413
- switch (toolChoice.type) {
2414
- case "none":
2415
- return "none";
2416
- case "auto":
2417
- return "auto";
2418
- case "required":
2419
- return "required";
2420
- case "tool":
2421
- if (!toolChoice.toolName) return void 0;
2422
- return {
2423
- type: "function",
2424
- function: { name: toolChoice.toolName }
2425
- };
1832
+ function mapOpenAICompatibleFinishReason2(finishReason) {
1833
+ switch (finishReason) {
1834
+ case "stop":
1835
+ return "stop";
1836
+ case "length":
1837
+ return "length";
1838
+ case "content_filter":
1839
+ return "content-filter";
1840
+ case "function_call":
1841
+ case "tool_calls":
1842
+ return "tool-calls";
2426
1843
  default:
2427
- return void 0;
1844
+ return "unknown";
2428
1845
  }
2429
1846
  }
2430
-
2431
- // src/apertis-chat-language-model.ts
2432
- var ApertisChatLanguageModel = class {
2433
- constructor(modelId, settings, config) {
1847
+ var openaiCompatibleCompletionProviderOptions = import_v45.z.object({
1848
+ /**
1849
+ * Echo back the prompt in addition to the completion.
1850
+ */
1851
+ echo: import_v45.z.boolean().optional(),
1852
+ /**
1853
+ * Modify the likelihood of specified tokens appearing in the completion.
1854
+ *
1855
+ * Accepts a JSON object that maps tokens (specified by their token ID in
1856
+ * the GPT tokenizer) to an associated bias value from -100 to 100.
1857
+ */
1858
+ logitBias: import_v45.z.record(import_v45.z.string(), import_v45.z.number()).optional(),
1859
+ /**
1860
+ * The suffix that comes after a completion of inserted text.
1861
+ */
1862
+ suffix: import_v45.z.string().optional(),
1863
+ /**
1864
+ * A unique identifier representing your end-user, which can help providers to
1865
+ * monitor and detect abuse.
1866
+ */
1867
+ user: import_v45.z.string().optional()
1868
+ });
1869
+ var OpenAICompatibleCompletionLanguageModel = class {
1870
+ // type inferred via constructor
1871
+ constructor(modelId, config) {
1872
+ this.specificationVersion = "v2";
1873
+ var _a15;
2434
1874
  this.modelId = modelId;
2435
- this.settings = settings;
2436
1875
  this.config = config;
1876
+ const errorStructure = (_a15 = config.errorStructure) != null ? _a15 : defaultOpenAICompatibleErrorStructure;
1877
+ this.chunkSchema = createOpenAICompatibleCompletionChunkSchema(
1878
+ errorStructure.errorSchema
1879
+ );
1880
+ this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
2437
1881
  }
2438
- specificationVersion = "v3";
2439
- /**
2440
- * Supported URL patterns for different media types.
2441
- * Supports HTTP(S) image URLs for direct URL passing.
2442
- */
2443
- supportedUrls = {
2444
- "image/*": [/^https?:\/\/.+$/]
2445
- };
2446
1882
  get provider() {
2447
1883
  return this.config.provider;
2448
1884
  }
2449
- async doGenerate(options) {
2450
- const body = this.buildRequestBody(options, false);
2451
- const { value: response } = await postJsonToApi({
2452
- url: `${this.config.baseURL}/chat/completions`,
2453
- headers: this.config.headers(),
2454
- body,
2455
- failedResponseHandler: apertisFailedResponseHandler,
2456
- successfulResponseHandler: createJsonResponseHandler(
2457
- openAIChatResponseSchema
2458
- ),
2459
- fetch: this.config.fetch,
2460
- abortSignal: options.abortSignal
2461
- });
2462
- const choice = response.choices[0];
2463
- const content = [];
2464
- if (choice.message.content) {
2465
- content.push({
2466
- type: "text",
2467
- text: choice.message.content
2468
- });
1885
+ get providerOptionsName() {
1886
+ return this.config.provider.split(".")[0].trim();
1887
+ }
1888
+ get supportedUrls() {
1889
+ var _a15, _b15, _c;
1890
+ return (_c = (_b15 = (_a15 = this.config).supportedUrls) == null ? void 0 : _b15.call(_a15)) != null ? _c : {};
1891
+ }
1892
+ async getArgs({
1893
+ prompt,
1894
+ maxOutputTokens,
1895
+ temperature,
1896
+ topP,
1897
+ topK,
1898
+ frequencyPenalty,
1899
+ presencePenalty,
1900
+ stopSequences: userStopSequences,
1901
+ responseFormat,
1902
+ seed,
1903
+ providerOptions,
1904
+ tools,
1905
+ toolChoice
1906
+ }) {
1907
+ var _a15;
1908
+ const warnings = [];
1909
+ const completionOptions = (_a15 = await parseProviderOptions({
1910
+ provider: this.providerOptionsName,
1911
+ providerOptions,
1912
+ schema: openaiCompatibleCompletionProviderOptions
1913
+ })) != null ? _a15 : {};
1914
+ if (topK != null) {
1915
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
2469
1916
  }
2470
- if (choice.message.tool_calls) {
2471
- for (const tc of choice.message.tool_calls) {
2472
- content.push({
2473
- type: "tool-call",
2474
- toolCallId: tc.id,
2475
- toolName: tc.function.name,
2476
- input: tc.function.arguments
2477
- });
2478
- }
1917
+ if (tools == null ? void 0 : tools.length) {
1918
+ warnings.push({ type: "unsupported-setting", setting: "tools" });
1919
+ }
1920
+ if (toolChoice != null) {
1921
+ warnings.push({ type: "unsupported-setting", setting: "toolChoice" });
1922
+ }
1923
+ if (responseFormat != null && responseFormat.type !== "text") {
1924
+ warnings.push({
1925
+ type: "unsupported-setting",
1926
+ setting: "responseFormat",
1927
+ details: "JSON response format is not supported."
1928
+ });
2479
1929
  }
1930
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt });
1931
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
2480
1932
  return {
2481
- content,
2482
- finishReason: mapApertisFinishReason(choice.finish_reason),
2483
- usage: {
2484
- inputTokens: {
2485
- total: response.usage?.prompt_tokens ?? 0,
2486
- noCache: void 0,
2487
- cacheRead: void 0,
2488
- cacheWrite: void 0
2489
- },
2490
- outputTokens: {
2491
- total: response.usage?.completion_tokens ?? 0,
2492
- text: void 0,
2493
- reasoning: void 0
2494
- }
2495
- },
2496
- warnings: [],
2497
- request: { body }
2498
- };
2499
- }
2500
- async doStream(options) {
2501
- const body = this.buildRequestBody(options, true);
2502
- const { value: response } = await postJsonToApi({
2503
- url: `${this.config.baseURL}/chat/completions`,
2504
- headers: this.config.headers(),
2505
- body,
2506
- failedResponseHandler: apertisFailedResponseHandler,
2507
- successfulResponseHandler: createEventSourceResponseHandler(
2508
- openAIChatChunkSchema
2509
- ),
2510
- fetch: this.config.fetch,
2511
- abortSignal: options.abortSignal
2512
- });
2513
- const toolCallBuffers = /* @__PURE__ */ new Map();
2514
- let textId = null;
2515
- const transformStream = new TransformStream({
2516
- transform(parseResult, controller) {
2517
- if (!parseResult.success) {
2518
- return;
2519
- }
2520
- const chunk = parseResult.value;
2521
- const choice = chunk.choices[0];
2522
- if (!choice) return;
2523
- if (choice.delta.content) {
2524
- if (!textId) {
2525
- textId = generateId();
2526
- controller.enqueue({
2527
- type: "text-start",
2528
- id: textId
2529
- });
2530
- }
2531
- controller.enqueue({
2532
- type: "text-delta",
2533
- id: textId,
2534
- delta: choice.delta.content
2535
- });
2536
- }
2537
- if (choice.delta.tool_calls) {
2538
- for (const tc of choice.delta.tool_calls) {
2539
- let buffer = toolCallBuffers.get(tc.index);
2540
- if (!buffer) {
2541
- buffer = { id: tc.id ?? generateId(), name: "", arguments: "" };
2542
- toolCallBuffers.set(tc.index, buffer);
2543
- }
2544
- if (tc.id) buffer.id = tc.id;
2545
- if (tc.function?.name) buffer.name += tc.function.name;
2546
- if (tc.function?.arguments)
2547
- buffer.arguments += tc.function.arguments;
2548
- }
2549
- }
2550
- if (choice.finish_reason) {
2551
- if (textId) {
2552
- controller.enqueue({
2553
- type: "text-end",
2554
- id: textId
2555
- });
2556
- }
2557
- for (const [, buffer] of toolCallBuffers) {
2558
- if (buffer.name) {
2559
- controller.enqueue({
2560
- type: "tool-call",
2561
- toolCallId: buffer.id,
2562
- toolName: buffer.name,
2563
- input: buffer.arguments
2564
- });
2565
- }
2566
- }
2567
- toolCallBuffers.clear();
2568
- controller.enqueue({
2569
- type: "finish",
2570
- finishReason: mapApertisFinishReason(choice.finish_reason),
2571
- usage: {
2572
- inputTokens: {
2573
- total: chunk.usage?.prompt_tokens ?? 0,
2574
- noCache: void 0,
2575
- cacheRead: void 0,
2576
- cacheWrite: void 0
2577
- },
2578
- outputTokens: {
2579
- total: chunk.usage?.completion_tokens ?? 0,
2580
- text: void 0,
2581
- reasoning: void 0
2582
- }
2583
- }
2584
- });
2585
- }
1933
+ args: {
1934
+ // model id:
1935
+ model: this.modelId,
1936
+ // model specific settings:
1937
+ echo: completionOptions.echo,
1938
+ logit_bias: completionOptions.logitBias,
1939
+ suffix: completionOptions.suffix,
1940
+ user: completionOptions.user,
1941
+ // standardized settings:
1942
+ max_tokens: maxOutputTokens,
1943
+ temperature,
1944
+ top_p: topP,
1945
+ frequency_penalty: frequencyPenalty,
1946
+ presence_penalty: presencePenalty,
1947
+ seed,
1948
+ ...providerOptions == null ? void 0 : providerOptions[this.providerOptionsName],
1949
+ // prompt:
1950
+ prompt: completionPrompt,
1951
+ // stop sequences:
1952
+ stop: stop.length > 0 ? stop : void 0
2586
1953
  },
2587
- flush(controller) {
2588
- if (textId) {
2589
- controller.enqueue({
2590
- type: "text-end",
2591
- id: textId
2592
- });
2593
- }
2594
- for (const [, buffer] of toolCallBuffers) {
2595
- if (buffer.name) {
2596
- controller.enqueue({
2597
- type: "tool-call",
2598
- toolCallId: buffer.id,
2599
- toolName: buffer.name,
2600
- input: buffer.arguments
2601
- });
2602
- }
2603
- }
2604
- }
2605
- });
2606
- return {
2607
- stream: response.pipeThrough(transformStream),
2608
- request: { body }
2609
- };
2610
- }
2611
- buildRequestBody(options, stream) {
2612
- const tools = this.filterFunctionTools(options.tools);
2613
- const responseFormat = options.responseFormat?.type === "json" ? { type: "json_object" } : void 0;
2614
- const body = {
2615
- model: this.modelId,
2616
- messages: convertToOpenAIMessages(options.prompt),
2617
- stream
1954
+ warnings
2618
1955
  };
2619
- if (stream) body.stream_options = { include_usage: true };
2620
- if (options.temperature !== void 0)
2621
- body.temperature = options.temperature;
2622
- if (options.maxOutputTokens !== void 0)
2623
- body.max_tokens = options.maxOutputTokens;
2624
- if (options.topP !== void 0) body.top_p = options.topP;
2625
- if (options.frequencyPenalty !== void 0)
2626
- body.frequency_penalty = options.frequencyPenalty;
2627
- if (options.presencePenalty !== void 0)
2628
- body.presence_penalty = options.presencePenalty;
2629
- if (options.stopSequences !== void 0) body.stop = options.stopSequences;
2630
- if (options.seed !== void 0) body.seed = options.seed;
2631
- const convertedTools = convertToOpenAITools(tools);
2632
- if (convertedTools !== void 0) body.tools = convertedTools;
2633
- const convertedToolChoice = convertToOpenAIToolChoice(options.toolChoice);
2634
- if (convertedToolChoice !== void 0)
2635
- body.tool_choice = convertedToolChoice;
2636
- if (responseFormat !== void 0) body.response_format = responseFormat;
2637
- if (this.settings.user !== void 0) body.user = this.settings.user;
2638
- if (this.settings.logprobs !== void 0)
2639
- body.logprobs = this.settings.logprobs;
2640
- if (this.settings.topLogprobs !== void 0)
2641
- body.top_logprobs = this.settings.topLogprobs;
2642
- return body;
2643
- }
2644
- filterFunctionTools(tools) {
2645
- if (!tools) return void 0;
2646
- return tools.filter(
2647
- (tool) => tool.type === "function"
2648
- );
2649
- }
2650
- };
2651
-
2652
- // src/apertis-chat-language-model-v2.ts
2653
- var ApertisChatLanguageModelV2 = class {
2654
- constructor(modelId, settings, config) {
2655
- this.modelId = modelId;
2656
- this.settings = settings;
2657
- this.config = config;
2658
- }
2659
- specificationVersion = "v2";
2660
- supportedUrls = {
2661
- "image/*": [/^https?:\/\/.+$/]
2662
- };
2663
- get provider() {
2664
- return this.config.provider;
2665
1956
  }
2666
1957
  async doGenerate(options) {
2667
- const body = this.buildRequestBody(options, false);
2668
- const { value: response } = await postJsonToApi({
2669
- url: `${this.config.baseURL}/chat/completions`,
2670
- headers: this.config.headers(),
2671
- body,
2672
- failedResponseHandler: apertisFailedResponseHandler,
1958
+ var _a15, _b15, _c, _d, _e, _f;
1959
+ const { args, warnings } = await this.getArgs(options);
1960
+ const {
1961
+ responseHeaders,
1962
+ value: response,
1963
+ rawValue: rawResponse
1964
+ } = await postJsonToApi({
1965
+ url: this.config.url({
1966
+ path: "/completions",
1967
+ modelId: this.modelId
1968
+ }),
1969
+ headers: combineHeaders(this.config.headers(), options.headers),
1970
+ body: args,
1971
+ failedResponseHandler: this.failedResponseHandler,
2673
1972
  successfulResponseHandler: createJsonResponseHandler(
2674
- openAIChatResponseSchema
1973
+ openaiCompatibleCompletionResponseSchema
2675
1974
  ),
2676
- fetch: this.config.fetch,
2677
- abortSignal: options.abortSignal
1975
+ abortSignal: options.abortSignal,
1976
+ fetch: this.config.fetch
2678
1977
  });
2679
1978
  const choice = response.choices[0];
2680
1979
  const content = [];
2681
- if (choice.message.content) {
2682
- content.push({
2683
- type: "text",
2684
- text: choice.message.content
2685
- });
2686
- }
2687
- if (choice.message.tool_calls) {
2688
- for (const tc of choice.message.tool_calls) {
2689
- content.push({
2690
- type: "tool-call",
2691
- toolCallId: tc.id,
2692
- toolName: tc.function.name,
2693
- input: tc.function.arguments
2694
- });
2695
- }
1980
+ if (choice.text != null && choice.text.length > 0) {
1981
+ content.push({ type: "text", text: choice.text });
2696
1982
  }
2697
1983
  return {
2698
1984
  content,
2699
- finishReason: mapApertisFinishReasonV2(choice.finish_reason),
2700
1985
  usage: {
2701
- inputTokens: response.usage?.prompt_tokens ?? 0,
2702
- outputTokens: response.usage?.completion_tokens ?? 0,
2703
- totalTokens: response.usage?.total_tokens ?? void 0
1986
+ inputTokens: (_b15 = (_a15 = response.usage) == null ? void 0 : _a15.prompt_tokens) != null ? _b15 : void 0,
1987
+ outputTokens: (_d = (_c = response.usage) == null ? void 0 : _c.completion_tokens) != null ? _d : void 0,
1988
+ totalTokens: (_f = (_e = response.usage) == null ? void 0 : _e.total_tokens) != null ? _f : void 0
2704
1989
  },
2705
- warnings: [],
2706
- request: { body }
1990
+ finishReason: mapOpenAICompatibleFinishReason2(choice.finish_reason),
1991
+ request: { body: args },
1992
+ response: {
1993
+ ...getResponseMetadata2(response),
1994
+ headers: responseHeaders,
1995
+ body: rawResponse
1996
+ },
1997
+ warnings
2707
1998
  };
2708
1999
  }
2709
2000
  async doStream(options) {
2710
- const body = this.buildRequestBody(options, true);
2711
- const { value: response } = await postJsonToApi({
2712
- url: `${this.config.baseURL}/chat/completions`,
2713
- headers: this.config.headers(),
2001
+ const { args, warnings } = await this.getArgs(options);
2002
+ const body = {
2003
+ ...args,
2004
+ stream: true,
2005
+ // only include stream_options when in strict compatibility mode:
2006
+ stream_options: this.config.includeUsage ? { include_usage: true } : void 0
2007
+ };
2008
+ const { responseHeaders, value: response } = await postJsonToApi({
2009
+ url: this.config.url({
2010
+ path: "/completions",
2011
+ modelId: this.modelId
2012
+ }),
2013
+ headers: combineHeaders(this.config.headers(), options.headers),
2714
2014
  body,
2715
- failedResponseHandler: apertisFailedResponseHandler,
2015
+ failedResponseHandler: this.failedResponseHandler,
2716
2016
  successfulResponseHandler: createEventSourceResponseHandler(
2717
- openAIChatChunkSchema
2017
+ this.chunkSchema
2718
2018
  ),
2719
- fetch: this.config.fetch,
2720
- abortSignal: options.abortSignal
2019
+ abortSignal: options.abortSignal,
2020
+ fetch: this.config.fetch
2721
2021
  });
2722
- const toolCallBuffers = /* @__PURE__ */ new Map();
2723
- let textId = null;
2724
- const transformStream = new TransformStream({
2725
- transform(parseResult, controller) {
2726
- if (!parseResult.success) {
2727
- return;
2728
- }
2729
- const chunk = parseResult.value;
2730
- const choice = chunk.choices[0];
2731
- if (!choice) return;
2732
- if (choice.delta.content) {
2733
- if (!textId) {
2734
- textId = generateId();
2735
- controller.enqueue({
2736
- type: "text-start",
2737
- id: textId
2738
- });
2739
- }
2740
- controller.enqueue({
2741
- type: "text-delta",
2742
- id: textId,
2743
- delta: choice.delta.content
2744
- });
2745
- }
2746
- if (choice.delta.tool_calls) {
2747
- for (const tc of choice.delta.tool_calls) {
2748
- let buffer = toolCallBuffers.get(tc.index);
2749
- if (!buffer) {
2750
- buffer = {
2751
- id: tc.id ?? generateId(),
2752
- name: "",
2753
- arguments: ""
2754
- };
2755
- toolCallBuffers.set(tc.index, buffer);
2022
+ let finishReason = "unknown";
2023
+ const usage = {
2024
+ inputTokens: void 0,
2025
+ outputTokens: void 0,
2026
+ totalTokens: void 0
2027
+ };
2028
+ let isFirstChunk = true;
2029
+ return {
2030
+ stream: response.pipeThrough(
2031
+ new TransformStream({
2032
+ start(controller) {
2033
+ controller.enqueue({ type: "stream-start", warnings });
2034
+ },
2035
+ transform(chunk, controller) {
2036
+ var _a15, _b15, _c;
2037
+ if (options.includeRawChunks) {
2038
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2756
2039
  }
2757
- if (tc.id) buffer.id = tc.id;
2758
- if (tc.function?.name) buffer.name += tc.function.name;
2759
- if (tc.function?.arguments)
2760
- buffer.arguments += tc.function.arguments;
2761
- }
2762
- }
2763
- if (choice.finish_reason) {
2764
- if (textId) {
2765
- controller.enqueue({
2766
- type: "text-end",
2767
- id: textId
2768
- });
2769
- }
2770
- for (const [, buffer] of toolCallBuffers) {
2771
- if (buffer.name) {
2040
+ if (!chunk.success) {
2041
+ finishReason = "error";
2042
+ controller.enqueue({ type: "error", error: chunk.error });
2043
+ return;
2044
+ }
2045
+ const value = chunk.value;
2046
+ if ("error" in value) {
2047
+ finishReason = "error";
2048
+ controller.enqueue({ type: "error", error: value.error });
2049
+ return;
2050
+ }
2051
+ if (isFirstChunk) {
2052
+ isFirstChunk = false;
2772
2053
  controller.enqueue({
2773
- type: "tool-call",
2774
- toolCallId: buffer.id,
2775
- toolName: buffer.name,
2776
- input: buffer.arguments
2054
+ type: "response-metadata",
2055
+ ...getResponseMetadata2(value)
2056
+ });
2057
+ controller.enqueue({
2058
+ type: "text-start",
2059
+ id: "0"
2777
2060
  });
2778
2061
  }
2779
- }
2780
- toolCallBuffers.clear();
2781
- controller.enqueue({
2782
- type: "finish",
2783
- finishReason: mapApertisFinishReasonV2(choice.finish_reason),
2784
- usage: {
2785
- inputTokens: chunk.usage?.prompt_tokens ?? 0,
2786
- outputTokens: chunk.usage?.completion_tokens ?? 0,
2787
- totalTokens: void 0
2062
+ if (value.usage != null) {
2063
+ usage.inputTokens = (_a15 = value.usage.prompt_tokens) != null ? _a15 : void 0;
2064
+ usage.outputTokens = (_b15 = value.usage.completion_tokens) != null ? _b15 : void 0;
2065
+ usage.totalTokens = (_c = value.usage.total_tokens) != null ? _c : void 0;
2066
+ }
2067
+ const choice = value.choices[0];
2068
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
2069
+ finishReason = mapOpenAICompatibleFinishReason2(
2070
+ choice.finish_reason
2071
+ );
2072
+ }
2073
+ if ((choice == null ? void 0 : choice.text) != null) {
2074
+ controller.enqueue({
2075
+ type: "text-delta",
2076
+ id: "0",
2077
+ delta: choice.text
2078
+ });
2079
+ }
2080
+ },
2081
+ flush(controller) {
2082
+ if (!isFirstChunk) {
2083
+ controller.enqueue({ type: "text-end", id: "0" });
2788
2084
  }
2789
- });
2790
- }
2791
- },
2792
- flush(controller) {
2793
- if (textId) {
2794
- controller.enqueue({
2795
- type: "text-end",
2796
- id: textId
2797
- });
2798
- }
2799
- for (const [, buffer] of toolCallBuffers) {
2800
- if (buffer.name) {
2801
2085
  controller.enqueue({
2802
- type: "tool-call",
2803
- toolCallId: buffer.id,
2804
- toolName: buffer.name,
2805
- input: buffer.arguments
2086
+ type: "finish",
2087
+ finishReason,
2088
+ usage
2806
2089
  });
2807
2090
  }
2808
- }
2809
- }
2810
- });
2811
- return {
2812
- stream: response.pipeThrough(transformStream),
2813
- request: { body }
2814
- };
2815
- }
2816
- buildRequestBody(options, stream) {
2817
- const tools = this.filterFunctionTools(options.tools);
2818
- const responseFormat = options.responseFormat?.type === "json" ? { type: "json_object" } : void 0;
2819
- const body = {
2820
- model: this.modelId,
2821
- messages: convertToOpenAIMessages(options.prompt),
2822
- stream
2091
+ })
2092
+ ),
2093
+ request: { body },
2094
+ response: { headers: responseHeaders }
2823
2095
  };
2824
- if (stream) body.stream_options = { include_usage: true };
2825
- if (options.temperature !== void 0)
2826
- body.temperature = options.temperature;
2827
- if (options.maxOutputTokens !== void 0)
2828
- body.max_tokens = options.maxOutputTokens;
2829
- if (options.topP !== void 0) body.top_p = options.topP;
2830
- if (options.frequencyPenalty !== void 0)
2831
- body.frequency_penalty = options.frequencyPenalty;
2832
- if (options.presencePenalty !== void 0)
2833
- body.presence_penalty = options.presencePenalty;
2834
- if (options.stopSequences !== void 0) body.stop = options.stopSequences;
2835
- if (options.seed !== void 0) body.seed = options.seed;
2836
- const convertedTools = convertToOpenAITools(tools);
2837
- if (convertedTools !== void 0) body.tools = convertedTools;
2838
- const convertedToolChoice = convertToOpenAIToolChoice(options.toolChoice);
2839
- if (convertedToolChoice !== void 0)
2840
- body.tool_choice = convertedToolChoice;
2841
- if (responseFormat !== void 0) body.response_format = responseFormat;
2842
- if (this.settings.user !== void 0) body.user = this.settings.user;
2843
- if (this.settings.logprobs !== void 0)
2844
- body.logprobs = this.settings.logprobs;
2845
- if (this.settings.topLogprobs !== void 0)
2846
- body.top_logprobs = this.settings.topLogprobs;
2847
- return body;
2848
- }
2849
- filterFunctionTools(tools) {
2850
- if (!tools) return void 0;
2851
- return tools.filter(
2852
- (tool) => tool.type === "function"
2853
- );
2854
2096
  }
2855
2097
  };
2856
-
2857
- // src/schemas/embedding-response.ts
2858
- var import_zod3 = require("zod");
2859
- var openAIEmbeddingResponseSchema = import_zod3.z.object({
2860
- object: import_zod3.z.literal("list").optional(),
2861
- data: import_zod3.z.array(
2862
- import_zod3.z.object({
2863
- object: import_zod3.z.literal("embedding").optional(),
2864
- embedding: import_zod3.z.array(import_zod3.z.number()),
2865
- index: import_zod3.z.number()
2098
+ var usageSchema = import_v44.z.object({
2099
+ prompt_tokens: import_v44.z.number(),
2100
+ completion_tokens: import_v44.z.number(),
2101
+ total_tokens: import_v44.z.number()
2102
+ });
2103
+ var openaiCompatibleCompletionResponseSchema = import_v44.z.object({
2104
+ id: import_v44.z.string().nullish(),
2105
+ created: import_v44.z.number().nullish(),
2106
+ model: import_v44.z.string().nullish(),
2107
+ choices: import_v44.z.array(
2108
+ import_v44.z.object({
2109
+ text: import_v44.z.string(),
2110
+ finish_reason: import_v44.z.string()
2866
2111
  })
2867
2112
  ),
2868
- model: import_zod3.z.string().optional(),
2869
- usage: import_zod3.z.object({
2870
- prompt_tokens: import_zod3.z.number(),
2871
- total_tokens: import_zod3.z.number()
2872
- }).optional()
2113
+ usage: usageSchema.nullish()
2873
2114
  });
2874
-
2875
- // src/apertis-embedding-model.ts
2876
- var ApertisEmbeddingModel = class {
2877
- constructor(modelId, settings, config) {
2115
+ var createOpenAICompatibleCompletionChunkSchema = (errorSchema) => import_v44.z.union([
2116
+ import_v44.z.object({
2117
+ id: import_v44.z.string().nullish(),
2118
+ created: import_v44.z.number().nullish(),
2119
+ model: import_v44.z.string().nullish(),
2120
+ choices: import_v44.z.array(
2121
+ import_v44.z.object({
2122
+ text: import_v44.z.string(),
2123
+ finish_reason: import_v44.z.string().nullish(),
2124
+ index: import_v44.z.number()
2125
+ })
2126
+ ),
2127
+ usage: usageSchema.nullish()
2128
+ }),
2129
+ errorSchema
2130
+ ]);
2131
+ var openaiCompatibleEmbeddingProviderOptions = import_v47.z.object({
2132
+ /**
2133
+ * The number of dimensions the resulting output embeddings should have.
2134
+ * Only supported in text-embedding-3 and later models.
2135
+ */
2136
+ dimensions: import_v47.z.number().optional(),
2137
+ /**
2138
+ * A unique identifier representing your end-user, which can help providers to
2139
+ * monitor and detect abuse.
2140
+ */
2141
+ user: import_v47.z.string().optional()
2142
+ });
2143
+ var OpenAICompatibleEmbeddingModel = class {
2144
+ constructor(modelId, config) {
2145
+ this.specificationVersion = "v2";
2878
2146
  this.modelId = modelId;
2879
- this.settings = settings;
2880
2147
  this.config = config;
2881
- this.maxEmbeddingsPerCall = settings.maxEmbeddingsPerCall ?? 2048;
2882
- this.supportsParallelCalls = settings.supportsParallelCalls ?? true;
2883
2148
  }
2884
- specificationVersion = "v3";
2885
- maxEmbeddingsPerCall;
2886
- supportsParallelCalls;
2887
2149
  get provider() {
2888
2150
  return this.config.provider;
2889
2151
  }
2890
- async doEmbed(options) {
2891
- const body = {
2892
- model: this.modelId,
2893
- input: options.values,
2894
- encoding_format: "float"
2895
- };
2896
- if (this.settings.dimensions !== void 0) {
2897
- body.dimensions = this.settings.dimensions;
2898
- }
2899
- if (this.settings.user !== void 0) {
2900
- body.user = this.settings.user;
2152
+ get maxEmbeddingsPerCall() {
2153
+ var _a15;
2154
+ return (_a15 = this.config.maxEmbeddingsPerCall) != null ? _a15 : 2048;
2155
+ }
2156
+ get supportsParallelCalls() {
2157
+ var _a15;
2158
+ return (_a15 = this.config.supportsParallelCalls) != null ? _a15 : true;
2159
+ }
2160
+ get providerOptionsName() {
2161
+ return this.config.provider.split(".")[0].trim();
2162
+ }
2163
+ async doEmbed({
2164
+ values,
2165
+ headers,
2166
+ abortSignal,
2167
+ providerOptions
2168
+ }) {
2169
+ var _a15, _b15, _c;
2170
+ const compatibleOptions = Object.assign(
2171
+ (_a15 = await parseProviderOptions({
2172
+ provider: "openai-compatible",
2173
+ providerOptions,
2174
+ schema: openaiCompatibleEmbeddingProviderOptions
2175
+ })) != null ? _a15 : {},
2176
+ (_b15 = await parseProviderOptions({
2177
+ provider: this.providerOptionsName,
2178
+ providerOptions,
2179
+ schema: openaiCompatibleEmbeddingProviderOptions
2180
+ })) != null ? _b15 : {}
2181
+ );
2182
+ if (values.length > this.maxEmbeddingsPerCall) {
2183
+ throw new TooManyEmbeddingValuesForCallError({
2184
+ provider: this.provider,
2185
+ modelId: this.modelId,
2186
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
2187
+ values
2188
+ });
2901
2189
  }
2902
- const { value: response } = await postJsonToApi({
2903
- url: `${this.config.baseURL}/embeddings`,
2904
- headers: this.config.headers(),
2905
- body,
2906
- failedResponseHandler: apertisFailedResponseHandler,
2190
+ const {
2191
+ responseHeaders,
2192
+ value: response,
2193
+ rawValue
2194
+ } = await postJsonToApi({
2195
+ url: this.config.url({
2196
+ path: "/embeddings",
2197
+ modelId: this.modelId
2198
+ }),
2199
+ headers: combineHeaders(this.config.headers(), headers),
2200
+ body: {
2201
+ model: this.modelId,
2202
+ input: values,
2203
+ encoding_format: "float",
2204
+ dimensions: compatibleOptions.dimensions,
2205
+ user: compatibleOptions.user
2206
+ },
2207
+ failedResponseHandler: createJsonErrorResponseHandler(
2208
+ (_c = this.config.errorStructure) != null ? _c : defaultOpenAICompatibleErrorStructure
2209
+ ),
2907
2210
  successfulResponseHandler: createJsonResponseHandler(
2908
- openAIEmbeddingResponseSchema
2211
+ openaiTextEmbeddingResponseSchema
2909
2212
  ),
2910
- fetch: this.config.fetch,
2911
- abortSignal: options.abortSignal
2213
+ abortSignal,
2214
+ fetch: this.config.fetch
2912
2215
  });
2913
2216
  return {
2914
2217
  embeddings: response.data.map((item) => item.embedding),
2915
2218
  usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
2916
- warnings: []
2219
+ providerMetadata: response.providerMetadata,
2220
+ response: { headers: responseHeaders, body: rawValue }
2917
2221
  };
2918
2222
  }
2919
2223
  };
2920
-
2921
- // src/apertis-embedding-model-v2.ts
2922
- var ApertisEmbeddingModelV2 = class {
2923
- constructor(modelId, settings, config) {
2224
+ var openaiTextEmbeddingResponseSchema = import_v46.z.object({
2225
+ data: import_v46.z.array(import_v46.z.object({ embedding: import_v46.z.array(import_v46.z.number()) })),
2226
+ usage: import_v46.z.object({ prompt_tokens: import_v46.z.number() }).nullish(),
2227
+ providerMetadata: import_v46.z.record(import_v46.z.string(), import_v46.z.record(import_v46.z.string(), import_v46.z.any())).optional()
2228
+ });
2229
+ var OpenAICompatibleImageModel = class {
2230
+ constructor(modelId, config) {
2924
2231
  this.modelId = modelId;
2925
- this.settings = settings;
2926
2232
  this.config = config;
2927
- this.maxEmbeddingsPerCall = settings.maxEmbeddingsPerCall ?? 2048;
2928
- this.supportsParallelCalls = settings.supportsParallelCalls ?? true;
2233
+ this.specificationVersion = "v2";
2234
+ this.maxImagesPerCall = 10;
2929
2235
  }
2930
- specificationVersion = "v2";
2931
- maxEmbeddingsPerCall;
2932
- supportsParallelCalls;
2933
2236
  get provider() {
2934
2237
  return this.config.provider;
2935
2238
  }
2936
- async doEmbed(options) {
2937
- const body = {
2938
- model: this.modelId,
2939
- input: options.values,
2940
- encoding_format: "float"
2941
- };
2942
- if (this.settings.dimensions !== void 0) {
2943
- body.dimensions = this.settings.dimensions;
2239
+ async doGenerate({
2240
+ prompt,
2241
+ n,
2242
+ size,
2243
+ aspectRatio,
2244
+ seed,
2245
+ providerOptions,
2246
+ headers,
2247
+ abortSignal
2248
+ }) {
2249
+ var _a15, _b15, _c, _d, _e;
2250
+ const warnings = [];
2251
+ if (aspectRatio != null) {
2252
+ warnings.push({
2253
+ type: "unsupported-setting",
2254
+ setting: "aspectRatio",
2255
+ details: "This model does not support aspect ratio. Use `size` instead."
2256
+ });
2944
2257
  }
2945
- if (this.settings.user !== void 0) {
2946
- body.user = this.settings.user;
2258
+ if (seed != null) {
2259
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
2947
2260
  }
2948
- const { value: response } = await postJsonToApi({
2949
- url: `${this.config.baseURL}/embeddings`,
2950
- headers: this.config.headers(),
2951
- body,
2952
- failedResponseHandler: apertisFailedResponseHandler,
2261
+ const currentDate = (_c = (_b15 = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b15.call(_a15)) != null ? _c : /* @__PURE__ */ new Date();
2262
+ const { value: response, responseHeaders } = await postJsonToApi({
2263
+ url: this.config.url({
2264
+ path: "/images/generations",
2265
+ modelId: this.modelId
2266
+ }),
2267
+ headers: combineHeaders(this.config.headers(), headers),
2268
+ body: {
2269
+ model: this.modelId,
2270
+ prompt,
2271
+ n,
2272
+ size,
2273
+ ...(_d = providerOptions.openai) != null ? _d : {},
2274
+ response_format: "b64_json"
2275
+ },
2276
+ failedResponseHandler: createJsonErrorResponseHandler(
2277
+ (_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure
2278
+ ),
2953
2279
  successfulResponseHandler: createJsonResponseHandler(
2954
- openAIEmbeddingResponseSchema
2280
+ openaiCompatibleImageResponseSchema
2955
2281
  ),
2956
- fetch: this.config.fetch,
2957
- abortSignal: options.abortSignal
2282
+ abortSignal,
2283
+ fetch: this.config.fetch
2958
2284
  });
2959
2285
  return {
2960
- embeddings: response.data.map((item) => item.embedding),
2961
- usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0
2286
+ images: response.data.map((item) => item.b64_json),
2287
+ warnings,
2288
+ response: {
2289
+ timestamp: currentDate,
2290
+ modelId: this.modelId,
2291
+ headers: responseHeaders
2292
+ }
2962
2293
  };
2963
2294
  }
2964
2295
  };
2965
-
2966
- // src/apertis-provider.ts
2967
- function initializeProvider(options = {}) {
2968
- const baseURL = withoutTrailingSlash(options.baseURL) ?? "https://api.apertis.ai/v1";
2969
- const getHeaders = () => ({
2970
- ...options.headers,
2971
- Authorization: `Bearer ${loadApiKey({
2972
- apiKey: options.apiKey,
2973
- environmentVariableName: "APERTIS_API_KEY",
2974
- description: "Apertis API key"
2975
- })}`,
2976
- "Content-Type": "application/json"
2977
- });
2978
- return { baseURL, getHeaders, fetch: options.fetch };
2979
- }
2980
- function createApertis(options = {}) {
2981
- const { baseURL, getHeaders, fetch: fetchImpl } = initializeProvider(options);
2982
- const createChatModel = (modelId, settings = {}) => new ApertisChatLanguageModelV2(modelId, settings, {
2983
- provider: "apertis.chat",
2984
- baseURL,
2296
+ var openaiCompatibleImageResponseSchema = import_v48.z.object({
2297
+ data: import_v48.z.array(import_v48.z.object({ b64_json: import_v48.z.string() }))
2298
+ });
2299
+ var VERSION2 = true ? "1.0.30" : "0.0.0-test";
2300
+ function createOpenAICompatible(options) {
2301
+ const baseURL = withoutTrailingSlash(options.baseURL);
2302
+ const providerName = options.name;
2303
+ const headers = {
2304
+ ...options.apiKey && { Authorization: `Bearer ${options.apiKey}` },
2305
+ ...options.headers
2306
+ };
2307
+ const getHeaders = () => withUserAgentSuffix(headers, `ai-sdk/openai-compatible/${VERSION2}`);
2308
+ const getCommonModelConfig = (modelType) => ({
2309
+ provider: `${providerName}.${modelType}`,
2310
+ url: ({ path }) => {
2311
+ const url = new URL(`${baseURL}${path}`);
2312
+ if (options.queryParams) {
2313
+ url.search = new URLSearchParams(options.queryParams).toString();
2314
+ }
2315
+ return url.toString();
2316
+ },
2985
2317
  headers: getHeaders,
2986
- fetch: fetchImpl
2318
+ fetch: options.fetch
2987
2319
  });
2988
- const createEmbeddingModel = (modelId, settings = {}) => new ApertisEmbeddingModelV2(modelId, settings, {
2989
- provider: "apertis.embedding",
2990
- baseURL,
2991
- headers: getHeaders,
2992
- fetch: fetchImpl
2320
+ const createLanguageModel = (modelId) => createChatModel(modelId);
2321
+ const createChatModel = (modelId) => new OpenAICompatibleChatLanguageModel(modelId, {
2322
+ ...getCommonModelConfig("chat"),
2323
+ includeUsage: options.includeUsage,
2324
+ supportsStructuredOutputs: options.supportsStructuredOutputs
2993
2325
  });
2994
- const provider = Object.assign(
2995
- (modelId, settings) => createChatModel(modelId, settings),
2996
- {
2997
- specificationVersion: "v2",
2998
- chat: createChatModel,
2999
- languageModel: (modelId) => createChatModel(modelId),
3000
- textEmbeddingModel: createEmbeddingModel,
3001
- imageModel: () => {
3002
- throw new Error("Image models are not supported by Apertis");
3003
- }
3004
- }
3005
- );
3006
- return provider;
3007
- }
3008
- function createApertisV3(options = {}) {
3009
- const { baseURL, getHeaders, fetch: fetchImpl } = initializeProvider(options);
3010
- const createChatModel = (modelId, settings = {}) => new ApertisChatLanguageModel(modelId, settings, {
3011
- provider: "apertis.chat",
3012
- baseURL,
3013
- headers: getHeaders,
3014
- fetch: fetchImpl
2326
+ const createCompletionModel = (modelId) => new OpenAICompatibleCompletionLanguageModel(modelId, {
2327
+ ...getCommonModelConfig("completion"),
2328
+ includeUsage: options.includeUsage
3015
2329
  });
3016
- const createEmbeddingModel = (modelId, settings = {}) => new ApertisEmbeddingModel(modelId, settings, {
3017
- provider: "apertis.embedding",
3018
- baseURL,
3019
- headers: getHeaders,
3020
- fetch: fetchImpl
2330
+ const createEmbeddingModel = (modelId) => new OpenAICompatibleEmbeddingModel(modelId, {
2331
+ ...getCommonModelConfig("embedding")
3021
2332
  });
3022
- const provider = Object.assign(
3023
- (modelId, settings) => createChatModel(modelId, settings),
3024
- {
3025
- specificationVersion: "v3",
3026
- chat: createChatModel,
3027
- languageModel: (modelId) => createChatModel(modelId),
3028
- embeddingModel: (modelId) => createEmbeddingModel(modelId),
3029
- textEmbeddingModel: createEmbeddingModel,
3030
- imageModel: () => {
3031
- throw new Error("Image models are not supported by Apertis");
3032
- }
3033
- }
3034
- );
2333
+ const createImageModel = (modelId) => new OpenAICompatibleImageModel(modelId, getCommonModelConfig("image"));
2334
+ const provider = (modelId) => createLanguageModel(modelId);
2335
+ provider.languageModel = createLanguageModel;
2336
+ provider.chatModel = createChatModel;
2337
+ provider.completionModel = createCompletionModel;
2338
+ provider.textEmbeddingModel = createEmbeddingModel;
2339
+ provider.imageModel = createImageModel;
3035
2340
  return provider;
3036
2341
  }
2342
+
2343
+ // src/apertis-provider.ts
2344
+ function createApertis(options = {}) {
2345
+ return createOpenAICompatible({
2346
+ name: "apertis",
2347
+ baseURL: options.baseURL ?? "https://api.apertis.ai/v1",
2348
+ apiKey: options.apiKey ?? process.env.APERTIS_API_KEY,
2349
+ headers: options.headers,
2350
+ fetch: options.fetch
2351
+ });
2352
+ }
3037
2353
  var apertis = createApertis();
3038
2354
  // Annotate the CommonJS export names for ESM import in node:
3039
2355
  0 && (module.exports = {
3040
2356
  apertis,
3041
- createApertis,
3042
- createApertisV3
2357
+ createApertis
3043
2358
  });
3044
2359
  //# sourceMappingURL=index.cjs.map