Categories:

String & binary functions (AI Functions)

AI_PARSE_DOCUMENT

Returns document content from a Snowflake stage as a JSON-formatted string. Supports text extraction (OCR), text and layout extraction (LAYOUT), and text, layout, and visual content extraction (AGENTIC). For more information, see Parsing documents with AI_PARSE_DOCUMENT.

Syntax

AI_PARSE_DOCUMENT( <file_object> [, <options> ] [, <return_error_details> ] )

Arguments

Required:

file_object

A FILE object that specifies the document to parse, stored in a Snowflake stage. For information about creating file objects, see TO_FILE.

Optional:

options

An OBJECT value that contains options for parsing documents. The supported keys are shown below. All are optional.

  • 'extract_images': If set to TRUE, the function extracts images embedded in the document. Requires LAYOUT mode.

  • 'mode': Specifies the parsing mode. The supported modes are:

    • 'OCR': The function extracts text only. This is the default mode.
    • 'LAYOUT': The function extracts layout as well as text, including structural content such as tables.
    • 'AGENTIC': The function goes beyond text and layout extraction to interpret visual elements, generate semantic summaries, and extract structured data from charts, diagrams, tables, and other visuals. For more information, see Agentic mode.
  • 'page_split': If set to TRUE, the function splits the document into pages and processes each page separately. This feature supports only PDF, PowerPoint (.pptx), and Word (.docx) documents. Documents in other formats return an error. The default is FALSE.

    Tip

    To process long documents that exceed the token limit of AI_PARSE_DOCUMENT, set this option to TRUE.

  • 'page_filter': An array that specifies ranges of pages of a multi-page document to process. Each range is an object with start and end fields that specify the first (inclusive) and last (exclusive) page in the range. Page indexes start at 0. For example, {'start': 0, 'end': 1} specifies the first page of the document.

    Note

    Specifying page_filter implies page_split. If you specify page ranges, it is not necessary to also set page_split.

return_error_details

A BOOLEAN flag that indicates whether to return error details in case of error. When set to TRUE, the function returns an OBJECT that contains value, error, and metadata fields. The value field contains the parsed document data, the error field contains the error message (or NULL on success), and metadata is returned alongside value and error. value uses the shape in Returns. See Error behavior for details.

Returns

By default the function returns the JSON as a string, so use PARSE_JSON to read the fields in SQL. If parsing fails, the function returns NULL. Every successful result includes metadata.pageCount.

Page splitting is on when 'page_split' is TRUE or 'page_filter' is specified.

Page splitting off. The document is one content string: plain text in OCR mode, or Markdown in LAYOUT mode.

{
  "content": "Document text.",
  "metadata": {
    "pageCount": 1
  }
}

Page splitting on. pages is an array of page objects, including for a one-page file. With 'page_filter', the array contains only the selected pages. index is the zero-based position in the original file. Printed page numbers are ignored. dimensions has height and width.

{
  "metadata": {
    "pageCount": 140
  },
  "pages": [
    {
      "content": "Page text.",
      "index": 0
    }
  ]
}

Images. images is included when 'mode' is 'LAYOUT' and 'extract_images' is TRUE, or when 'mode' is 'AGENTIC'. It is a top-level array when page splitting is off, and an array on each page when page splitting is on. The array is [] when there are no images. Markdown in content refers to an image by id, for example ![img-0.jpeg](img-0.jpeg).

In AGENTIC mode, each image entry contains a results object with the semantic summary and structured details for that visual. For field definitions, see Expected image result schemas for AGENTIC mode.

FieldDescription
idImage identifier, such as img-0.jpeg.
top_left_x, top_left_yUpper-left corner on the page.
bottom_right_x, bottom_right_yLower-right corner on the page.
image_base64Image data encoded as a base64 string. Returned in LAYOUT mode when 'extract_images' is TRUE.
resultsIn AGENTIC mode, contains the results for the image, such as its image type, a semantic summary, and structured details. If processing fails for the image, contains an error marker instead.
{
  "id": "img-0.jpeg",
  "top_left_x": 666,
  "top_left_y": 697,
  "bottom_right_x": 1026,
  "bottom_right_y": 816,
  "image_base64": "data:image/jpeg;base64,..."
}

Expected image result schemas for AGENTIC mode

Important

AGENTIC mode generates image results on a best-effort basis. The schemas in this section describe the expected structure of the model-generated results object, but schema conformance isn’t enforced or guaranteed. Returned fields, types, and values can vary. Validate the fields your application requires, and handle missing, null, or unexpected values.

These schemas describe the results for images that are processed successfully. If processing fails for an image, its results object contains the error marker described in Partial results in AGENTIC mode, which also includes an example response.

Common fields

The expected results object contains these fields:

FieldExpected typeDescription
image_typeStringImage classification: chart, table, diagram, screenshot, document_page, infographic, photo_with_text, or other.
summaryStringA short paragraph describing the image and the information it conveys.
detailsObjectImage-type-specific fields, described in the following sections.

All field paths in the following sections are relative to details. The notation [] refers to an element of an array.

Chart

The following fields are expected when image_type is chart:

FieldExpected typeDescription
chart_typeStringbar, line, pie, scatter, area, heatmap, multi_panel, or other.
titleString or nullChart title, when available.
x_axisObjectHorizontal-axis information, with label and units fields. Each field is a string or null.
y_axisObjectVertical-axis information, with label and units fields. Each field is a string or null.
seriesArray of objectsData series identified in the chart.
series[].nameStringSeries name.
series[].unitString or nullUnit and scale used for numeric values in the series, such as USD millions.
series[].pointsArray of objectsData points in the series.
series[].points[].labelStringCategory, time period, or other point label.
series[].points[].valueNumber or stringExtracted or estimated value. A string can preserve a printed unit or scale suffix.
key_valuesArray of stringsNotable values or facts from the chart.
notesStringTrends, outliers, multi-panel layout, footnotes, estimation caveats, or other relevant context.
Units and scale

When printed values with unit or scale suffixes are returned as bare numbers, the expected output uses one consistent unit for the entire series and records it in series[].unit.

For example, values printed as $97B and $1.08T can be represented as:

{
  "name": "Market value",
  "unit": "USD billions",
  "points": [
    {
      "label": "A",
      "value": 97
    },
    {
      "label": "B",
      "value": 1080
    }
  ]
}

Alternatively, values can retain their original strings, such as "$97B" and "$1.08T". In that representation, each value carries its own unit and scale, and series[].unit is expected to be null.

Stacked charts

Category-level series depend on a readable mapping between segments and category names, such as a clear legend or directly labeled segments. When that mapping is ambiguous, the expected output is a single series representing total stacked heights, with an explanation in notes, rather than an inferred category breakdown.

Table

The following fields are expected when image_type is table:

FieldExpected typeDescription
titleString or nullTable title, when available.
columnsArray of stringsColumn headers in order.
rowsArray of arrays of stringsTable rows. Each inner array contains cell values in column order.
key_valuesArray of stringsNotable cells or facts from the table.

Diagram

The following fields are expected when image_type is diagram:

FieldExpected typeDescription
diagram_typeStringflowchart, block_diagram, architecture, schematic, tree, network, or other.
componentsArray of objectsComponents identified in the diagram.
components[].idStringComponent identifier used by connections.
components[].labelStringVisible component label.
components[].roleString or nullComponent role, when identifiable.
connectionsArray of objectsRelationships or connections between components.
connections[].fromStringSource component identifier.
connections[].toStringDestination component identifier.
connections[].labelString or nullVisible connection or edge label, when available.
purposeStringOne sentence describing what the diagram conveys.

Screenshot

The following fields are expected when image_type is screenshot:

FieldExpected typeDescription
app_or_pageString or nullProduct or page name, when visible.
visible_textArray of stringsMeaningful visible text in reading order.
state_signalsArray of stringsErrors, warnings, statuses, badges, selected options, or disabled controls.
purposeStringOne sentence describing what a user would do on the screen.

Document page

The following fields are expected when image_type is document_page:

FieldExpected typeDescription
headingsArray of stringsHeadings in reading order.
bodyStringTranscribed body text, preserving reading order.
calloutsArray of stringsSidebars, highlighted text, footnotes, or image captions.

Infographic

The following fields are expected when image_type is infographic:

FieldExpected typeDescription
titleString or nullInfographic title, when available.
sectionsArray of objectsSections identified in the infographic.
sections[].headingStringSection heading.
sections[].key_factsArray of stringsFacts presented in the section.
key_valuesArray of stringsNotable numbers or facts from the infographic.

Photo with text

The following fields are expected when image_type is photo_with_text:

FieldExpected typeDescription
visible_textArray of stringsMeaningful visible text in reading order.
scene_descriptionStringOne sentence describing what the photograph shows.

Other

The following fields are expected when image_type is other:

FieldExpected typeDescription
visible_textArray of stringsMeaningful visible text. Expected to be an empty array when no text is present.
descriptionStringA paragraph describing the image.

Usage notes

  • AGENTIC mode supports up to 2,000 images per document. This limit applies to the document, not to each page.
  • AGENTIC mode doesn’t support the 'extract_images' option. If you set 'extract_images' to TRUE in AGENTIC mode, the function returns an error. To extract embedded images as base64-encoded data, use LAYOUT mode with 'extract_images' set to TRUE.

Error behavior

By default, if AI_PARSE_DOCUMENT can’t process the input, the function returns NULL. If the query processes multiple rows, rows with errors return NULL and don’t prevent the query from completing.

The following table shows the return value based on the return_error_details argument:

return_error_detailsReturn valueDescription
FALSE Not passedNULL
TRUEOBJECT with value, error, and metadata fieldsvalue: An OBJECT containing the parsed document data, or NULL if an error occurred. error: A VARCHAR value that contains the error message if an error occurred, or NULL if the function succeeded. The error field inside value (renamed from errorInformation) contains per-document error details when present. metadata: An OBJECT containing document metadata such as page count. This field is returned alongside value and error.

For more information about error handling for AI functions, see Snowflake Cortex AI Function: Multirow error handling improvements.

Partial results in AGENTIC mode

If processing fails for an image, AI_PARSE_DOCUMENT still returns the parsed document content and the available results for other images. The affected image entry contains the following error marker:

{
  "id": "img-1.jpeg",
  "results": {
    "description": "error"
  }
}

This marker indicates a processing failure for that image, not a failure to parse the entire document. Check image-level results before using them in downstream processing.

The following illustrative response contains successfully extracted details for one chart and one image that couldn’t be processed. Image coordinates are omitted for brevity.

{
  "metadata": {
    "pageCount": 1
  },
  "pages": [
    {
      "index": 0,
      "content": "## Quarterly revenue\n\n![img-0.jpeg](img-0.jpeg)\n\n![img-1.jpeg](img-1.jpeg)",
      "images": [
        {
          "id": "img-0.jpeg",
          "results": {
            "image_type": "chart",
            "summary": "Bar chart comparing revenue for two quarters.",
            "details": {
              "chart_type": "bar",
              "title": "Quarterly revenue",
              "x_axis": {
                "label": "Quarter",
                "units": null
              },
              "y_axis": {
                "label": "Revenue",
                "units": "USD millions"
              },
              "series": [
                {
                  "name": "Revenue",
                  "unit": "USD millions",
                  "points": [
                    {
                      "label": "Q1",
                      "value": 100
                    },
                    {
                      "label": "Q2",
                      "value": 113
                    }
                  ]
                }
              ],
              "key_values": [
                "Q1 revenue: USD 100 million",
                "Q2 revenue: approximately USD 113 million"
              ],
              "notes": "Q1 has a printed value. Q2 is estimated from the bar height."
            }
          }
        },
        {
          "id": "img-1.jpeg",
          "results": {
            "description": "error"
          }
        }
      ]
    }
  ]
}

Examples

For examples, see AI_PARSE_DOCUMENT examples.

Note

AI_PARSE_DOCUMENT is the updated version of PARSE_DOCUMENT. For the latest functionality, use AI_PARSE_DOCUMENT.

Refer to Snowflake AI and ML for legal notices.