翻篇收录说明
翻篇网页快照

Extractions | AI SDK

https://ai-sdk.dev/docs/ai-sdk-core/extractions

最近抓取:2026-12-04 02:45:13(北京时间)

最近内容变化:2026-11-30 23:26:04(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Extract typed field values from shared state.

正文摘录

AI SDK CoreMenuExtractionsCopy for LLMView MarkdownAsk AI about this pageexperimental_extract pulls typed values out of one shared state using an extraction model: an invoice number, a total, a due date, a list of names. Each field is described once and comes back as one typed answer. State can be a string, JSON object, or an array of ordered text, file, and JSON parts, the same as decisions. This API and the extraction model specification are experimental and may change in patch releases. Pass an extraction model instance, resolve a model through a provider registry, or use a string ID resolved by the default provider. import { experimental_extract, type Experimental_ExtractionModel } from 'ai'; async function readInvoice(model: Experimental_ExtractionModel, text: string) { return experimental_extract({ model, state: text, referenceDate: '2026-11-11', fields: { invoiceNumber: { type: 'text', instructions: 'The invoice number' }, total: { type: 'number', instructions: 'Total amount due', unit: 'USD', decimals: 2, }, dueDate: { type: 'date', instructions: 'Payment due date' }, contacts: { type: 'list', items: 'text', instructions: 'Contact names' }, }, }); } const { answers } = await readInvoice( model, 'Invoice INV-2041, total due $1,250.00 by March 3. Contacts: Ana, Bo.', ); answers.total.value; // number | null answers.dueDate.value; // string | null, e.g. '2027-03-03' answers.contacts.value; // string[] | null referenceDate is an optional YYYY-MM-DD date that anchors relative dates and dates without a year. File URLs Remote file URLs in state require experimental_download; otherwise extraction throws DownloadError before making a network request. Inline bytes and data URLs work without a download hook. The model's custom fetch does not cover these core downloads. For user-supplied URLs on Node.js, configure a DNS-protected transport: import { createGuardedFetch } from 'guarded-fetch'; import { createDownload, experimental_extract, type Experimental_ExtractionModel, } from 'ai'; async function readInvoiceFile(model: Experimental_ExtractionModel, url: URL) { const fetch = createGuardedFetch(); try { return await experimental_extract({ model, state: [{ type: 'file', mediaType: 'application/pdf', data: url }], fields: { invoiceNumber: { type: 'text' } }, experimental_download: createDownload({ fetch }), }); } finally { await fetch.close(); } } See Secure URL Fetching for installation and transport requirements on other server runtimes. Field types Every field has a type and optional instructions. Instructions accept strings, JSON objects, or JSON arrays. TypeValueOptionstextstringNonenumberFinite numberunit (e.g. 'USD'), integer, decimals (0 to 6)date'YYYY-MM-DD', a real calendar dateNonetime'HH:MM' or 'HH:MM:SS'NonedatetimeISO 8601 date and time, with an offset when availableNonedurationNonnegative number in unitunit (seconds, minutes, hours, days, weeks, months, years), integer, decimalsliststring[] or number[]Required items ('text', 'number', or 'date'), integer and decimals for numbers Answer value types are inferred from the field definitions. Provider models Use a provider's extractionModel factory: ProviderExample modelOpenAIopenai.extractionModel('gpt-6.1-sol')Anthropicanthropic.extractionModel('claude-sonnet-5-5')Googlegoogle.extractionModel('gemini-4-hydrogen') These adapt structured language-model output and extract every field in one prompt. Anthropic sends more than 16 fields as parallel calls, see Anthropic extraction models. They return null for missing values but no pNull, confidence, guess, or source. Judge quality against your own labeled examples before choosing a model for a task. Empty strings and empty lists are returned as null. Numbers, durations, and number list items are rounded to decimals. When the provider refuses a request, the fields in that request are reported as refused and experimental_extract throws Experimental_ExtractionRefusalError. The AI Gateway serves extraction models from several providers through gateway.extractionModel('scaledown/extract-1'). Supported field types depend on the model, so the gateway reports an unsupported field after the request is sent. Model aliases and registries Use customProvider to give extraction models application-specific names, then register providers with createProviderRegistry: import { anthropic } from '@ai-sdk/anthropic'; import { openai } from '@ai-sdk/openai'; import { createProviderRegistry, customProvider, experimental_extract, } from 'ai'; const registry = createProviderRegistry({ invoices: customProvider({ extractionModels: { fast: openai.extractionModel('gpt-6.1-sol'), careful: anthropic.extractionModel('claude-sonnet-5-5'), }, fallbackProvider: openai, }), anthropic, }); const { answers } = await experimental_extract({ model: registry.extractionModel('invoices:fast'), state: 'Invoice INV-2041, total due $1,250.00.', fields: { total: { type: 'number', decimals: 2 } }, }); Registry IDs use providerId:modelId. Custom aliases take precedence over a fallback provider, and a fallback only resolves unknown model IDs. String IDs passed directly to experimental_extract resolve through the default provider. That is the AI Gateway unless globalThis.AI_SDK_DEFAULT_PROVIDER is set, so model: 'scaledown/extract-1' works without a provider import. A configured default provider must have an extractionModel method. This exposes an alias from the registry above through a custom provider: globalThis.AI_SDK_DEFAULT_PROVIDER = customProvider({ extractionModels: { careful: registry.extractionModel('invoices:careful') }, }); await experimental_extract({ model: 'careful', state: 'Invoice INV-2041, total due $1,250.00.', fields: { total: { type: 'number', decimals: 2 } }, }); Resolution errors use NoSuchModelError and NoSuchProviderError with modelType: 'extractionModel'. Answers Every answer has the field's type and a value. value is null when the state does not contain a value for the field. Models can add: pNull: probability in [0, 1] that the state does not contain a value. confidence: confidence in [0, 1] that value is correct. guess: the most likely value, also when value is null. Not on lists. source: where the value was found. Not on lists. { type: 'text', part, start, end }: state[part].text.slice(start, end), with offsets in UTF-16 code units, so the slice works directly in JavaScript. A string state is part 0. { type: 'file', part }: the value was read from the file at state[part]. List answers can include items, one { confidence?, source? } entry per value. Errors Unsupported field types throw Experimental_ExtractionUnsupportedFieldTypeError, before provider I/O or, for AI Gateway models, after the gateway rejects the field. Invalid inputs throw InvalidArgumentError; malformed answers throw InvalidResponseDataError. Fields the model refuses throw Experimental_ExtractionRefusalError. Invalid answers and refusals are not retried, and partial results are not supported. Telemetry experimental_extract accepts the standard telemetry option, runtimeContext, and onStart and onEnd callbacks. Because extraction is experimental, custom integrations receive its lifecycle through experimental_onExtractStart, experimental_onExtractionModelCallStart, experimental_onExtractionModelCallEnd, and experimental_onExtractEnd; errors use onError. With recordInputs: false, integrations do not receive the state, fields, or reference date, and with recordOutputs: false they do not receive answers. Request headers and provider options are never sent to telemetry because they can contain credentials, and file URLs and references in the state are replaced with [redacted]; onStart and onEnd still receive the original values. See Telemetry for the OpenTelemetry spans. Testing Use Experimental_ExtractionMockModelV4 from ai/test: import { experimental_extract } from 'ai'; import { Experimental_ExtractionMockModelV4 } from 'ai/test'; const result = await experimental_extract({ model: new Experimental_ExtractionMockModelV4({ doExtract: async () => ({ answers: { total: { type: 'number', value: 1250 } }, warnings: [], }), }), state: 'Total due: $1,250.00', fields: { total: { type: 'number', decimals: 2 } }, }); Provider specification Experimental_ExtractionModelV4 is exported from @ai-sdk/provider and declares specificationVersion: 'v4', provider, modelId, supportedFieldTypes, and doExtract(options). Extraction models are isolated from stable ProviderV4.PreviousDecisionsNextImage Generation