ai 7.0.172 → 7.0.174

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 (55) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/index.d.ts +68 -21
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +325 -100
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +109 -9
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +68 -18
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/02-providers-and-models.mdx +1 -0
  11. package/docs/02-foundations/03-prompts.mdx +1 -1
  12. package/docs/03-agents/04-loop-control.mdx +1 -1
  13. package/docs/03-agents/06-memory.mdx +28 -1
  14. package/docs/03-agents/06-tool-approvals.mdx +1 -1
  15. package/docs/03-agents/07-workflow-agent.mdx +87 -34
  16. package/docs/03-ai-sdk-core/05-generating-text.mdx +7 -2
  17. package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +4 -0
  18. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +3 -0
  19. package/docs/03-ai-sdk-core/26-reasoning.mdx +3 -3
  20. package/docs/03-ai-sdk-core/32-decisions.mdx +4 -0
  21. package/docs/03-ai-sdk-core/33-extractions.mdx +59 -2
  22. package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -0
  23. package/docs/03-ai-sdk-core/36-transcription.mdx +3 -0
  24. package/docs/03-ai-sdk-core/37-speech.mdx +3 -0
  25. package/docs/03-ai-sdk-core/42-batch.mdx +54 -0
  26. package/docs/03-ai-sdk-core/45-provider-management.mdx +8 -0
  27. package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +13 -13
  28. package/docs/07-reference/01-ai-sdk-core/20-start-batch.mdx +7 -0
  29. package/docs/07-reference/01-ai-sdk-core/22-get-batch-results.mdx +7 -0
  30. package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +6 -0
  31. package/docs/07-reference/01-ai-sdk-core/33-safe-validate-ui-messages.mdx +3 -0
  32. package/docs/07-reference/01-ai-sdk-core/40-provider-registry.mdx +14 -0
  33. package/docs/07-reference/01-ai-sdk-core/42-custom-provider.mdx +13 -0
  34. package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +62 -5
  35. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-model-error.mdx +3 -0
  36. package/docs/07-reference/05-ai-sdk-errors/ai-no-such-provider-error.mdx +3 -0
  37. package/package.json +12 -12
  38. package/src/agent/default-stop-condition.ts +28 -13
  39. package/src/batch/batch-types.ts +70 -18
  40. package/src/batch/batch.ts +93 -7
  41. package/src/extract/extract.ts +23 -4
  42. package/src/extract/extraction-provider.ts +5 -0
  43. package/src/extract/extraction-result.ts +1 -1
  44. package/src/generate-text/stream-text.ts +1 -1
  45. package/src/generate-text/validate-tool-approvals.ts +23 -19
  46. package/src/global.ts +1 -0
  47. package/src/model/resolve-model.ts +25 -0
  48. package/src/registry/custom-provider.ts +37 -0
  49. package/src/registry/index.ts +1 -0
  50. package/src/registry/no-such-provider-error.ts +1 -0
  51. package/src/registry/provider-registry.ts +59 -5
  52. package/src/telemetry/redact-telemetry-credentials.ts +22 -4
  53. package/src/types/citation.ts +41 -25
  54. package/src/ui/validate-ui-messages.ts +46 -91
  55. package/src/util/normalize-json-value.ts +182 -0
@@ -20,6 +20,8 @@ import {
20
20
  normalizePrompt as normalizeImagePrompt,
21
21
  } from '../generate-image/generate-image';
22
22
  import { DefaultGeneratedFile } from '../generate-text/generated-file';
23
+ import { NoOutputGeneratedError } from '../error/no-output-generated-error';
24
+ import type { Output } from '../generate-text/output';
23
25
  import { parseToolCall } from '../generate-text/parse-tool-call';
24
26
  import { prepareToolChoice } from '../prompt/prepare-tool-choice';
25
27
  import { prepareTools } from '../prompt/prepare-tools';
@@ -159,6 +161,7 @@ export async function startBatch<
159
161
  provider,
160
162
  requests,
161
163
  providerOptions,
164
+ output,
162
165
  webhookUrl,
163
166
  abortSignal,
164
167
  headers,
@@ -173,6 +176,7 @@ export async function startBatch<
173
176
  );
174
177
  const supportedUrls = await batchApi.supportedUrls;
175
178
  operationAbortSignal?.throwIfAborted();
179
+ const responseFormat = await output?.responseFormat;
176
180
  const normalizedRequests = [];
177
181
  const toolsByName = new Map<string, unknown>();
178
182
 
@@ -198,6 +202,7 @@ export async function startBatch<
198
202
  modelId: request.model,
199
203
  options: {
200
204
  ...prepareLanguageModelCallOptions(request),
205
+ responseFormat,
201
206
  prompt: await convertToLanguageModelPrompt({
202
207
  prompt: standardizedPrompt,
203
208
  supportedUrls,
@@ -347,16 +352,20 @@ export async function getBatchStatus({
347
352
  /**
348
353
  * Streams complete terminal results for the requests in a batch.
349
354
  */
350
- export function getBatchResults<TOOLS extends ToolSet>({
355
+ export function getBatchResults<
356
+ TOOLS extends ToolSet,
357
+ OUTPUT extends Output | undefined = undefined,
358
+ >({
351
359
  provider,
352
360
  batch,
353
361
  tools,
362
+ output,
354
363
  providerOptions,
355
364
  maxRetries,
356
365
  abortSignal,
357
366
  headers,
358
367
  timeout,
359
- }: GetBatchResultsOptions<TOOLS>) {
368
+ }: GetBatchResultsOptions<TOOLS, OUTPUT>) {
360
369
  const batchApi = resolveBatchApi(provider);
361
370
  validateBatchReference({ batchApi, batch });
362
371
 
@@ -370,7 +379,10 @@ export function getBatchResults<TOOLS extends ToolSet>({
370
379
  maxRetries,
371
380
  abortSignal: operationAbortSignal,
372
381
  });
373
- const transformer: Transformer<BatchV4ItemResult, BatchItemResult<TOOLS>> & {
382
+ const transformer: Transformer<
383
+ BatchV4ItemResult,
384
+ BatchItemResult<TOOLS, OUTPUT>
385
+ > & {
374
386
  cancel?: (reason?: unknown) => void;
375
387
  } = {
376
388
  async transform(item, controller) {
@@ -378,6 +390,7 @@ export function getBatchResults<TOOLS extends ToolSet>({
378
390
  await convertBatchItemResult({
379
391
  item,
380
392
  tools,
393
+ output,
381
394
  abortSignal: operationAbortSignal,
382
395
  }),
383
396
  );
@@ -391,7 +404,7 @@ export function getBatchResults<TOOLS extends ToolSet>({
391
404
  };
392
405
  const transform = new TransformStream<
393
406
  BatchV4ItemResult,
394
- BatchItemResult<TOOLS>
407
+ BatchItemResult<TOOLS, OUTPUT>
395
408
  >(transformer);
396
409
 
397
410
  void (async () => {
@@ -502,15 +515,20 @@ function validateBatchReference({
502
515
  }
503
516
  }
504
517
 
505
- async function convertBatchItemResult<TOOLS extends ToolSet>({
518
+ async function convertBatchItemResult<
519
+ TOOLS extends ToolSet,
520
+ OUTPUT extends Output | undefined,
521
+ >({
506
522
  item,
507
523
  tools,
524
+ output,
508
525
  abortSignal,
509
526
  }: {
510
527
  item: BatchV4ItemResult;
511
528
  tools: TOOLS | undefined;
529
+ output: OUTPUT | undefined;
512
530
  abortSignal: AbortSignal | undefined;
513
- }): Promise<BatchItemResult<TOOLS>> {
531
+ }): Promise<BatchItemResult<TOOLS, OUTPUT>> {
514
532
  switch (item.type) {
515
533
  case 'text':
516
534
  switch (item.status) {
@@ -524,7 +542,10 @@ async function convertBatchItemResult<TOOLS extends ToolSet>({
524
542
  tools,
525
543
  abortSignal,
526
544
  })),
527
- };
545
+ ...(output != null
546
+ ? await parseBatchOutput({ result: item.result, output })
547
+ : {}),
548
+ } as BatchItemResult<TOOLS, OUTPUT>;
528
549
  case 'failed':
529
550
  return {
530
551
  type: item.type,
@@ -601,6 +622,71 @@ function convertImageResult(
601
622
  };
602
623
  }
603
624
 
625
+ /**
626
+ * Parses the structured output of a successful text item. Failures are
627
+ * reported as `outputError` so that one malformed item does not affect the
628
+ * rest of the batch or discard the item's text and usage.
629
+ */
630
+ async function parseBatchOutput({
631
+ result,
632
+ output,
633
+ }: {
634
+ result: LanguageModelV4GenerateResult;
635
+ output: Output;
636
+ }): Promise<
637
+ { output: unknown } | { outputError: { message: string; type: string } }
638
+ > {
639
+ const generatedText = result.content
640
+ .filter((part): part is Extract<typeof part, { type: 'text' }> => {
641
+ return part.type === 'text';
642
+ })
643
+ .map(part => part.text)
644
+ .join('');
645
+ const finishReason = result.finishReason.unified;
646
+
647
+ // same conditions as generateText: stop responses and non-empty responses
648
+ // that are not tool calls
649
+ if (
650
+ !(
651
+ finishReason === 'stop' ||
652
+ (finishReason !== 'tool-calls' && generatedText.length > 0)
653
+ )
654
+ ) {
655
+ const error = new NoOutputGeneratedError();
656
+ return { outputError: { message: error.message, type: error.name } };
657
+ }
658
+
659
+ const textForOutput =
660
+ (await output.responseFormat)?.type === 'json'
661
+ ? (result.structuredOutputText ?? generatedText)
662
+ : generatedText;
663
+
664
+ try {
665
+ return {
666
+ output: await output.parseCompleteOutput(
667
+ { text: textForOutput },
668
+ {
669
+ response: {
670
+ id: result.response?.id ?? '',
671
+ timestamp: result.response?.timestamp ?? new Date(0),
672
+ modelId: result.response?.modelId ?? '',
673
+ headers: result.response?.headers,
674
+ },
675
+ usage: asLanguageModelUsage(result.usage),
676
+ finishReason,
677
+ },
678
+ ),
679
+ };
680
+ } catch (error) {
681
+ return {
682
+ outputError: {
683
+ message: error instanceof Error ? error.message : String(error),
684
+ type: error instanceof Error ? error.name : 'Error',
685
+ },
686
+ };
687
+ }
688
+ }
689
+
604
690
  async function convertGenerateResult<TOOLS extends ToolSet>({
605
691
  result,
606
692
  tools,
@@ -12,6 +12,7 @@ import {
12
12
  prepareDecisionState,
13
13
  type DecisionState,
14
14
  } from '../decide/decision-state';
15
+ import { isRecord } from '../decide/validate-decision';
15
16
  import { logWarnings } from '../logger/log-warnings';
16
17
  import { resolveExtractionModel } from '../model/resolve-model';
17
18
  import { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';
@@ -40,7 +41,7 @@ export async function extract<
40
41
  headers,
41
42
  providerOptions = {},
42
43
  }: {
43
- /** An extraction model instance. */
44
+ /** An extraction model instance or an ID resolved by the configured default provider. */
44
45
  model: ExtractionModel;
45
46
  state: DecisionState;
46
47
  fields: FIELDS;
@@ -98,13 +99,31 @@ export async function extract<
98
99
  });
99
100
 
100
101
  abortSignal?.throwIfAborted();
102
+ const answers = isRecord(result.answers)
103
+ ? Object.fromEntries(
104
+ Object.entries(result.answers).map(([id, answer]) => {
105
+ if (!isRecord(answer) || answer.type === 'refusal') {
106
+ return [id, answer];
107
+ }
108
+ if (
109
+ answer.value === '' ||
110
+ (Array.isArray(answer.value) && answer.value.length === 0)
111
+ ) {
112
+ const normalized = { ...answer, value: null };
113
+ if (normalized.type === 'list') delete normalized.items;
114
+ return [id, normalized];
115
+ }
116
+ return [id, answer];
117
+ }),
118
+ )
119
+ : result.answers;
101
120
  validateExtractionAnswers({
102
121
  fields,
103
122
  state: preparedState,
104
- answers: result.answers,
123
+ answers,
105
124
  });
106
125
  const refusedFieldIds = Object.keys(fields).filter(
107
- id => result.answers[id]?.type === 'refusal',
126
+ id => answers[id]?.type === 'refusal',
108
127
  );
109
128
  if (refusedFieldIds.length > 0) {
110
129
  throw new ExtractionRefusalError({
@@ -123,7 +142,7 @@ export async function extract<
123
142
  const inputTokens = result.usage?.inputTokens;
124
143
  const outputTokens = result.usage?.outputTokens;
125
144
  return {
126
- answers: result.answers as ExtractionResult<FIELDS>['answers'],
145
+ answers: answers as ExtractionResult<FIELDS>['answers'],
127
146
  usage: {
128
147
  inputTokens,
129
148
  outputTokens,
@@ -0,0 +1,5 @@
1
+ import type { Experimental_ExtractionModelV4 as ExtractionModelV4 } from '@ai-sdk/provider';
2
+
3
+ export type ExtractionProvider = {
4
+ extractionModel?: (modelId: string) => ExtractionModelV4;
5
+ };
@@ -5,7 +5,7 @@ import type {
5
5
  Experimental_ExtractionModelV4Source as ExtractionSource,
6
6
  } from '@ai-sdk/provider';
7
7
 
8
- export type ExtractionModel = ExtractionModelV4;
8
+ export type ExtractionModel = string | ExtractionModelV4;
9
9
 
10
10
  export type ExtractionValue<FIELD extends ExtractionField> = FIELD extends {
11
11
  type: 'number' | 'duration';
@@ -2182,7 +2182,7 @@ class DefaultStreamTextResult<
2182
2182
  stream = applyStreamTextTransforms({
2183
2183
  stream,
2184
2184
  transforms,
2185
- tools: tools as TOOLS,
2185
+ tools: tools ?? ({} as TOOLS),
2186
2186
  stopStream() {
2187
2187
  stitchableStream.terminate();
2188
2188
  isRunning = false;
@@ -111,22 +111,27 @@ export async function validateApprovedToolApprovals<
111
111
  }
112
112
 
113
113
  if (isExecutableTool(tool) && tool.inputSchema != null) {
114
- const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(
115
- approvalRequest,
116
- 'inputSchemaInput',
117
- );
118
- const validation = await safeValidateTypes({
119
- value: hasInputSchemaInput
120
- ? approvalRequest.inputSchemaInput
121
- : toolCall.input,
122
- schema: asSchema(tool.inputSchema),
123
- });
124
-
125
114
  let validationError: unknown;
126
- if (!validation.success) {
127
- validationError = validation.error;
128
- } else {
129
- try {
115
+ try {
116
+ // Preserve the approved input before validators or refiners can mutate
117
+ // it, and give them an independent copy of the schema input.
118
+ const approvedInput = structuredClone(toolCall.input);
119
+ const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(
120
+ approvalRequest,
121
+ 'inputSchemaInput',
122
+ );
123
+ const validation = await safeValidateTypes({
124
+ value: structuredClone(
125
+ hasInputSchemaInput
126
+ ? approvalRequest.inputSchemaInput
127
+ : toolCall.input,
128
+ ),
129
+ schema: asSchema(tool.inputSchema),
130
+ });
131
+
132
+ if (!validation.success) {
133
+ validationError = validation.error;
134
+ } else {
130
135
  const revalidatedToolCall = await refineParsedToolCallInput({
131
136
  toolCall: {
132
137
  ...toolCall,
@@ -135,9 +140,8 @@ export async function validateApprovedToolApprovals<
135
140
  refineToolInput,
136
141
  });
137
142
 
138
- // Clone both inputs into the current realm before comparing them.
143
+ // Normalize the revalidated input to the snapshot's realm.
139
144
  const revalidatedInput = structuredClone(revalidatedToolCall.input);
140
- const approvedInput = structuredClone(toolCall.input);
141
145
 
142
146
  // Revalidation must never change the operation that was approved,
143
147
  // including when older or projected history omits the schema input.
@@ -146,9 +150,9 @@ export async function validateApprovedToolApprovals<
146
150
  'Approved tool input does not match the validated schema output.',
147
151
  );
148
152
  }
149
- } catch (error) {
150
- validationError = error;
151
153
  }
154
+ } catch (error) {
155
+ validationError = error;
152
156
  }
153
157
 
154
158
  if (validationError != null) {
package/src/global.ts CHANGED
@@ -22,6 +22,7 @@ declare global {
22
22
  *
23
23
  * If not set, the default provider is the Vercel AI gateway provider.
24
24
  * An explicitly configured provider must support decision models to use experimental_decide.
25
+ * An explicitly configured provider must support extraction models to use experimental_extract.
25
26
  *
26
27
  * @see https://ai-sdk.dev/docs/ai-sdk-core/provider-management#global-provider-configuration
27
28
  */
@@ -17,6 +17,7 @@ import type { DecisionModel } from '../decide/decision-result';
17
17
  import type { DecisionProvider } from '../decide/decision-provider';
18
18
  import { UnsupportedModelVersionError } from '../error';
19
19
  import type { ExtractionModel } from '../extract/extraction-result';
20
+ import type { ExtractionProvider } from '../extract/extraction-provider';
20
21
  import type { EmbeddingModel } from '../types/embedding-model';
21
22
  import type { LanguageModel } from '../types/language-model';
22
23
  import type { SpeechModel } from '../types/speech-model';
@@ -273,6 +274,30 @@ export function resolveDecisionModel(model: DecisionModel): DecisionModelV4 {
273
274
  export function resolveExtractionModel(
274
275
  model: ExtractionModel,
275
276
  ): ExtractionModelV4 {
277
+ if (typeof model === 'string') {
278
+ const provider = (globalThis.AI_SDK_DEFAULT_PROVIDER ??
279
+ gateway) as ExtractionProvider;
280
+
281
+ if (typeof provider.extractionModel !== 'function') {
282
+ throw new NoSuchModelError({
283
+ modelId: model,
284
+ modelType: 'extractionModel',
285
+ message:
286
+ 'The default provider does not support extraction models. ' +
287
+ 'Pass an extraction model instance or configure AI_SDK_DEFAULT_PROVIDER with an extractionModel method.',
288
+ });
289
+ }
290
+
291
+ const resolvedModel = provider.extractionModel(model);
292
+ if (resolvedModel == null) {
293
+ throw new NoSuchModelError({
294
+ modelId: model,
295
+ modelType: 'extractionModel',
296
+ });
297
+ }
298
+ model = resolvedModel;
299
+ }
300
+
276
301
  const version: string = model.specificationVersion;
277
302
  if (version !== 'v4') {
278
303
  throw new UnsupportedModelVersionError({
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  type Experimental_DecisionModelV4 as DecisionModelV4,
3
3
  type EmbeddingModelV4,
4
+ type Experimental_ExtractionModelV4 as ExtractionModelV4,
4
5
  type Experimental_VideoModelV3,
5
6
  type Experimental_VideoModelV4,
6
7
  type FilesV4,
@@ -17,6 +18,8 @@ import {
17
18
  } from '@ai-sdk/provider';
18
19
  import type { DecisionModel } from '../decide/decision-result';
19
20
  import type { DecisionProvider } from '../decide/decision-provider';
21
+ import type { ExtractionModel } from '../extract/extraction-result';
22
+ import type { ExtractionProvider } from '../extract/extraction-provider';
20
23
  import { asProviderV4 } from '../model/as-provider-v4';
21
24
  import {
22
25
  resolveEmbeddingModel,
@@ -27,6 +30,7 @@ import {
27
30
  resolveTranscriptionModel,
28
31
  resolveVideoModel,
29
32
  resolveDecisionModel,
33
+ resolveExtractionModel,
30
34
  asEvaluationModel,
31
35
  } from '../model/resolve-model';
32
36
  import type { EmbeddingModel } from '../types/embedding-model';
@@ -55,6 +59,7 @@ type ProviderWithOptionalVideoModel = {
55
59
  * @param {Record<string, RerankingModel>} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances.
56
60
  * @param {Record<string, VideoModel>} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances.
57
61
  * @param {Record<string, DecisionModel>} [options.decisionModels] - Experimental decision models or default-provider model IDs, keyed by alias.
62
+ * @param {Record<string, ExtractionModel>} [options.extractionModels] - Experimental extraction models or default-provider model IDs, keyed by alias.
58
63
  * @param {FilesV4} [options.files] - A files interface for uploading files.
59
64
  * @param {SkillsV4} [options.skills] - A skills interface for uploading skills.
60
65
  * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.
@@ -77,6 +82,10 @@ export function customProvider<
77
82
  string,
78
83
  DecisionModel
79
84
  >,
85
+ EXTRACTION_MODELS extends Record<string, ExtractionModel> = Record<
86
+ string,
87
+ ExtractionModel
88
+ >,
80
89
  >({
81
90
  languageModels,
82
91
  embeddingModels,
@@ -87,6 +96,7 @@ export function customProvider<
87
96
  videoModels,
88
97
  decisionModels: decisionModelsArg,
89
98
  evaluationModels,
99
+ extractionModels,
90
100
  files,
91
101
  skills,
92
102
  fallbackProvider: fallbackProviderArg,
@@ -101,6 +111,7 @@ export function customProvider<
101
111
  decisionModels?: DECISION_MODELS;
102
112
  /** @deprecated Use `decisionModels` instead. When both are set, `decisionModels` takes precedence. */
103
113
  evaluationModels?: DECISION_MODELS;
114
+ extractionModels?: EXTRACTION_MODELS;
104
115
  files?: FILES;
105
116
  skills?: SKILLS;
106
117
  fallbackProvider?: FALLBACK;
@@ -119,6 +130,9 @@ export function customProvider<
119
130
  evaluationModel(modelId: ExtractModelId<DECISION_MODELS>): DecisionModelV4 & {
120
131
  doEvaluate: DecisionModelV4['doDecide'];
121
132
  };
133
+ extractionModel(
134
+ modelId: ExtractModelId<EXTRACTION_MODELS>,
135
+ ): ExtractionModelV4;
122
136
  } & (FILES extends FilesV4
123
137
  ? { files(): FilesV4 }
124
138
  : [FALLBACK] extends [{ files: () => FilesV4 }]
@@ -152,6 +166,9 @@ export function customProvider<
152
166
  ): DecisionModelV4 & {
153
167
  doEvaluate: DecisionModelV4['doDecide'];
154
168
  };
169
+ extractionModel(
170
+ modelId: ExtractModelId<EXTRACTION_MODELS>,
171
+ ): ExtractionModelV4;
155
172
  } = {
156
173
  specificationVersion: 'v4',
157
174
  languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV4 {
@@ -259,6 +276,26 @@ export function customProvider<
259
276
  evaluationModel(modelId: ExtractModelId<DECISION_MODELS>) {
260
277
  return asEvaluationModel(this.decisionModel(modelId));
261
278
  },
279
+ extractionModel(
280
+ modelId: ExtractModelId<EXTRACTION_MODELS>,
281
+ ): ExtractionModelV4 {
282
+ if (
283
+ extractionModels != null &&
284
+ Object.hasOwn(extractionModels, modelId)
285
+ ) {
286
+ return resolveExtractionModel(extractionModels[modelId]);
287
+ }
288
+
289
+ const provider = fallbackProviderArg as ExtractionProvider | undefined;
290
+ if (typeof provider?.extractionModel === 'function') {
291
+ const model = provider.extractionModel(modelId);
292
+ if (model != null) {
293
+ return resolveExtractionModel(model);
294
+ }
295
+ }
296
+
297
+ throw new NoSuchModelError({ modelId, modelType: 'extractionModel' });
298
+ },
262
299
  videoModel(
263
300
  modelId: ExtractModelId<VIDEO_MODELS>,
264
301
  ): Experimental_VideoModelV4 {
@@ -10,6 +10,7 @@ export {
10
10
  export type { ProviderRegistryProvider } from './provider-registry';
11
11
 
12
12
  export type { DecisionProviderRegistry as Experimental_DecisionProviderRegistry } from './provider-registry';
13
+ export type { ExtractionProviderRegistry as Experimental_ExtractionProviderRegistry } from './provider-registry';
13
14
 
14
15
  /** @deprecated Use `Experimental_DecisionProviderRegistry` instead. */
15
16
  export type Experimental_EvaluationProviderRegistry<
@@ -27,6 +27,7 @@ export class NoSuchProviderError extends NoSuchModelError {
27
27
  | 'rerankingModel'
28
28
  | 'videoModel'
29
29
  | 'decisionModel'
30
+ | 'extractionModel'
30
31
  /** @deprecated Use `decisionModel` instead. */
31
32
  | 'evaluationModel';
32
33
  providerId: string;
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  type Experimental_DecisionModelV4 as DecisionModelV4,
3
3
  type EmbeddingModelV4,
4
+ type Experimental_ExtractionModelV4 as ExtractionModelV4,
4
5
  type Experimental_VideoModelV3,
5
6
  type Experimental_VideoModelV4,
6
7
  type FilesV4,
@@ -16,8 +17,10 @@ import {
16
17
  } from '@ai-sdk/provider';
17
18
  import type { DecisionModel } from '../decide/decision-result';
18
19
  import type { DecisionProvider } from '../decide/decision-provider';
20
+ import type { ExtractionProvider } from '../extract/extraction-provider';
19
21
  import {
20
22
  resolveDecisionModel,
23
+ resolveExtractionModel,
21
24
  asEvaluationModel,
22
25
  } from '../model/resolve-model';
23
26
  import { wrapImageModel } from '../middleware/wrap-image-model';
@@ -42,7 +45,8 @@ type RegistryModelType =
42
45
  | 'speechModel'
43
46
  | 'rerankingModel'
44
47
  | 'videoModel'
45
- | 'decisionModel';
48
+ | 'decisionModel'
49
+ | 'extractionModel';
46
50
 
47
51
  type ProviderVideoModelIdentifier<PROVIDER> = PROVIDER extends {
48
52
  videoModel: (...args: infer ARGS) => unknown;
@@ -58,6 +62,29 @@ type ProviderDecisionModelIdentifier<PROVIDER> = PROVIDER extends {
58
62
  ? ExtractLiteralUnion<ARGS[0]>
59
63
  : never;
60
64
 
65
+ type ProviderExtractionModelIdentifier<PROVIDER> = PROVIDER extends {
66
+ extractionModel: (...args: infer ARGS) => unknown;
67
+ }
68
+ ? ExtractLiteralUnion<ARGS[0]>
69
+ : never;
70
+
71
+ export type ExtractionProviderRegistry<
72
+ PROVIDERS extends Record<string, ProviderV4 | ProviderV3> = Record<
73
+ string,
74
+ ProviderV4 | ProviderV3
75
+ >,
76
+ SEPARATOR extends string = ':',
77
+ > = DecisionProviderRegistry<PROVIDERS, SEPARATOR> & {
78
+ extractionModel<KEY extends keyof PROVIDERS>(
79
+ id: KEY extends string
80
+ ? `${KEY & string}${SEPARATOR}${ProviderExtractionModelIdentifier<PROVIDERS[KEY]>}`
81
+ : never,
82
+ ): ExtractionModelV4;
83
+ extractionModel<KEY extends keyof PROVIDERS>(
84
+ id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never,
85
+ ): ExtractionModelV4;
86
+ };
87
+
61
88
  /** Registry with experimental decision access, separate from the stable interface. */
62
89
  export type DecisionProviderRegistry<
63
90
  PROVIDERS extends Record<string, ProviderV4 | ProviderV3> = Record<
@@ -194,7 +221,7 @@ export function createProviderRegistry<
194
221
  | LanguageModelMiddleware[];
195
222
  imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[];
196
223
  } = {},
197
- ): DecisionProviderRegistry<PROVIDERS, SEPARATOR> {
224
+ ): ExtractionProviderRegistry<PROVIDERS, SEPARATOR> {
198
225
  const registry = new DefaultProviderRegistry<PROVIDERS, SEPARATOR>({
199
226
  separator,
200
227
  languageModelMiddleware,
@@ -222,12 +249,16 @@ class DefaultProviderRegistry<
222
249
  >
223
250
  implements
224
251
  ProviderRegistryProvider<PROVIDERS, SEPARATOR>,
225
- DecisionProviderRegistry<PROVIDERS, SEPARATOR>
252
+ DecisionProviderRegistry<PROVIDERS, SEPARATOR>,
253
+ ExtractionProviderRegistry<PROVIDERS, SEPARATOR>
226
254
  {
227
255
  private providers: Partial<
228
256
  Record<
229
257
  keyof PROVIDERS,
230
- ProviderV4 & ProviderWithOptionalVideoModel & DecisionProvider
258
+ ProviderV4 &
259
+ ProviderWithOptionalVideoModel &
260
+ DecisionProvider &
261
+ ExtractionProvider
231
262
  >
232
263
  > = Object.create(null);
233
264
  private separator: SEPARATOR;
@@ -268,6 +299,9 @@ class DefaultProviderRegistry<
268
299
  const decisionModel = (
269
300
  decisionProvider.decisionModel ?? decisionProvider.evaluationModel
270
301
  )?.bind(provider);
302
+ const extractionModel = (
303
+ provider as ExtractionProvider
304
+ ).extractionModel?.bind(provider);
271
305
 
272
306
  const registeredProvider =
273
307
  videoModel == null
@@ -282,13 +316,19 @@ class DefaultProviderRegistry<
282
316
  if (registeredProvider !== provider && decisionModel != null) {
283
317
  Object.assign(registeredProvider, { decisionModel });
284
318
  }
319
+ if (registeredProvider !== provider && extractionModel != null) {
320
+ Object.assign(registeredProvider, { extractionModel });
321
+ }
285
322
  this.providers[id] = registeredProvider;
286
323
  }
287
324
 
288
325
  private getProvider(
289
326
  id: string,
290
327
  modelType: RegistryModelType,
291
- ): ProviderV4 & ProviderWithOptionalVideoModel & DecisionProvider {
328
+ ): ProviderV4 &
329
+ ProviderWithOptionalVideoModel &
330
+ DecisionProvider &
331
+ ExtractionProvider {
292
332
  const provider = this.providers[id as keyof PROVIDERS];
293
333
 
294
334
  if (provider == null) {
@@ -468,6 +508,20 @@ class DefaultProviderRegistry<
468
508
  return asEvaluationModel(this.decisionModel(id));
469
509
  }
470
510
 
511
+ extractionModel<KEY extends keyof PROVIDERS>(
512
+ id: `${KEY & string}${SEPARATOR}${string}`,
513
+ ): ExtractionModelV4 {
514
+ const [providerId, modelId] = this.splitId(id, 'extractionModel');
515
+ const provider = this.getProvider(providerId, 'extractionModel');
516
+ const model = provider.extractionModel?.(modelId);
517
+
518
+ if (model == null) {
519
+ throw new NoSuchModelError({ modelId: id, modelType: 'extractionModel' });
520
+ }
521
+
522
+ return resolveExtractionModel(model);
523
+ }
524
+
471
525
  files<KEY extends keyof PROVIDERS>(id: KEY & string): FilesV4 {
472
526
  const provider = this.getProvider(id, 'languageModel');
473
527
  const files = provider.files?.();
@@ -58,7 +58,7 @@ function mapArray(
58
58
  return copy.some((entry, index) => entry !== value[index]) ? copy : value;
59
59
  }
60
60
 
61
- /** Preserve result getters, streams, and property descriptors without mutation. */
61
+ /** Preserve result getters and property descriptors without mutation. */
62
62
  function replaceProperties<T>(
63
63
  value: T,
64
64
  redactors: Record<string, (value: unknown) => unknown>,
@@ -74,7 +74,25 @@ function replaceProperties<T>(
74
74
  descriptors[key] = { ...descriptor, value: redacted };
75
75
  }
76
76
  }
77
- return descriptors == null
78
- ? value
79
- : Object.create(Object.getPrototypeOf(value), descriptors);
77
+ if (descriptors == null) return value;
78
+
79
+ // Instrumentation replaces result.stream with a tapped stream, locking the
80
+ // original. Forward replacements so the application consumes the tapped stream.
81
+ const streamDescriptor = descriptors.stream;
82
+ if (
83
+ streamDescriptor?.writable &&
84
+ streamDescriptor.value instanceof ReadableStream
85
+ ) {
86
+ const original: Record<string, unknown> = value;
87
+ descriptors.stream = {
88
+ configurable: streamDescriptor.configurable,
89
+ enumerable: streamDescriptor.enumerable,
90
+ get: () => original.stream,
91
+ set: stream => {
92
+ original.stream = stream;
93
+ },
94
+ };
95
+ }
96
+
97
+ return Object.create(Object.getPrototypeOf(value), descriptors);
80
98
  }