# Azure - AI Document Intelligence

> 使用 Microsoft Azure AI Document Intelligence（原 Azure Form Recognizer）对复杂文档执行版面分析、表单理解和结构化抽取。

Source: https://docs.sommatic.ai/zh/nodes/integrations.microsoft.azure.document-intelligence/

- 标识: `integrations.microsoft.azure.document-intelligence`
- 类别: 集成
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

使用 Microsoft Azure AI Document Intelligence（原 Azure Form Recognizer）对复杂文档执行版面分析、表单理解和结构化抽取。

通过 `connection_id`（带 `endpoint` 元数据的 api-key 凭据）使用你自己的 Azure 资源进行认证；执行费用由 Azure 计入你的订阅。

**操作（预构建模型和自定义模型）：**
- **prebuilt-layout**（默认）：完整的页面结构，包括段落、表格、选择标记和阅读顺序。
- **prebuilt-document：** 在任意表单中通用地抽取键值对和实体。
- **prebuilt-invoice：** 发票字段的类型化 schema（供应商、合计、明细行、日期）。
- **prebuilt-receipt：** 零售收据的类型化 schema（商户、合计、税费、商品）。
- **prebuilt-tax.us.w2：** 美国 W-2 税表的类型化 schema。
- **prebuilt-id：** 政府签发身份证件的类型化 schema。
- **prebuilt-healthInsuranceCard.us：** 美国医疗保险卡的类型化 schema。
- **prebuilt-read：** 页面级 OCR，支持手写体和多语言。
- **custom-<id>：** 针对特定文档模板由用户训练的模型。

## 配置

- `connection_id` (string, 必填): 包含 Azure AI Document Intelligence 资源 endpoint + api-key 的连接凭据。
- `model` (string, 可选): Azure AI Document Intelligence 模型标识符。可使用内置的预构建模型，或自定义训练模型 ID（custom-<id>）。 默认值: `prebuilt-layout`. 可选值: `prebuilt-layout`, `prebuilt-invoice`, `prebuilt-receipt`, `prebuilt-tax.us.w2`, `prebuilt-idDocument`, `prebuilt-healthInsuranceCard.us`, `prebuilt-read`.
- `pages` (string, 可选, 支持表达式): 可选的页码范围过滤（例如“1-3”）。留空则处理所有页面。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Extracted
- `empty`: Empty
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

- `text` (string, 可选)
- `chars` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)
- `tables` (array, 可选)
- `key_value_pairs` (array, 可选)

## 在表达式中

后续节点可通过 `$("Azure - AI Document Intelligence").item.json.<路径>` 读取此节点输出中的内容（请把 `Azure - AI Document Intelligence` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("Azure - AI Document Intelligence").item.json.text` (string) = `"INVOICE 2026-0418\nTotal: 129.99 USD"`
- `$("Azure - AI Document Intelligence").item.json.chars` (number) = `35`
- `$("Azure - AI Document Intelligence").item.json.empty` (boolean) = `false`
- `$("Azure - AI Document Intelligence").item.json.method` (string) = `"azure-document-intelligence:prebuilt-layout"`
- `$("Azure - AI Document Intelligence").item.json.metadata` (object) = `{…}`
- `$("Azure - AI Document Intelligence").item.json.tables` (array) = `[…] (1)`
- `$("Azure - AI Document Intelligence").item.json.key_value_pairs` (array) = `[…] (0)`
- `$("Azure - AI Document Intelligence").item.json.metadata.model_id` (string) = `"prebuilt-layout"` (编辑器不提示)
- `$("Azure - AI Document Intelligence").item.json.metadata.pages_analyzed` (number) = `1` (编辑器不提示)
- `$("Azure - AI Document Intelligence").item.json.metadata.tables_count` (number) = `1` (编辑器不提示)
- `$("Azure - AI Document Intelligence").item.json.metadata.key_value_pairs_count` (number) = `0` (编辑器不提示)


## 工作原理

使用你自己的 Azure AI Document Intelligence 资源分析文档，返回文本、表格和键值对。未识别到文本时经 `empty` 输出。

1. 解析节点配置。先从配置、再从输入项读取 `content_base64` 或 `file_path`。
2. 必须提供 `connection_id`，以及 `content_base64` 或 `file_path` 之一。
3. 在服务端解析凭据：密钥中必须包含 `apiKey`（或 `api_key`），endpoint 从凭据配置（`endpoint`）或密钥中读取。
4. 启动 Python 进程调用 `begin_analyze_document`，传入 `model`（默认 `prebuilt-layout`）和可选的 `pages` 页码范围，并等待分析完成。
5. 生成 `{ text, chars, empty, method, metadata, tables, key_value_pairs }`。表格会转换为单元格文本网格（`rows`），并附带其首个区域所在页码。
6. 去除空白后文本为空时选择 `empty`，否则选择 `extracted`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-read-invoice",
  "label": "Read invoice",
  "operator_slug": "integrations.microsoft.azure.document-intelligence",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "model": "prebuilt-layout",
    "pages": "1-3"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "text": "INVOICE 2026-0418\nTotal: 129.99 USD",
    "chars": 35,
    "empty": false,
    "method": "azure-document-intelligence:prebuilt-layout",
    "metadata": {
      "model_id": "prebuilt-layout",
      "pages_analyzed": 1,
      "tables_count": 1,
      "key_value_pairs_count": 0
    },
    "tables": [
      {
        "page": 1,
        "rows": [
          [
            "Item",
            "Amount"
          ],
          [
            "Service",
            "129.99"
          ]
        ]
      }
    ],
    "key_value_pairs": []
  },
  "port": "extracted"
}
```

## 输出端口 (代码中的行为)

### `extracted`

分析返回了文本。

```json
{
  "text": "INVOICE 2026-0418\nTotal: 129.99 USD",
  "chars": 35,
  "empty": false,
  "method": "azure-document-intelligence:prebuilt-layout",
  "metadata": {
    "model_id": "prebuilt-layout",
    "pages_analyzed": 1,
    "tables_count": 1,
    "key_value_pairs_count": 0
  },
  "tables": [
    {
      "page": 1,
      "rows": [
        [
          "Item",
          "Amount"
        ],
        [
          "Service",
          "129.99"
        ]
      ]
    }
  ],
  "key_value_pairs": []
}
```

### `empty`

分析成功但未找到文本（例如空白页或无可读文字的图片）。

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "azure-document-intelligence:prebuilt-layout",
  "metadata": {
    "model_id": "prebuilt-layout",
    "pages_analyzed": 1,
    "tables_count": 0,
    "key_value_pairs_count": 0
  },
  "tables": [],
  "key_value_pairs": []
}
```

### `error`

校验、凭据解析、Python 进程或 Azure 调用失败。Python 失败时会附带其 `stderr`。

```json
{
  "error": "Python timed out after 300000ms",
  "stderr": ""
}
```

## 代码中的行为

- `connection_id`: 请使用 `object` 类型凭据，其密钥包含 `apiKey` 和 `endpoint`（或将 `endpoint` 写入凭据配置）。
- `model`: 原样传递，因此可以使用资源支持的任意模型 ID（包括自定义模型），不限于列表中的选项。
- `content_base64`: 未在配置 schema 中声明，通常来自输入项。`file_path` 同理，仅在缺少 `content_base64` 时使用。
- `execution`: 只读取 `timeout_ms`（默认 300000），重试设置不会生效。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required.` | `error` | 未配置凭据。 |
| `Either content_base64 or file_path is required.` | `error` | 输入项中两个字段都没有。当 `file_path` 在编排器上不存在时，Python 也会返回此错误。 |
| `connection must provide endpoint + apiKey` | `error` | 凭据密钥不是包含 `apiKey` 的对象，或未保存 endpoint。纯字符串形式的 api-key 密钥无法使用。 |
| `Python timed out after <ms>ms` | `error` | 分析耗时超过 `execution.timeout_ms`（默认 300000）。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据不存在或无法连接后端。 |

## 说明与限制

- 在某台主机上首次运行时，会在缓存的虚拟环境中安装 Python 依赖，可能需要数分钟。
- `file_path` 必须存在于编排器的文件系统中，例如 `connectors.microsoft.outlook.attachments` 以 `file` 模式写出的文件。
- Azure 用量计入你自己的资源。worker 不会重试。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "integrations.microsoft.azure.document-intelligence",
  "name": "Azure - AI Document Intelligence",
  "category": "integrations",
  "group": [
    {
      "key": "microsoft",
      "name": "Microsoft",
      "icon_url": "/icons/integrations/microsoft/microsoft.svg"
    },
    {
      "key": "foundry",
      "name": "Microsoft Foundry",
      "icon_url": "/icons/integrations/microsoft/foundry.webp"
    }
  ],
  "icon_url": "/icons/integrations/microsoft/microsoft.svg",
  "version": "1.0.0",
  "description": "Execute layout analysis, form understanding, and structured extraction on complex documents using Microsoft Azure AI Document Intelligence (formerly Azure Form Recognizer).\n\n  Authenticates with your own Azure resource via `connection_id` (api-key credential with `endpoint` metadata); execution costs are billed by Azure to your subscription.\n\n  **Operations (prebuilt and custom models):**\n  - **prebuilt-layout** (default): full page structure — paragraphs, tables, selection marks, reading order.\n  - **prebuilt-document:** generic key-value and entity extraction across arbitrary forms.\n  - **prebuilt-invoice:** typed schema for invoice fields (vendor, totals, line items, dates).\n  - **prebuilt-receipt:** typed schema for retail receipts (merchant, totals, taxes, items).\n  - **prebuilt-tax.us.w2:** typed schema for U.S. W-2 tax forms.\n  - **prebuilt-id:** typed schema for government-issued identification documents.\n  - **prebuilt-healthInsuranceCard.us:** typed schema for U.S. health insurance cards.\n  - **prebuilt-read:** page-level OCR with handwriting and multi-language support.\n  - **custom-<id>:** user-trained models for specific document templates.",
  "capabilities": [
    "document-intelligence",
    "ocr",
    "forms",
    "tables",
    "layout",
    "azure",
    "cloud"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "Azure AI Document Intelligence Credential",
        "description": "Connection credential with endpoint + api-key for your Azure AI Document Intelligence resource.",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "api-key",
            "object"
          ],
          "providers": [
            "azure"
          ]
        }
      },
      "model": {
        "type": "string",
        "title": "Model",
        "enum": [
          "prebuilt-layout",
          "prebuilt-invoice",
          "prebuilt-receipt",
          "prebuilt-tax.us.w2",
          "prebuilt-idDocument",
          "prebuilt-healthInsuranceCard.us",
          "prebuilt-read"
        ],
        "default": "prebuilt-layout",
        "description": "Azure AI Document Intelligence model identifier. Use a built-in prebuilt model or a custom trained model id (custom-<id>)."
      },
      "pages": {
        "type": "string",
        "title": "Pages",
        "description": "Optional page range filter (e.g. \"1-3\"). Leave empty for all pages.",
        "format": "expression"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "connection_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      },
      "tables": {
        "type": "array"
      },
      "key_value_pairs": {
        "type": "array"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "cloud-io"
  ],
  "tags": [
    "azure",
    "document-intelligence",
    "ocr",
    "forms",
    "layout"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "Azure AI Document Intelligence Credential",
      "description": "Connection credential with endpoint + api-key for your Azure AI Document Intelligence resource.",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "api-key",
          "object"
        ],
        "providers": [
          "azure"
        ]
      }
    },
    "model": {
      "type": "string",
      "title": "Model",
      "enum": [
        "prebuilt-layout",
        "prebuilt-invoice",
        "prebuilt-receipt",
        "prebuilt-tax.us.w2",
        "prebuilt-idDocument",
        "prebuilt-healthInsuranceCard.us",
        "prebuilt-read"
      ],
      "default": "prebuilt-layout",
      "description": "Azure AI Document Intelligence model identifier. Use a built-in prebuilt model or a custom trained model id (custom-<id>)."
    },
    "pages": {
      "type": "string",
      "title": "Pages",
      "description": "Optional page range filter (e.g. \"1-3\"). Leave empty for all pages.",
      "format": "expression"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "connection_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    },
    "tables": {
      "type": "array"
    },
    "key_value_pairs": {
      "type": "array"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
