ai_parse_document函式

適用於:勾選為「是」Databricks SQL 勾選為「是」Databricks Runtime

此功能 ai_parse_document() 利用最先進的 Databricks 管理研究技術,從非結構化文件中解析結構化內容。

如需視覺化使用者介面以驗證並迭代 的 ai_parse_document結果,請參見 文件解析

Requirements

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

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

  • 此功能僅在部分地區提供,詳見 AI 功能可用性
  • Databricks 執行環境 17.3 或以上。
  • 如果您使用無伺服器計算,也需要下列項目:
    • 無伺服器環境版本必須設定為 3 或更高版本,因為這會啟用 VARIANT.
    • 必須使用 Python 或 SQL 其中之一。 如需其他無伺服器功能和限制,請參閱 無伺服器計算限制
  • ai_parse_document 函式可使用 Databricks 筆記本、SQL 編輯器、Databricks 工作流程、作業或 Lakeflow Spark 宣告式管線使用。
  • ai_parse_document 裡,成本被記錄為 AI_FUNCTIONS 產品的一部分。 如需範例查詢,請參閱檢視執行成本ai_parse_document

數據安全性

您的文件數據會在 Databricks 安全性周邊內處理。 Databricks 不會儲存傳入 ai_parse_document function 呼叫的參數,但會保留詮釋資料中的執行詳細數據,例如所使用的 Databricks 執行環境版本。

支援的輸入檔案格式

您的輸入資料檔必須儲存為以位元組為單位的 Blob 資料,這表示 DataFrame 或 Delta 資料表中的二進位類型資料行。 如果源檔儲存在 Unity 目錄磁碟區中,則可以使用 Spark binaryFile 格式讀取器產生二進位類型數據行。

支援下列檔案格式:

  • PDF
  • JPG/JPEG
  • PNG
  • 多倫多電影節/TIF
  • 文檔/DOCX
  • PPT/PPTX

Syntax

ai_parse_document(content)
ai_parse_document(content, Map("version" -> "2.0"))

Arguments

content 是唯一必要的論點。 參數中傳遞map的所有選項(, imageOutputPathdescriptionElementTypes, , pageRange和 )皆為可version選。

  • content BINARY:表示輸入位元組陣列資料的表達式。
  • version:支援的輸出結構描述版本:「2.0」。
  • 'imageOutputPath':將渲染的頁面影像儲存到 Unity 目錄卷,供參考或多模態 RAG 應用程式使用。
  • 'descriptionElementTypes':AI 生成的描述。 2.0 版僅支援 的 figures 說明,因此 '*''figure' 會產生相同的行為。
    • '' (空字串):不會產生任何描述。 這減少了具有大量數字的文件所需的計算和成本。
    • 'figure':僅產生圖的描述。 僅支持AI生成的描述。
    • '*' (預設):產生所有支援元素類型的描述。
  • 'pageRange': 限制解析僅限於文件中的部分頁面。 頁碼為 1-index 格式。 該值是一個逗號分隔的標記列表,每個標記要麼是單一頁面(例如 "3"),要麼是包含範圍(例如 "5-10")。 例如,解析 '1,3,5-10' 第1、3頁、第5頁到第10頁。 所選頁面必須控制在500頁的限制內。 若 pageRange 省略且文件超過 500 頁,函式會立即失敗,且未解析任何頁面。

Returns

函式ai_parse_document會從文件擷取內容相關的版面配置元數據,例如page_numberheaderfooter。 它也會擷取文件內容,例如文字段落。 對於 2.0 版,表格以 HTML 表示。 輸出是VARIANT類型。

理解元素

元素是解析文件中識別的離散內容單位。 當處理文件時 ai_parse_document ,會將文件拆解成一連串元素,每個元素代表一個獨立的內容區塊,例如文字段落、表格、圖表,或是版面標記,如頁頭或頁尾。

輸出 elements 陣列中的每個元素包含以下欄位:

  • id: 一個以 0 為基礎的索引,表示該元素在文件中的位置。
  • type:一個表示該元素所代表內容類型的字串。 支援的元素類型包括:
    • text: 一段文字或一般正文。
    • table:一個以HTML格式表示內容的表格。
    • figure:文件中的圖片或圖表。
    • title:文件標題。
    • caption:與圖形或表格相關的說明文字。
    • section_header:標頭或副標題,表示章節開始。
    • page_header: 頁面頂端的標頭。
    • page_footer:頁尾,顯示在頁面底部。
    • page_number:頁碼標記。
    • footnote:註腳參考或文本。
  • content: 是該元素擷取的文字內容。 元素 table 內容格式為 HTML。 對於 figure 元素,內容可能為 NULL
  • confidence:一個信心分數,表示該元素從文件中提取的可靠性。
  • bbox:一組表示該元素在頁面上的物理位置的包圍框座標陣列。 每個包圍框包含像素座標和參考 page_id
  • description:一個由 AI 生成的文字描述。 在 2.0 版本中,只有啟用該選項時figure才會產生descriptionElementTypes描述。

Important

函數輸出綱目會使用 major.minor 格式進行版本設定。 Databricks 可能會升級支援或預設版本,以反映以持續研究為基礎的改良表示法。

  • 次要版本升級向後相容,並且可能只引入新的欄位。
  • 主要版本升級可能包括重大變更,例如字段新增、移除或重新命名。

以下是輸出架構:

備註

截至 2025 年 9 月 22 日,輸出結構描述位於 “2.0” 版上,並已更新為包含:

  • descriptions 用於 AI 生成的圖形描述。
  • bbox 用於邊界方塊座標。

若要移轉現有的工作負載以使用更新的結構描述,請參閱 將工作負載移轉至更新的結構描述

{
  "document": {
    "pages": [
      {
        "id": INT,                // 0-based page index
        "image_uri": STRING       // Path to saved page image (if enabled)
      }
    ],
    "elements": [
      {
        "id": INT,                 // 0-based element index
        "type": STRING,            // Supported: text, table, figure, table, title, caption, section_header,
                                   // page_footer, page_header, page_number, footnote
        "content": STRING,         // Text content of the target element
        "confidence": DOUBLE,      // Confidence score of the target element
        "bbox": [                  // Bounding box coordinates
          {
            "coord": [ INT ],
            "page_id": INT
          }
        ],
        "description": STRING      // AI-generated description for figures
      }
    ]
  },
  "error_status": [
    {
      "error_message": STRING       // The detailed error message
      "page_id": INT                // 0-based page index
    }
  ],
  "metadata": {
    "id": STRING,
    "version": STRING,              // The version of the output schema
    "file_metadata": {
      "file_path": STRING,
      "file_name": STRING,
      "file_size": LONG,
      "file_modification_time": TIMESTAMP
    }
  }
}

將工作負載移轉至更新的結構描述

本節中的步驟說明如何移轉 2025 年 9 月 22 日之前建立的工作負載,以使用更新的輸出結構描述。

  1. 在您的 SQL 請求中,使用 version 參數來指定特定的結構描述版本。
SELECT
ai_parse_document(
  content,
  map('version', '2.0')
) AS parsed
FROM READ_FILES('/path/to/documents', format => 'binaryFile');
  1. 修改程式碼以從elements陣列讀取內容而不是從pages陣列讀取。
  2. 重新評估中繼資料。 例如,如果您使用 page 頁首和頁尾等元數據,則需要開發一種替代方法來從 中 elements提取此資訊。
  3. 在移轉完整工作負載之前,請先使用範例文件驗證更新的邏輯。
  4. 如果圖形描述或影像持久性與您的使用案例相關,請考慮啟用它們。
  5. 檢查權限。 例如,如果您打算使用映像持續性,請確定您已為目標 Unity 目錄磁碟區設定正確的許可權。

Examples

本節提供使用 ai_parse_document的範例。

關於使用 ai_parse_document,請參考這個宣告式自動化套件的增量處理場景

下列範例用於 ai_parse_document 擷取文字元素並串連所有文字內容。 從那裡,它與 Claude Sonnet 4 模型一起使用 ai_query 來提取特定的結構化信息,例如供應商名稱、日期、發票號碼和購買的物品。

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;

下列範例使用 ai_parse_document 擷取文件版面配置,作為單一檔案的 VARIANT 輸出,並作出指定。

  • 儲存彩現影像的位置。
  • 釘選輸出結構描述版本。
  • 啟用 AI 生成的圖形描述。
SELECT
  path,
  ai_parse_document(
    content,
    map(
      'version', '2.0',
      'imageOutputPath', '/Volumes/catalog/schema/volume/directory/',
      'descriptionElementTypes', '*'
    )
  ) as parsed_doc
FROM READ_FILES('/Volumes/data/documents/', format => 'binaryFile');

以下範例限制 pageRange 解析僅限於 Unity 目錄卷中二進位檔案的子集頁面。 頁碼是 1 索引,你可以將單頁與範圍合併(例如 '1,3,5-10')。

SELECT
  path,
  ai_parse_document(
    content,
    map('pageRange', '1-500')
  ) AS parsed_doc
FROM READ_FILES('/Volumes/catalog/schema/volume/documents/', format => 'binaryFile');

下列範例會使用 ai_parse_document 來擷取檔版面配置做為 VARIANT Unity 目錄磁碟區中檔案的輸出。

SQL

SELECT
  path,
  ai_parse_document(content)
FROM READ_FILES('/Volumes/path/to/your/directory', format => 'binaryFile');

Python

from pyspark.sql.functions import *


df = spark.read.format("binaryFile") \
  .load("/Volumes/path/to/your/directory") \
  .withColumn(
    "parsed",
    expr("ai_parse_document(content)"))
display(df)

Scala

import org.apache.spark.sql.functions._

val df = spark.read.format("binaryFile")
  .load("/Volumes/path/to/your/directory")
  .withColumn(
    "parsed",
    ai_parse_document($"content"))
display(df)

以下範例使用 ai_parse_document 搭配 Lakeflow Connect for SharePoint 直接解析SharePoint文件庫的文件。

Important

Lakeflow Connect for SharePoint 的 Beta

CREATE TABLE documents AS
  SELECT * FROM read_files(
    'https://mytenant.sharepoint.com/sites/Marketing/Shared%20Documents',
    databricks.connection => 'my_sharepoint_conn',
    format => 'binaryFile',
    pathGlobFilter => '*.{pdf,docx}',
    schemaEvolutionMode => 'none'
  );

SELECT *, ai_parse_document(content) AS parsed_content
FROM documents;

使用 to_json() 搭配 PySpark collect()

ai_parse_document 回傳一個 VARIANT 型別,PySpark(或其他不支援 VARIANT 的 API)無法直接收集。 若要將解析結果匯成 Python 以便進一步處理,請使用 SQL 中的 to_json() 將 VARIANT 轉換成 JSON 字串,然後在 Python 中用 json.loads() 進行解析:

import json

sql = """
WITH parsed_documents AS (
  SELECT
    path,
    ai_parse_document(
      content,
      map(
        'version', '2.0',
        'imageOutputPath', '/Volumes/catalog/schema/volume/parsed_images/',
        'descriptionElementTypes', '*'
      )
    ) AS parsed
  FROM READ_FILES('/Volumes/catalog/schema/volume/source_docs/*', format => 'binaryFile')
)
SELECT path, to_json(parsed) AS parsed_json FROM parsed_documents
"""
parsed_results = [json.loads(row.parsed_json) for row in spark.sql(sql).collect()]
# Each item in parsed_results is a Python dict with the parsed document structure.

下列範例用於 ai_parse_document 分隔輸出的每個最上層欄位。 例如,document.pagesdocument.elementserror_statusmetadata作為個別的欄位。

SQL

WITH corpus AS (
  SELECT
    path,
    ai_parse_document(content) AS parsed
  FROM
    READ_FILES('/Volumes/path/to/source/file.pdf', format => 'binaryFile')
)
SELECT
  path,
  parsed:document:pages,
  parsed:document:elements,
  parsed:error_status,
  parsed:metadata
FROM corpus;

Python

from pyspark.sql.functions import *

df = (
  spark.read.format("binaryFile")
    .load("/Volumes/path/to/source/file.pdf")
    .withColumn("parsed", ai_parse_document(col("content")))
    .select(
      "path",
      expr("parsed:document:pages"),
      expr("parsed:document:elements"),
      expr("parsed:error_status"),
      expr("parsed:metadata")
    )
)
display(df)

Scala


import com.databricks.sql.catalyst.unstructured.DocumentParseResultV2_0
import org.apache.spark.sql.functions._


val df = spark.read.format("binaryFile")
 .load("/Volumes/path/to/source/file.pdf")
 .withColumn(
   "parsed",
   ai_parse_document($"content").cast(DocumentParseResultV2_0.SCHEMA))
 .select(
   $"path",
   $"parsed.*")
display(df)

調試介面筆記本

以下筆記本提供一個視覺化的除錯介面,用於分析ai_parse_document函式的輸出。 它使用互動式邊界框疊加來渲染解析的文件,允許您檢查從文件的每個區域中提取的內容

調試介面筆記本

拿筆記本

限制

  • 文件最多可達500頁,超過此限制將會出現錯誤。
  • 最大檔案大小限制為 100 MB。
  • 雖然 Databricks 不斷努力改進其所有功能,但 LLM 是一項新興技術,可能會產生錯誤。
  • ai_parse_document 式可能需要時間擷取檔內容,同時保留結構化資訊,特別是對於包含高度密集內容或具有不良解析度之內容的檔。 在某些情況下,函式可能需要一些時間才能運行或忽略內容。 Databricks 會持續運作以改善延遲。
  • 請參閱 支援的輸入檔案格式。 Databricks 歡迎對貴組織而言最重要的其他格式意見反應。
  • ai_parse_document不支援自訂模型或使用客戶提供的模型ai_parse_document
  • 使用非拉丁字母的文字處理影像時,基礎模型可能無法以最佳方式執行,例如日文或韓文。
  • 具有數位簽名的檔可能無法正確處理。