ai_extract函式

適用於:check 標示為 Yes Databricks SQL 檢查標示為 Yes Databricks Runtime

這個 ai_extract() 函式會根據你提供的架構,從文字和文件中擷取結構化資料。 你可以用簡單的欄位名稱來進行基本擷取,或是定義複雜的結構結構,包含巢狀物件、陣列、型別驗證,以及商業文件如發票、合約和財務申報的欄位描述。

此函式接受文字或 VARIANT 來自其他 AI 函式的 ai_parse_document輸出,如 ,實現可組合的工作流程,實現端到端的文件處理。

若要用視覺化介面驗證並迭代 的 ai_extract結果,請參見 資訊擷取。

需求

Apache 2.0 授權

目前可能使用的底層模型依照 Apache 2.0 授權,版權屬於 © Apache 軟體基金會。 客戶應負責確保遵循適用的模型授權。

Databricks 建議檢閱這些授權,以確保符合任何適用的條款。 如果未來模型根據 Databricks 的內部基準檢驗而表現更好,Databricks 可能會變更模型(以及此頁面上提供的適用授權清單)。

支撐此功能的模型是透過 Model Serving Foundation 模型 API 提供。 請參閱 適用模型條款 ,了解 Databricks 上可用的模型,以及管理這些模型使用的授權與政策。

如果未來模型根據 Databricks 的內部基準檢驗而表現更好,Databricks 可能會變更模型並更新檔。

Tip

Databricks 建議使用 2.0 版本或更新版本。ai_extract 1.0 版本是舊有介面,不支援這些功能,且不建議用於新建或生產工作負載。

2.0 版本及以後版本支援,

  • 豐富的 JSON 架構,包含巢狀物件、陣列、型別驗證及欄位描述
  • 同時接受兩者 STRING ,也 VARIANT 接受來自上游 AI 功能的輸入,例如 ai_parse_document

2.1 版本也新增了引用次數與信心分數。

若要明確釘選版本,請傳遞 options => map('version', '2.1')。

數據安全性

您的文件數據會在 Databricks 安全性周邊內處理。 Databricks 不儲存傳遞給 AI 函式呼叫的參數,但會保留元資料執行細節,例如 Databricks 執行時版本。

語法

ai_extract(content, schema [, options])

第 2 版

ai_extract(content, schema [, options])

版本 1(傳承)

ai_extract(content, labels [, options])

引數

  • content VARIANT:或STRING表達式。 接受以下任一:

    • 原始文字作為 STRING
    • 由另一個 AI 函數(例如 VARIANT) 產生的ai_parse_document
  • schema: 一個 STRING 定義提取用 JSON 架構的字面值。 該模式可以是:

    • 簡單結構:一個 JSON 陣列,包含欄位名稱(假設為字串)
      "[\"vendor_name\", \"invoice_id\", \"total_amount\"]"
      
    • 進階結構:一個包含型別資訊、描述與巢狀結構的 JSON 物件
      • 支援、stringinteger、number、booleanenum、及類型。 執行型別驗證。 不有效的數值會導致錯誤。 最多可有 500 個 enum 值。
      • 支援巢狀物件,使用"type": "object""properties"
      • 支援使用 "type": "array" 的原始元件或物件陣列 "items"
      • 每個物業的選用 "description" 欄位用以指導萃取品質
  • options:一個包含配置選項的可選 MAP<STRING, STRING> 性:

    • version: 版本切換以支援遷移 ("2.1", "2.0", "1.0")。 預設是根據輸入類型來決定的。
    • instructions: 全域描述任務與領域以提升擷取品質。 字元必須少於20,000字元。
    • mode: 設為 "precision" 為為擷取,優化於長文件、高容量輸出及大型、深度巢狀或需要推理的複雜結構。 例如,使用精確模式從發票中提取數百項行項,拉取跨多頁文件指定的合約條款,並填充需要推理的結構,例如計算指標與評分。
    • enableCitations當 true時,擷取結構中每個欄位的輸出包含零個或多個引用,文件中顯示該輸出被擷取。
    • enableConfidenceScores當 true時,萃取模式中每個欄位的輸出包含介於 0 到 1 之間的信心分數,顯示模型對該值的確定度。 適當的信心門檻取決於你的具體使用情境,你應該選擇一個符合你對風險與錯誤容忍度的臨界值。

第 2 版

  • content VARIANT:或STRING表達式。 接受以下任一:

    • 原始文字作為 STRING
    • 由另一個 AI 函數(例如 VARIANT) 產生的ai_parse_document
  • schema: 一個 STRING 定義提取用 JSON 架構的字面值。 該模式可以是:

    • 簡單結構:一個 JSON 陣列,包含欄位名稱(假設為字串)
      "[\"vendor_name\", \"invoice_id\", \"total_amount\"]"
      
    • 進階結構:一個包含型別資訊、描述與巢狀結構的 JSON 物件
      • 支援、stringinteger、number、booleanenum、及類型。 執行型別驗證。 不有效的數值會導致錯誤。 最多可有 500 個 enum 值。
      • 支援巢狀物件,使用"type": "object""properties"
      • 支援使用 "type": "array" 的原始元件或物件陣列 "items"
      • 每個物業的選用 "description" 欄位用以指導萃取品質
  • options:一個包含配置選項的可選 MAP<STRING, STRING> 性:

    • version:版本切換以支援遷移("1.0" 針對 v1 行為,針對 "2.0" v2 行為)。 預設是基於輸入類型,但會退回到 "1.0"。
    • instructions: 全域描述任務與領域以提升擷取品質。 字元必須少於20,000字元。
    • mode:設定為 "precision" 更強大的擷取,優化於長文件、高容量輸出及複雜結構——大型、深度巢狀或需推理。 例如,使用精確模式從發票中提取數百項行項,拉取跨多頁文件指定的合約條款,並填充需要推理的結構,例如計算指標與評分。

版本 1(傳承)

  • content:一個 STRING 包含原始文字的表達式。

  • labels:ARRAY<STRING> 常數。 每個元素都是要擷取的實體類型。

  • options:一個包含配置選項的可選 MAP<STRING, STRING> 性:

    • version:版本切換以支援遷移("1.0" 針對 v1 行為,針對 "2.0" v2 行為)。 預設值是基於輸入類型,但會退回到 "1.0"。

退貨

返回包含 VARIANT :

{
  "response": {...},       // Extracted data matching the provided schema. Each leaf is returned as a Field object (see below).
  "error_message": null,   // null on success, or error message on failure
  "metadata": { ... }      // Metadata about the response, including version and citation details.
}

欄位 response 包含依照結構模式擷取的結構化資料:

  • 欄位名稱與類型與結構定義相符
  • 結構在回應中得以保留:巢狀物件與陣列保持原始形狀。 擷取模式中的每個「純量」欄位都有一個輸出物件,包含以下欄位:
    • value:根據結構型別的擷取值。 Null 如果該場無法被抽取。
    • citation_ids:僅當 enableCitations 為 時 true才出現。 一個索引為 metadata.citations的 ID 陣列。
    • confidence_score:僅當 enableConfidenceScores 為 時 true才出現。 介於 0 和 1 之間的 浮點數 。
  • 類型驗證對整數、數字、布林和枚舉類型都強制執行
  • 如果 content 是 NULL,結果就是 NULL。

該 metadata 欄位包含關於回應的元資料。 當 mode 在請求中設定時,metadata包含使用過的。mode 當 enableCitations 為 true時,也會包含欄位中 response 每個引用 ID 的詳細資料,追蹤擷取值至輸入中的位置。

根據輸入類型,引用可能分為兩種類型:

  • 對於原始文字(STRING)輸入,引用是原始輸入中的一段文字。 metadata.citations 中的每個物件包含:
    • id:整數匹配域上的 citation_ids 條目。
    • start:包含以 0 為基礎的字元偏移到輸入字串中。
    • stop: 輸入字串中排他以 0 為基礎的字元偏移。
  • 對於 PDF 文件和圖片(使用 ai_extract 下游 ai_parse_document時),引用是在原始輸入中作為邊界框。 每個物件 metadata.citations 包含:
    • id:整數匹配 citation_ids 欄位上的一個項目。
    • bbox: 物件陣列 {coord, page_id} ,輸出形狀與 element.bbox ai_parse_document 完全相同。 coord 是頁面影像上的像素座標,而 [x0, y0, x1, y1]; page_id 0 為基礎的頁面索引則是。

第 2 版

返回包含 VARIANT :

{
  "response": { ... },   // Extracted data matching the provided schema
  "metadata": {
    "version": "2.0"     // Function version used
  },
  "error_message": null  // null on success, or error message on failure
}

欄位 response 包含依照結構模式擷取的結構化資料:

  • 欄位名稱與類型與結構定義相符
  • 巢狀物件與陣列會保留在結構中
  • 若未找到欄位,則可null
  • 類型驗證對 、 integer、 number及 boolean 類型都會強制enum執行

該 metadata 欄位包含關於回應的元資料。

如果 content 是 NULL,結果就是 NULL。

版本 1(傳承)

回傳 a STRUCT ,每個欄位對應於 中 labels指定的實體類型。 每個欄位都包含代表所擷取實體的字串。 若函式對任何實體類型找到多個候選,則只會回傳一個。

範例

簡單架構-僅有欄位名稱

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '["invoice_id", "vendor_name", "total_amount", "invoice_date"]',
    options => map('version', '2.1')
  );
 {
   "response": {
     "invoice_id":   {"value": "12345"},
     "vendor_name":  {"value": "Acme Corp"},
     "total_amount": {"value": "1250.00"},
     "invoice_date": {"value": "2024-01-15"}
   },
   "error_message": null
 }

進階結構-包含類型與描述

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '{
      "invoice_id": {"type": "string", "description": "Unique invoice identifier"},
      "vendor_name": {"type": "string", "description": "Legal business name"},
      "total_amount": {"type": "number", "description": "Total invoice amount"},
      "invoice_date": {"type": "string", "description": "Date in YYYY-MM-DD format"}
    }',
    options => map('version', '2.1')
  );
 {
   "response": {
     "invoice_id":   {"value": "12345"},
     "vendor_name":  {"value": "Acme Corp"},
     "total_amount": {"value": 1250.00},
     "invoice_date": {"value": "2024-01-15"}
   },
   "error_message": null
 }

巢狀物件與陣列

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp
     Line 1: Widget A, qty 10, $50.00 each
     Line 2: Widget B, qty 5, $100.00 each
     Subtotal: $1,000.00, Tax: $80.00, Total: $1,080.00',
    '{
      "invoice_header": {
        "type": "object",
        "properties": {
          "invoice_id": {"type": "string"},
          "vendor_name": {"type": "string"}
        }
      },
      "line_items": {
        "type": "array",
        "description": "List of invoiced products",
        "items": {
          "type": "object",
          "properties": {
            "description": {"type": "string"},
            "quantity": {"type": "integer"},
            "unit_price": {"type": "number"}
          }
        }
      },
      "totals": {
        "type": "object",
        "properties": {
          "subtotal": {"type": "number"},
          "tax_amount": {"type": "number"},
          "total_amount": {"type": "number"}
        }
      }
    }',
    options => map('version', '2.1')
  );
 {
   "response": {
     "invoice_header": {
       "invoice_id":  {"value": "12345"},
       "vendor_name": {"value": "Acme Corp"}
     },
     "line_items": [
       {"description": {"value": "Widget A"}, "quantity": {"value": 10}, "unit_price": {"value": 50.00}},
       {"description": {"value": "Widget B"}, "quantity": {"value": 5},  "unit_price": {"value": 100.00}}
     ],
     "totals": {
       "subtotal":     {"value": 1000.00},
       "tax_amount":   {"value": 80.00},
       "total_amount": {"value": 1080.00}
     }
   },
   "error_message": null
 }

可組合性為 ai_parse_document

> WITH parsed_docs AS (
    SELECT
      path,
      ai_parse_document(
        content,
        MAP('version', '2.0')
      ) AS parsed_content
    FROM READ_FILES('/Volumes/finance/invoices/', format => 'binaryFile')
  )
  SELECT
    path,
    ai_extract(
      parsed_content,
      '["invoice_id", "vendor_name", "total_amount"]',
      MAP('version', '2.1', 'instructions', 'These are vendor invoices.')
    ) AS invoice_data
  FROM parsed_docs;

使用枚舉

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp, amount: $1,250.00 USD',
    '{
      "invoice_id": {"type": "string"},
      "vendor_name": {"type": "string"},
      "total_amount": {"type": "number"},
      "currency": {
        "type": "enum",
        "labels": ["USD", "EUR", "GBP", "CAD", "AUD"],
        "description": "Currency code"
      },
      "payment_terms": {"type": "string"}
    }',
    options => map('version', '2.1')
  );
 {
   "response": {
     "invoice_id":     {"value": "12345"},
     "vendor_name":    {"value": "Acme Corp"},
     "total_amount":   {"value": 1250.00},
     "currency":       {"value": "USD"},
     "payment_terms":  {"value": null}
   },
   "error_message": null
 }

引用(STRING 輸入、SPAN 引用)

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '{
      "invoice_id": {"type": "string", "description": "Unique invoice identifier"},
      "vendor_name": {"type": "string", "description": "Legal business name"},
      "total_amount": {"type": "number", "description": "Total invoice amount"},
      "invoice_date": {"type": "string", "description": "Date in YYYY-MM-DD format"}
    }',
   options => map(
     'version', '2.1',
     'enableCitations', 'true'
   )
  );
 {
   "response": {
     "invoice_id": {"citation_ids": [0], "value": "12345"},
     "vendor_name": {"citation_ids": [0], "value": "Acme Corp"},
     "total_amount": {"citation_ids": [1], "value": 1250.00},
     "invoice_date": {"citation_ids": [1], "value": "2024-01-15"}
   },
   "metadata": {
     "version": "2.1",
     "chunk_type": "span",
     "citations": [
       {"id": 0, "start": 0, "stop": 29},
       {"id": 1, "start": 29, "stop": 60}
     ]
   },
   "error_message": null
 }

引用(來自ai_parse_document年變體,BBOX 引用)

> WITH parsed AS (
    SELECT ai_parse_document(
             content,
             map('imageOutputPath', '/Volumes/main/default/parsed_images/')  // necessary for rendering bboxes
           ) AS doc
    FROM READ_FILES('/Volumes/main/default/invoices/invoice.pdf', format => 'binaryFile')
  )
  SELECT ai_extract(
    doc,
    '{"invoice_id":{"type":"string"}, "total_amount":{"type":"number"}}',
    options => map('version','2.1','enableCitations','true')
  ) AS extracted
  FROM parsed;
{
  "response": {
    "invoice_id":   {"citation_ids": [0], "value": "12345"},
    "total_amount": {"citation_ids": [1], "value": 1250.00}
  },
  "metadata": {
    "version": "2.1",
    "chunk_type": "bbox",
    "citations": [
      {"id": 0, "bbox": [{"coord": [120, 80,  240, 110], "page_id": 0}]},
      {"id": 1, "bbox": [{"coord": [400, 500, 560, 530], "page_id": 0}]}
    ],
    "pages": [{"id": 0, "image_uri": "/Volumes/main/default/parsed_images/6077ca79...f8efdb2ed05.jpg"}]
  },
  "error_message": null
}

信心分數


> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '{
      "invoice_id": {"type": "string", "description": "Unique invoice identifier"},
      "vendor_name": {"type": "string", "description": "Legal business name"},
      "total_amount": {"type": "number", "description": "Total invoice amount"},
      "invoice_date": {"type": "string", "description": "Date in YYYY-MM-DD format"}
    }',
   options => map(
    'version', '2.1',
    'enableConfidenceScores', 'true'
   )
  );
{
  "response": {
    "invoice_id": {"confidence_score": 0.95, "value": "12345"},
    "vendor_name": {"confidence_score": 0.62, "value": "Acme Corp"},
    "total_amount": {"confidence_score": 1.0, "value": 1250.00},
    "invoice_date": {"confidence_score": 0.99, "value": "2024-01-15"}
  },
  "error_message": null
}

精密模式

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '["invoice_id", "vendor_name", "total_amount"]',
   options => map(
    'version', '2.1',
    'mode', 'precision'
   )
  );
{
  "response": {
    "invoice_id":   {"value": "12345"},
    "vendor_name":  {"value": "Acme Corp"},
    "total_amount": {"value": 1250.00}
  },
  "metadata": {
    "version": "2.1",
    "mode": "precision"
  },
  "error_message": null
}

筆記本範例

以下筆記本提供視覺化除錯介面,用於分析函 ai_extract 式的引用輸出。 它示範如何將引用元資料呈現為子字串摘要(STRING 輸入)或邊界框覆蓋(VARIANT 輸入),並將 ai_extract 引用連結回 ai_parse_document SQL 元素,讓你能標記低信心抽取供人工審查。

引用呈現筆記本

拿筆記本

第 2 版

簡單架構-僅有欄位名稱

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '["invoice_id", "vendor_name", "total_amount", "invoice_date"]'
  );
 {
   "response": {
     "invoice_id": "12345",
     "vendor_name": "Acme Corp",
     "total_amount": "1250.00",
     "invoice_date": "2024-01-15"
   },
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }

進階結構-包含類型與描述

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '{
      "invoice_id": {"type": "string", "description": "Unique invoice identifier"},
      "vendor_name": {"type": "string", "description": "Legal business name"},
      "total_amount": {"type": "number", "description": "Total invoice amount"},
      "invoice_date": {"type": "string", "description": "Date in YYYY-MM-DD format"}
    }'
  );
 {
   "response": {
     "invoice_id": "12345",
     "vendor_name": "Acme Corp",
     "total_amount": 1250.00,
     "invoice_date": "2024-01-15"
   },
   "metadata": {
     "version": "2.0"
   },
   "error_message": null
 }

巢狀物件與陣列

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp
     Line 1: Widget A, qty 10, $50.00 each
     Line 2: Widget B, qty 5, $100.00 each
     Subtotal: $1,000.00, Tax: $80.00, Total: $1,080.00',
    '{
      "invoice_header": {
        "type": "object",
        "properties": {
          "invoice_id": {"type": "string"},
          "vendor_name": {"type": "string"}
        }
      },
      "line_items": {
        "type": "array",
        "description": "List of invoiced products",
        "items": {
          "type": "object",
          "properties": {
            "description": {"type": "string"},
            "quantity": {"type": "integer"},
            "unit_price": {"type": "number"}
          }
        }
      },
      "totals": {
        "type": "object",
        "properties": {
          "subtotal": {"type": "number"},
          "tax_amount": {"type": "number"},
          "total_amount": {"type": "number"}
        }
      }
    }'
  );
 {
   "response": {
     "invoice_header": {
       "invoice_id": "12345",
       "vendor_name": "Acme Corp"
     },
     "line_items": [
       {"description": "Widget A", "quantity": 10, "unit_price": 50.00},
       {"description": "Widget B", "quantity": 5, "unit_price": 100.00}
     ],
     "totals": {
       "subtotal": 1000.00,
       "tax_amount": 80.00,
       "total_amount": 1080.00
     }
   },
   "metadata": {
     "version": "2.0"
   },
   "error": null
 }

可組合性為 ai_parse_document

> WITH parsed_docs AS (
    SELECT
      path,
      ai_parse_document(
        content,
        MAP('version', '2.0')
      ) AS parsed_content
    FROM READ_FILES('/Volumes/finance/invoices/', format => 'binaryFile')
  )
  SELECT
    path,
    ai_extract(
      parsed_content,
      '["invoice_id", "vendor_name", "total_amount"]',
      MAP('instructions', 'These are vendor invoices.')
    ) AS invoice_data
  FROM parsed_docs;

使用枚舉

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp, amount: $1,250.00 USD',
    '{
      "invoice_id": {"type": "string"},
      "vendor_name": {"type": "string"},
      "total_amount": {"type": "number"},
      "currency": {
        "type": "enum",
        "labels": ["USD", "EUR", "GBP", "CAD", "AUD"],
        "description": "Currency code"
      },
      "payment_terms": {"type": "string"}
    }'
  );
 {
   "response": {
     "invoice_id": "12345",
     "vendor_name": "Acme Corp",
     "total_amount": 1250.00,
     "currency": "USD",
     "payment_terms": null
   },
   "metadata": {
     "version": "2.0"
   },
   "error": null
 }

精密模式

> SELECT ai_extract(
    'Invoice #12345 from Acme Corp for $1,250.00 dated 2024-01-15',
    '["invoice_id", "vendor_name", "total_amount"]',
    options => map('version', '2.0', 'mode', 'precision')
  );
 {
   "response": {
     "invoice_id": "12345",
     "vendor_name": "Acme Corp",
     "total_amount": 1250.00
   },
   "metadata": {
     "version": "2.0",
     "mode": "precision"
   },
   "error_message": null
 }

版本 1(傳承)

> SELECT ai_extract(
    'John Doe lives in New York and works for Acme Corp.',
    array('person', 'location', 'organization')
  );
 {"person": "John Doe", "location": "New York", "organization": "Acme Corp."}

> SELECT ai_extract(
    'Send an email to jane.doe@example.com about the meeting at 10am.',
    array('email', 'time')
  );
 {"email": "jane.doe@example.com", "time": "10am"}

局限性

  • 此函式在 Azure Databricks SQL Classic 中無法使用。
  • 此函式無法用於 視圖。
  • 該結構最多支援 256 個欄位。
  • 欄位名稱最多可包含 150 個字元。
  • 結構結構支援巢狀欄位最多 12 層的巢式。
  • 枚舉欄位最多支援 500 個值。
  • 類型驗證對 、 integer、 number及 boolean 類型進行enum強制執行。 若值與指定型別不符,函式會回傳錯誤。
  • 最大總上下文大小為 100 萬個代幣。

第 2 版

  • 此函式在 Azure Databricks SQL Classic 中無法使用。
  • 此函式無法用於 視圖。
  • 該結構最多支援 256 個欄位。
  • 欄位名稱最多可包含 150 個字元。
  • 結構結構支援巢狀欄位最多 12 層的巢式。
  • 枚舉欄位最多支援 500 個值。
  • 類型驗證對 、 integer、 number及 boolean 類型進行enum強制執行。 若值與指定型別不符,函式會回傳錯誤。
  • 最大總上下文大小為 100 萬個代幣。

版本 1(傳承)

  • 此函式在 Azure Databricks SQL Classic 中無法使用。
  • 此函式無法用於檢視。
  • 若內容中發現同一實體類型的多個候選,則只會回傳一個值。