ai 7.0.173 → 7.0.175

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/index.d.ts +68 -21
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +292 -80
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +11 -9
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +16 -3
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/02-providers-and-models.mdx +3 -0
  11. package/docs/03-agents/06-memory.mdx +28 -1
  12. package/docs/03-ai-sdk-core/33-extractions.mdx +58 -1
  13. package/docs/03-ai-sdk-core/42-batch.mdx +54 -0
  14. package/docs/03-ai-sdk-core/45-provider-management.mdx +8 -0
  15. package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +13 -13
  16. package/docs/07-reference/01-ai-sdk-core/20-start-batch.mdx +7 -0
  17. package/docs/07-reference/01-ai-sdk-core/22-get-batch-results.mdx +7 -0
  18. package/docs/07-reference/01-ai-sdk-core/40-provider-registry.mdx +14 -0
  19. package/docs/07-reference/01-ai-sdk-core/42-custom-provider.mdx +13 -0
  20. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-model-error.mdx +3 -0
  21. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-provider-error.mdx +3 -0
  22. package/package.json +12 -12
  23. package/src/batch/batch-types.ts +70 -18
  24. package/src/batch/batch.ts +93 -7
  25. package/src/extract/extract.ts +23 -4
  26. package/src/extract/extraction-provider.ts +5 -0
  27. package/src/extract/extraction-result.ts +1 -1
  28. package/src/generate-text/stream-text.ts +1 -1
  29. package/src/global.ts +1 -0
  30. package/src/model/resolve-model.ts +25 -0
  31. package/src/registry/custom-provider.ts +37 -0
  32. package/src/registry/index.ts +1 -0
  33. package/src/registry/no-such-provider-error.ts +1 -0
  34. package/src/registry/provider-registry.ts +59 -5
  35. package/src/telemetry/redact-telemetry-credentials.ts +22 -4
  36. package/src/types/citation.ts +41 -25
  37. package/src/ui/validate-ui-messages.ts +46 -91
  38. package/src/util/normalize-json-value.ts +182 -0
package/dist/index.js CHANGED
@@ -1176,6 +1176,20 @@ function resolveDecisionModel(model) {
1176
1176
  };
1177
1177
  }
1178
1178
  function resolveExtractionModel(model) {
1179
+ if (typeof model === "string") {
1180
+ const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway$1;
1181
+ if (typeof provider.extractionModel !== "function") throw new NoSuchModelError$1({
1182
+ modelId: model,
1183
+ modelType: "extractionModel",
1184
+ message: "The default provider does not support extraction models. Pass an extraction model instance or configure AI_SDK_DEFAULT_PROVIDER with an extractionModel method."
1185
+ });
1186
+ const resolvedModel = provider.extractionModel(model);
1187
+ if (resolvedModel == null) throw new NoSuchModelError$1({
1188
+ modelId: model,
1189
+ modelType: "extractionModel"
1190
+ });
1191
+ model = resolvedModel;
1192
+ }
1179
1193
  const version = model.specificationVersion;
1180
1194
  if (version !== "v4") throw new UnsupportedModelVersionError({
1181
1195
  version,
@@ -1251,7 +1265,7 @@ function cloneValue(value, seen) {
1251
1265
  }
1252
1266
  //#endregion
1253
1267
  //#region src/version.ts
1254
- const VERSION = "7.0.173";
1268
+ const VERSION = "7.0.175";
1255
1269
  //#endregion
1256
1270
  //#region src/util/download/download.ts
1257
1271
  /**
@@ -4248,7 +4262,7 @@ function mapArray(value, redact) {
4248
4262
  const copy = value.map(redact);
4249
4263
  return copy.some((entry, index) => entry !== value[index]) ? copy : value;
4250
4264
  }
4251
- /** Preserve result getters, streams, and property descriptors without mutation. */
4265
+ /** Preserve result getters and property descriptors without mutation. */
4252
4266
  function replaceProperties(value, redactors) {
4253
4267
  if (!isRecord$2(value)) return value;
4254
4268
  let descriptors;
@@ -4264,7 +4278,20 @@ function replaceProperties(value, redactors) {
4264
4278
  };
4265
4279
  }
4266
4280
  }
4267
- return descriptors == null ? value : Object.create(Object.getPrototypeOf(value), descriptors);
4281
+ if (descriptors == null) return value;
4282
+ const streamDescriptor = descriptors.stream;
4283
+ if (streamDescriptor?.writable && streamDescriptor.value instanceof ReadableStream) {
4284
+ const original = value;
4285
+ descriptors.stream = {
4286
+ configurable: streamDescriptor.configurable,
4287
+ enumerable: streamDescriptor.enumerable,
4288
+ get: () => original.stream,
4289
+ set: (stream) => {
4290
+ original.stream = stream;
4291
+ }
4292
+ };
4293
+ }
4294
+ return Object.create(Object.getPrototypeOf(value), descriptors);
4268
4295
  }
4269
4296
  //#endregion
4270
4297
  //#region src/telemetry/tracing-channel-publisher.ts
@@ -6675,43 +6702,50 @@ const z = {
6675
6702
  };
6676
6703
  //#endregion
6677
6704
  //#region src/types/json-value.ts
6678
- const jsonValueSchema = z.lazy(() => z.union([
6705
+ const jsonValueSchema$1 = z.lazy(() => z.union([
6679
6706
  z.null(),
6680
6707
  z.string(),
6681
6708
  z.number(),
6682
6709
  z.boolean(),
6683
- z.record(z.string(), jsonValueSchema.optional()),
6684
- z.array(jsonValueSchema)
6710
+ z.record(z.string(), jsonValueSchema$1.optional()),
6711
+ z.array(jsonValueSchema$1)
6685
6712
  ]));
6686
6713
  //#endregion
6687
6714
  //#region src/types/provider-metadata.ts
6688
- const providerMetadataSchema$1 = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
6715
+ const providerMetadataSchema$1 = z.record(z.string(), z.record(z.string(), jsonValueSchema$1.optional()));
6689
6716
  //#endregion
6690
6717
  //#region src/types/citation.ts
6691
- const citationSchema = z$1.object({
6692
- source: z$1.discriminatedUnion("sourceType", [z$1.object({
6693
- type: z$1.literal("source"),
6694
- sourceType: z$1.literal("url"),
6695
- id: z$1.string(),
6696
- url: z$1.string(),
6697
- title: z$1.optional(z$1.string()),
6698
- providerMetadata: z$1.optional(providerMetadataSchema$1)
6699
- }), z$1.object({
6700
- type: z$1.literal("source"),
6701
- sourceType: z$1.literal("document"),
6702
- id: z$1.string(),
6703
- mediaType: z$1.string(),
6704
- title: z$1.string(),
6705
- filename: z$1.optional(z$1.string()),
6706
- providerMetadata: z$1.optional(providerMetadataSchema$1)
6707
- })]),
6708
- startIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6709
- endIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6710
- citedText: z$1.optional(z$1.string())
6711
- });
6718
+ /**
6719
+ * Creates a citation schema that validates the provider metadata of the
6720
+ * source with the given schema.
6721
+ */
6722
+ function createCitationSchema(providerMetadataSchema) {
6723
+ return z$1.object({
6724
+ source: z$1.discriminatedUnion("sourceType", [z$1.object({
6725
+ type: z$1.literal("source"),
6726
+ sourceType: z$1.literal("url"),
6727
+ id: z$1.string(),
6728
+ url: z$1.string(),
6729
+ title: z$1.optional(z$1.string()),
6730
+ providerMetadata: z$1.optional(providerMetadataSchema)
6731
+ }), z$1.object({
6732
+ type: z$1.literal("source"),
6733
+ sourceType: z$1.literal("document"),
6734
+ id: z$1.string(),
6735
+ mediaType: z$1.string(),
6736
+ title: z$1.string(),
6737
+ filename: z$1.optional(z$1.string()),
6738
+ providerMetadata: z$1.optional(providerMetadataSchema)
6739
+ })]),
6740
+ startIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6741
+ endIndex: z$1.optional(z$1.number().check(z$1.int()).check(z$1.nonnegative())),
6742
+ citedText: z$1.optional(z$1.string())
6743
+ });
6744
+ }
6745
+ const citationSchema = createCitationSchema(providerMetadataSchema$1);
6712
6746
  //#endregion
6713
6747
  //#region src/ui-message-stream/ui-message-chunks.ts
6714
- const toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema));
6748
+ const toolMetadataSchema$1 = z$1.record(z$1.string(), z$1.optional(jsonValueSchema$1));
6715
6749
  const uiMessageChunkSchema = lazySchema(() => zodSchema$1(z$1.union([
6716
6750
  z$1.looseObject({
6717
6751
  type: z$1.literal("text-start"),
@@ -10056,7 +10090,7 @@ var DefaultStreamTextResult = class {
10056
10090
  stream = applyStreamTextTransforms({
10057
10091
  stream,
10058
10092
  transforms,
10059
- tools,
10093
+ tools: tools ?? {},
10060
10094
  stopStream() {
10061
10095
  stitchableStream.terminate();
10062
10096
  isRunning = false;
@@ -11820,60 +11854,159 @@ function convertUserContentUIPart(part) {
11820
11854
  };
11821
11855
  }
11822
11856
  //#endregion
11823
- //#region src/ui/validate-ui-messages.ts
11857
+ //#region src/util/normalize-json-value.ts
11858
+ const invalid = Symbol("invalid");
11824
11859
  /**
11825
- * Returns the path to the first value that can never be part of a JSON value
11826
- * (a non-finite number, bigint, symbol, or function), if there is one.
11860
+ * Validates that a value is a JSON value: `null`, a string, a finite number, a
11861
+ * boolean, an array of JSON values, or a plain object with JSON values.
11862
+ *
11863
+ * The value is validated in a single pass that does not allocate memory for
11864
+ * its valid parts, so that validating untrusted input costs little more than
11865
+ * the input itself. A recursive union schema tries (and reports the issues of)
11866
+ * every alternative for every nested value and returns a copy of the value.
11867
+ *
11868
+ * It accepts the same values as a record schema of JSON values, except that a
11869
+ * JSON value cannot contain itself:
11870
+ *
11871
+ * - Object properties can be `undefined`. Array elements cannot.
11872
+ * - Objects must be plain objects without enumerable symbol keys.
11873
+ * - Own `__proto__` keys are removed. Only the objects with such a key and the
11874
+ * arrays and objects that contain them are copied. Everything else is
11875
+ * returned as is.
11876
+ *
11877
+ * @returns The JSON value, or the path to the first invalid value.
11878
+ */
11879
+ function normalizeJsonValue(value) {
11880
+ const path = [];
11881
+ const normalized = normalize(value, path, /* @__PURE__ */ new Set());
11882
+ return normalized === invalid ? {
11883
+ success: false,
11884
+ path
11885
+ } : {
11886
+ success: true,
11887
+ value: normalized
11888
+ };
11889
+ }
11890
+ /**
11891
+ * Returns the normalized value, or `invalid` with the path to the invalid
11892
+ * value in `path`.
11893
+ *
11894
+ * @param ancestors - The arrays and objects that contain `value`. Tracking
11895
+ * them instead of all visited values detects cycles with memory proportional
11896
+ * to the nesting depth.
11827
11897
  */
11828
- function findInvalidJsonValuePath(value, path = [], visited = /* @__PURE__ */ new WeakSet()) {
11898
+ function normalize(value, path, ancestors) {
11829
11899
  switch (typeof value) {
11830
- case "number": return Number.isFinite(value) ? void 0 : [...path];
11831
- case "bigint":
11832
- case "symbol":
11833
- case "function": return [...path];
11900
+ case "string":
11901
+ case "boolean": return value;
11902
+ case "number": return Number.isFinite(value) ? value : invalid;
11834
11903
  case "object": {
11835
- if (value === null || visited.has(value)) return;
11836
- visited.add(value);
11837
- const keys = Array.isArray(value) ? value.keys() : Object.keys(value);
11838
- for (const key of keys) {
11839
- if (key === "__proto__") continue;
11840
- path.push(key);
11841
- const invalidPath = findInvalidJsonValuePath(value[key], path, visited);
11842
- if (invalidPath != null) return invalidPath;
11843
- path.pop();
11844
- }
11845
- return;
11904
+ if (value === null) return value;
11905
+ if (ancestors.has(value)) return invalid;
11906
+ ancestors.add(value);
11907
+ const normalized = Array.isArray(value) ? normalizeArray(value, path, ancestors) : normalizeObject(value, path, ancestors);
11908
+ ancestors.delete(value);
11909
+ return normalized;
11910
+ }
11911
+ default: return invalid;
11912
+ }
11913
+ }
11914
+ function normalizeArray(array, path, ancestors) {
11915
+ let copy;
11916
+ for (let index = 0; index < array.length; index++) {
11917
+ const element = array[index];
11918
+ path.push(index);
11919
+ const normalized = normalize(element, path, ancestors);
11920
+ if (normalized === invalid) return invalid;
11921
+ path.pop();
11922
+ if (copy != null) copy.push(normalized);
11923
+ else if (normalized !== element) {
11924
+ copy = array.slice(0, index);
11925
+ copy.push(normalized);
11846
11926
  }
11847
- default: return;
11848
11927
  }
11928
+ return copy ?? array;
11929
+ }
11930
+ function normalizeObject(object, path, ancestors) {
11931
+ if (!isPlainObject(object) || hasEnumerableSymbolKey(object)) return invalid;
11932
+ const keys = Object.keys(object);
11933
+ let copy;
11934
+ for (let index = 0; index < keys.length; index++) {
11935
+ const key = keys[index];
11936
+ if (key === "__proto__") {
11937
+ copy ??= copyProperties(object, keys, index);
11938
+ continue;
11939
+ }
11940
+ const property = object[key];
11941
+ let normalized = property;
11942
+ if (property !== void 0) {
11943
+ path.push(key);
11944
+ normalized = normalize(property, path, ancestors);
11945
+ if (normalized === invalid) return invalid;
11946
+ path.pop();
11947
+ }
11948
+ if (copy != null) copy[key] = normalized;
11949
+ else if (normalized !== property) {
11950
+ copy = copyProperties(object, keys, index);
11951
+ copy[key] = normalized;
11952
+ }
11953
+ }
11954
+ return copy ?? object;
11849
11955
  }
11850
11956
  /**
11851
- * Rejects values that contain an invalid JSON value with a single issue before
11852
- * `schema` validates them.
11853
- *
11854
- * The JSON value schema is a recursive union. It reports the issues of every
11855
- * alternative at every nesting level around an invalid value, so the size of a
11856
- * validation error would grow much faster than the (untrusted) input.
11957
+ * Copies the properties of the first `count` keys, which are known to be valid.
11958
+ */
11959
+ function copyProperties(object, keys, count) {
11960
+ const copy = {};
11961
+ for (let index = 0; index < count; index++) copy[keys[index]] = object[keys[index]];
11962
+ return copy;
11963
+ }
11964
+ /**
11965
+ * Same check as record schemas, which accepts plain objects from other realms
11966
+ * and objects without a prototype.
11967
+ */
11968
+ function isPlainObject(object) {
11969
+ const constructor = object.constructor;
11970
+ if (typeof constructor !== "function") return true;
11971
+ const prototype = constructor.prototype;
11972
+ return prototype !== null && typeof prototype === "object" && Object.prototype.hasOwnProperty.call(prototype, "isPrototypeOf");
11973
+ }
11974
+ function hasEnumerableSymbolKey(object) {
11975
+ const symbols = Object.getOwnPropertySymbols(object);
11976
+ for (let index = 0; index < symbols.length; index++) if (Object.prototype.propertyIsEnumerable.call(object, symbols[index])) return true;
11977
+ return false;
11978
+ }
11979
+ //#endregion
11980
+ //#region src/ui/validate-ui-messages.ts
11981
+ /**
11982
+ * Validates a JSON value in a single pass and reports an invalid JSON value
11983
+ * with a single issue.
11857
11984
  *
11858
- * @param jsonValuePath - Path from the validated value to the JSON value.
11985
+ * UI messages are untrusted input. The recursive JSON value schema tries
11986
+ * every alternative for every nested value and returns a copy of the value,
11987
+ * so accepting a value would need several times the memory of the value. It
11988
+ * also reports the issues of every alternative at every nesting level around
11989
+ * an invalid value, so the size of a validation error would grow much faster
11990
+ * than the input.
11859
11991
  */
11860
- function withJsonValueCheck(schema, jsonValuePath = []) {
11861
- return z$1.pipe(z$1.unknown().check((context) => {
11862
- let jsonValue = context.value;
11863
- for (const key of jsonValuePath) jsonValue = jsonValue != null && typeof jsonValue === "object" ? jsonValue[key] : void 0;
11864
- const invalidPath = findInvalidJsonValuePath(jsonValue);
11865
- if (invalidPath != null) context.issues.push({
11992
+ const jsonValueSchema = z$1.pipe(z$1.unknown(), z$1.transform((value, context) => {
11993
+ const result = normalizeJsonValue(value);
11994
+ if (!result.success) {
11995
+ context.issues.push({
11866
11996
  code: "custom",
11867
11997
  message: "Invalid JSON value. Expected null, a string, a finite number, a boolean, an array, or an object.",
11868
- input: context.value,
11869
- path: [...jsonValuePath, ...invalidPath]
11998
+ input: value,
11999
+ path: result.path
11870
12000
  });
11871
- }), schema);
11872
- }
11873
- const toolMetadataSchema = withJsonValueCheck(z$1.record(z$1.string(), z$1.optional(jsonValueSchema)));
11874
- const providerMetadataSchema = withJsonValueCheck(providerMetadataSchema$1);
12001
+ return z$1.NEVER;
12002
+ }
12003
+ return result.value;
12004
+ }));
12005
+ const validatedJsonValueSchema = z$1.custom();
12006
+ const toolMetadataSchema = z$1.pipe(jsonValueSchema, z$1.record(z$1.string(), validatedJsonValueSchema));
12007
+ const providerMetadataSchema = z$1.pipe(jsonValueSchema, z$1.record(z$1.string(), z$1.record(z$1.string(), validatedJsonValueSchema)));
11875
12008
  const providerReferenceSchema$1 = z$1.record(z$1.string(), z$1.string());
11876
- const uiCitationSchema = withJsonValueCheck(citationSchema, ["source", "providerMetadata"]);
12009
+ const uiCitationSchema = createCitationSchema(providerMetadataSchema);
11877
12010
  function isEmptyObject(value) {
11878
12011
  return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11879
12012
  }
@@ -12832,12 +12965,13 @@ async function listBatches({ provider, providerOptions, limit, cursor, maxRetrie
12832
12965
  /**
12833
12966
  * Starts a batch.
12834
12967
  */
12835
- async function startBatch({ provider, requests, providerOptions, webhookUrl, abortSignal, headers, timeout }) {
12968
+ async function startBatch({ provider, requests, providerOptions, output, webhookUrl, abortSignal, headers, timeout }) {
12836
12969
  validateRequests(requests);
12837
12970
  const batchApi = resolveBatchApi(provider);
12838
12971
  const operationAbortSignal = mergeAbortSignals(abortSignal, getTotalTimeoutMs(timeout));
12839
12972
  const supportedUrls = await batchApi.supportedUrls;
12840
12973
  operationAbortSignal?.throwIfAborted();
12974
+ const responseFormat = await output?.responseFormat;
12841
12975
  const normalizedRequests = [];
12842
12976
  const toolsByName = /* @__PURE__ */ new Map();
12843
12977
  for (const request of requests) {
@@ -12861,6 +12995,7 @@ async function startBatch({ provider, requests, providerOptions, webhookUrl, abo
12861
12995
  modelId: request.model,
12862
12996
  options: {
12863
12997
  ...prepareLanguageModelCallOptions(request),
12998
+ responseFormat,
12864
12999
  prompt: await convertToLanguageModelPrompt({
12865
13000
  prompt: standardizedPrompt,
12866
13001
  supportedUrls,
@@ -12970,7 +13105,7 @@ async function getBatchStatus({ provider, batch, providerOptions, maxRetries, ab
12970
13105
  /**
12971
13106
  * Streams complete terminal results for the requests in a batch.
12972
13107
  */
12973
- function getBatchResults({ provider, batch, tools, providerOptions, maxRetries, abortSignal, headers, timeout }) {
13108
+ function getBatchResults({ provider, batch, tools, output, providerOptions, maxRetries, abortSignal, headers, timeout }) {
12974
13109
  const batchApi = resolveBatchApi(provider);
12975
13110
  validateBatchReference({
12976
13111
  batchApi,
@@ -12987,6 +13122,7 @@ function getBatchResults({ provider, batch, tools, providerOptions, maxRetries,
12987
13122
  controller.enqueue(await convertBatchItemResult({
12988
13123
  item,
12989
13124
  tools,
13125
+ output,
12990
13126
  abortSignal: operationAbortSignal
12991
13127
  }));
12992
13128
  },
@@ -13052,7 +13188,7 @@ function validateBatchReference({ batchApi, batch }) {
13052
13188
  message: `provider ${batchApi.provider} is not compatible with batch provider ${batch.provider}`
13053
13189
  });
13054
13190
  }
13055
- async function convertBatchItemResult({ item, tools, abortSignal }) {
13191
+ async function convertBatchItemResult({ item, tools, output, abortSignal }) {
13056
13192
  switch (item.type) {
13057
13193
  case "text": switch (item.status) {
13058
13194
  case "succeeded": return {
@@ -13063,7 +13199,11 @@ async function convertBatchItemResult({ item, tools, abortSignal }) {
13063
13199
  result: item.result,
13064
13200
  tools,
13065
13201
  abortSignal
13066
- })
13202
+ }),
13203
+ ...output != null ? await parseBatchOutput({
13204
+ result: item.result,
13205
+ output
13206
+ }) : {}
13067
13207
  };
13068
13208
  case "failed": return {
13069
13209
  type: item.type,
@@ -13126,6 +13266,42 @@ function convertImageResult(result) {
13126
13266
  usage: result.usage
13127
13267
  };
13128
13268
  }
13269
+ /**
13270
+ * Parses the structured output of a successful text item. Failures are
13271
+ * reported as `outputError` so that one malformed item does not affect the
13272
+ * rest of the batch or discard the item's text and usage.
13273
+ */
13274
+ async function parseBatchOutput({ result, output }) {
13275
+ const generatedText = result.content.filter((part) => {
13276
+ return part.type === "text";
13277
+ }).map((part) => part.text).join("");
13278
+ const finishReason = result.finishReason.unified;
13279
+ if (!(finishReason === "stop" || finishReason !== "tool-calls" && generatedText.length > 0)) {
13280
+ const error = new NoOutputGeneratedError();
13281
+ return { outputError: {
13282
+ message: error.message,
13283
+ type: error.name
13284
+ } };
13285
+ }
13286
+ const textForOutput = (await output.responseFormat)?.type === "json" ? result.structuredOutputText ?? generatedText : generatedText;
13287
+ try {
13288
+ return { output: await output.parseCompleteOutput({ text: textForOutput }, {
13289
+ response: {
13290
+ id: result.response?.id ?? "",
13291
+ timestamp: result.response?.timestamp ?? /* @__PURE__ */ new Date(0),
13292
+ modelId: result.response?.modelId ?? "",
13293
+ headers: result.response?.headers
13294
+ },
13295
+ usage: asLanguageModelUsage(result.usage),
13296
+ finishReason
13297
+ }) };
13298
+ } catch (error) {
13299
+ return { outputError: {
13300
+ message: error instanceof Error ? error.message : String(error),
13301
+ type: error instanceof Error ? error.name : "Error"
13302
+ } };
13303
+ }
13304
+ }
13129
13305
  async function convertGenerateResult({ result, tools, abortSignal }) {
13130
13306
  const toolCalls = await Promise.all(result.content.filter((part) => part.type === "tool-call").map((toolCall) => parseToolCall({
13131
13307
  toolCall,
@@ -14152,12 +14328,24 @@ async function extract({ model: modelArg, state, fields, referenceDate, maxOutpu
14152
14328
  });
14153
14329
  });
14154
14330
  abortSignal?.throwIfAborted();
14331
+ const answers = isRecord$1(result.answers) ? Object.fromEntries(Object.entries(result.answers).map(([id, answer]) => {
14332
+ if (!isRecord$1(answer) || answer.type === "refusal") return [id, answer];
14333
+ if (answer.value === "" || Array.isArray(answer.value) && answer.value.length === 0) {
14334
+ const normalized = {
14335
+ ...answer,
14336
+ value: null
14337
+ };
14338
+ if (normalized.type === "list") delete normalized.items;
14339
+ return [id, normalized];
14340
+ }
14341
+ return [id, answer];
14342
+ })) : result.answers;
14155
14343
  validateExtractionAnswers({
14156
14344
  fields,
14157
14345
  state: preparedState,
14158
- answers: result.answers
14346
+ answers
14159
14347
  });
14160
- const refusedFieldIds = Object.keys(fields).filter((id) => result.answers[id]?.type === "refusal");
14348
+ const refusedFieldIds = Object.keys(fields).filter((id) => answers[id]?.type === "refusal");
14161
14349
  if (refusedFieldIds.length > 0) throw new Experimental_ExtractionRefusalError$1({
14162
14350
  fieldIds: refusedFieldIds,
14163
14351
  provider: model.provider,
@@ -14171,7 +14359,7 @@ async function extract({ model: modelArg, state, fields, referenceDate, maxOutpu
14171
14359
  const inputTokens = result.usage?.inputTokens;
14172
14360
  const outputTokens = result.usage?.outputTokens;
14173
14361
  return {
14174
- answers: result.answers,
14362
+ answers,
14175
14363
  usage: {
14176
14364
  inputTokens,
14177
14365
  outputTokens,
@@ -17596,7 +17784,7 @@ const outputSchema = z.discriminatedUnion("type", [
17596
17784
  }),
17597
17785
  z.object({
17598
17786
  type: z.literal("json"),
17599
- value: jsonValueSchema,
17787
+ value: jsonValueSchema$1,
17600
17788
  providerOptions: providerMetadataSchema$1.optional()
17601
17789
  }),
17602
17790
  z.object({
@@ -17611,7 +17799,7 @@ const outputSchema = z.discriminatedUnion("type", [
17611
17799
  }),
17612
17800
  z.object({
17613
17801
  type: z.literal("error-json"),
17614
- value: jsonValueSchema,
17802
+ value: jsonValueSchema$1,
17615
17803
  providerOptions: providerMetadataSchema$1.optional()
17616
17804
  }),
17617
17805
  z.object({
@@ -20130,6 +20318,7 @@ var AbstractRealtimeSession = class {
20130
20318
  * @param {Record<string, RerankingModel>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances.
20131
20319
  * @param {Record<string, VideoModel>} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances.
20132
20320
  * @param {Record<string, DecisionModel>} [options.decisionModels] - Experimental decision models or default-provider model IDs, keyed by alias.
20321
+ * @param {Record<string, ExtractionModel>} [options.extractionModels] - Experimental extraction models or default-provider model IDs, keyed by alias.
20133
20322
  * @param {FilesV4} [options.files] - A files interface for uploading files.
20134
20323
  * @param {SkillsV4} [options.skills] - A skills interface for uploading skills.
20135
20324
  * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.
@@ -20137,7 +20326,7 @@ var AbstractRealtimeSession = class {
20137
20326
  *
20138
20327
  * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.
20139
20328
  */
20140
- function customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, files, skills, fallbackProvider: fallbackProviderArg }) {
20329
+ function customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, decisionModels: decisionModelsArg, evaluationModels, extractionModels, files, skills, fallbackProvider: fallbackProviderArg }) {
20141
20330
  const decisionModels = decisionModelsArg ?? evaluationModels;
20142
20331
  const fallbackProvider = fallbackProviderArg == null ? void 0 : asProviderV4(fallbackProviderArg);
20143
20332
  const baseProvider = {
@@ -20212,6 +20401,18 @@ function customProvider({ languageModels, embeddingModels, imageModels, transcri
20212
20401
  evaluationModel(modelId) {
20213
20402
  return asEvaluationModel(this.decisionModel(modelId));
20214
20403
  },
20404
+ extractionModel(modelId) {
20405
+ if (extractionModels != null && Object.hasOwn(extractionModels, modelId)) return resolveExtractionModel(extractionModels[modelId]);
20406
+ const provider = fallbackProviderArg;
20407
+ if (typeof provider?.extractionModel === "function") {
20408
+ const model = provider.extractionModel(modelId);
20409
+ if (model != null) return resolveExtractionModel(model);
20410
+ }
20411
+ throw new NoSuchModelError$1({
20412
+ modelId,
20413
+ modelType: "extractionModel"
20414
+ });
20415
+ },
20215
20416
  videoModel(modelId) {
20216
20417
  if (videoModels != null && modelId in videoModels) return resolveVideoModel(videoModels[modelId]);
20217
20418
  const provider = fallbackProviderArg;
@@ -20296,11 +20497,13 @@ var DefaultProviderRegistry = class {
20296
20497
  const videoModel = provider.videoModel?.bind(provider);
20297
20498
  const decisionProvider = provider;
20298
20499
  const decisionModel = (decisionProvider.decisionModel ?? decisionProvider.evaluationModel)?.bind(provider);
20500
+ const extractionModel = provider.extractionModel?.bind(provider);
20299
20501
  const registeredProvider = videoModel == null ? providerV4 : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {
20300
20502
  ...providerV4,
20301
20503
  videoModel: (modelId) => asVideoModelV4(videoModel(modelId))
20302
20504
  });
20303
20505
  if (registeredProvider !== provider && decisionModel != null) Object.assign(registeredProvider, { decisionModel });
20506
+ if (registeredProvider !== provider && extractionModel != null) Object.assign(registeredProvider, { extractionModel });
20304
20507
  this.providers[id] = registeredProvider;
20305
20508
  }
20306
20509
  getProvider(id, modelType) {
@@ -20407,6 +20610,15 @@ var DefaultProviderRegistry = class {
20407
20610
  evaluationModel(id) {
20408
20611
  return asEvaluationModel(this.decisionModel(id));
20409
20612
  }
20613
+ extractionModel(id) {
20614
+ const [providerId, modelId] = this.splitId(id, "extractionModel");
20615
+ const model = this.getProvider(providerId, "extractionModel").extractionModel?.(modelId);
20616
+ if (model == null) throw new NoSuchModelError$1({
20617
+ modelId: id,
20618
+ modelType: "extractionModel"
20619
+ });
20620
+ return resolveExtractionModel(model);
20621
+ }
20410
20622
  files(id) {
20411
20623
  const files = this.getProvider(id, "languageModel").files?.();
20412
20624
  if (files == null) throw new Error(`The provider "${id}" does not support file uploads. Make sure it exposes a files() method.`);