Communitygithub.com

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK 用于 .NET。使用预构建和自定义模型从文档中提取文本、表格和结构化数据。适用于发票处理、收据提取、身份证件分析和自定义文档模型。触发词:“Document Intelligence”、“DocumentIntelligenceClient”、“form recognizer”、“invoice extraction”、“receipt OCR”、“document analysis .NET”。

azure-ai-document-intelligence-dotnet 是什么?

此技能提供 Microsoft 的 Azure.AI.DocumentIntelligence .NET SDK 的集成,用于从文档中提取文本、表格和结构化数据。它支持通过预构建模型(如发票、收据、身份证件)和自定义模型进行分析,适用于自动化处理文档工作流。该 SDK 可在任何 .NET 环境中使用,并提供两个主要客户端:DocumentIntelligenceClient(用于分析)和 DocumentIntelligenceAdministrationClient(用于模型管理)。技能详细介绍了使用 Microsoft Entra ID 或 API 密钥进行身份验证、处理预构建模型(包括布局和阅读)、基于代码的发票分析示例、收据提取,以及构建自定义文档模型和分类器。它强调最佳实践,如重用客户端实例、检查字段置信度以及处理长时间运行的操作,并包含错误处理指南和常见查询类型的触发词。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-document-intelligence-dotnet

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Azure.AI.DocumentIntelligence (.NET)

使用预构建和自定义模型从文档中提取文本、表格和结构化数据。

安装

dotnet add package Azure.AI.DocumentIntelligence
dotnet add package Azure.Identity

当前版本:v1.0.0(正式发布版)

环境变量

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<资源名称>.cognitiveservices.azure.com/  # 必填:Document Intelligence 终结点
DOCUMENT_INTELLIGENCE_API_KEY=<你的 API 密钥>  # 仅在使用 AzureKeyCredential 身份验证时需要
BLOB_CONTAINER_SAS_URL=https://<存储>.blob.core.windows.net/<容器>?<SAS 令牌>  # 可选:用于训练数据的 Blob 容器 SAS URL
AZURE_TOKEN_CREDENTIALS=prod  # 仅在生产环境中使用 DefaultAzureCredential 时需要

身份验证

Microsoft Entra 令牌凭据

using Azure.Identity;
using Azure.AI.DocumentIntelligence;

string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
// 本地开发:DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<具体凭据>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生产环境中直接使用特定的凭据:
// 参见 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var client = new DocumentIntelligenceClient(new Uri(endpoint), credential);

注意:Entra ID 需要一个 自定义子域(例如 https://<资源名称>.cognitiveservices.azure.com/),而不是区域终结点。

API 密钥

string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
string apiKey = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_API_KEY");
var client = new DocumentIntelligenceClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

客户端类型

客户端用途
DocumentIntelligenceClient分析文档、分类文档
DocumentIntelligenceAdministrationClient构建/管理自定义模型和分类器

预构建模型

模型 ID描述
prebuilt-read提取文本、语言、手写内容
prebuilt-layout提取文本、表格、选择标记、结构
prebuilt-invoice提取发票字段(供应商、项目、总金额)
prebuilt-receipt提取收据字段(商家、项目、总金额)
prebuilt-idDocument提取身份证件字段(姓名、出生日期、地址)
prebuilt-businessCard提取名片字段
prebuilt-tax.us.w2提取 W-2 税务表单字段
prebuilt-healthInsuranceCard.us提取健康保险卡字段

核心工作流

1. 分析发票

using Azure.AI.DocumentIntelligence;

Uri invoiceUri = new Uri("https://example.com/invoice.pdf");

Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
    WaitUntil.Completed, 
    "prebuilt-invoice", 
    invoiceUri);

AnalyzeResult result = operation.Value;

foreach (AnalyzedDocument document in result.Documents)
{
    if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField)
        && vendorNameField.FieldType == DocumentFieldType.String)
    {
        string vendorName = vendorNameField.ValueString;
        Console.WriteLine($"供应商名称:'{vendorName}',置信度:{vendorNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
        && invoiceTotalField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
        Console.WriteLine($"发票总金额:'{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
    }
    
    // 提取行项目
    if (document.Fields.TryGetValue("Items", out DocumentField itemsField)
        && itemsField.FieldType == DocumentFieldType.List)
    {
        foreach (DocumentField item in itemsField.ValueList)
        {
            var itemFields = item.ValueDictionary;
            if (itemFields.TryGetValue("Description", out DocumentField descField))
                Console.WriteLine($"  项目:{descField.ValueString}");
        }
    }
}

2. 提取布局(文本、表格、结构)

Uri fileUri = new Uri("https://example.com/document.pdf");

Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
    WaitUntil.Completed, 
    "prebuilt-layout", 
    fileUri);

AnalyzeResult result = operation.Value;

// 按页面提取文本
foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"第 {page.PageNumber} 页:{page.Lines.Count} 行,{page.Words.Count} 个单词");
    
    foreach (DocumentLine line in page.Lines)
    {
        Console.WriteLine($"  行:'{line.Content}'");
    }
}

// 提取表格
foreach (DocumentTable table in result.Tables)
{
    Console.WriteLine($"表格:{table.RowCount} 行 x {table.ColumnCount} 列");
    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"  单元格({cell.RowIndex},{cell.ColumnIndex}):{cell.Content}");
    }
}

3. 分析收据

Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
    WaitUntil.Completed, 
    "prebuilt-receipt", 
    receiptUri);

AnalyzeResult result = operation.Value;

foreach (AnalyzedDocument document in result.Documents)
{
    if (document.Fields.TryGetValue("MerchantName", out DocumentField merchantField))
        Console.WriteLine($"商家:{merchantField.ValueString}");
        
    if (document.Fields.TryGetValue("Total", out DocumentField totalField))
        Console.WriteLine($"总金额:{totalField.ValueCurrency.Amount}");
        
    if (document.Fields.TryGetValue("TransactionDate", out DocumentField dateField))
        Console.WriteLine($"日期:{dateField.ValueDate}");
}

4. 构建自定义模型

var adminClient = new DocumentIntelligenceAdministrationClient(
    new Uri(endpoint), 
    new AzureKeyCredential(apiKey));

string modelId = "my-custom-model";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");

var blobSource = new BlobContentSource(blobContainerUri);
var options = new BuildDocumentModelOptions(modelId, DocumentBuildMode.Template, blobSource);

Operation<DocumentModelDetails> operation = await adminClient.BuildDocumentModelAsync(
    WaitUntil.Completed, 
    options);

DocumentModelDetails model = operation.Value;

Console.WriteLine($"模型 ID:{model.ModelId}");
Console.WriteLine($"创建时间:{model.CreatedOn}");

foreach (var docType in model.DocumentTypes)
{
    Console.WriteLine($"文档类型:{docType.Key}");
    foreach (var field in docType.Value.FieldSchema)
    {
        Console.WriteLine($"  字段:{field.Key},置信度:{docType.Value.FieldConfidence[field.Key]}");
    }
}

5. 构建文档分类器

string classifierId = "my-classifier";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");

var sourceA = new BlobContentSource(blobContainerUri) { Prefix = "TypeA/train" };
var sourceB = new BlobContentSource(blobContainerUri) { Prefix = "TypeB/train" };

var docTypes = new Dictionary<string, ClassifierDocumentTypeDetails>()
{
    { "TypeA", new ClassifierDocumentTypeDetails(sourceA) },
    { "TypeB", new ClassifierDocumentTypeDetails(sourceB) }
};

var options = new BuildClassifierOptions(classifierId, docTypes);

Operation<DocumentClassifierDetails> operation = await adminClient.BuildClassifierAsync(
    WaitUntil.Completed, 
    options);

DocumentClassifierDetails classifier = operation.Value;
Console.WriteLine($"分类器 ID:{classifier.ClassifierId}");

6. 分类文档

string classifierId = "my-classifier";
Uri documentUri = new Uri("https://example.com/document.pdf");

var options = new ClassifyDocumentOptions(classifierId, documentUri);

Operation<AnalyzeResult> operation = await client.ClassifyDocumentAsync(
    WaitUntil.Completed, 
    options);

AnalyzeResult result = operation.Value;

foreach (AnalyzedDocument document in result.Documents)
{
    Console.WriteLine($"文档类型:{document.DocumentType},置信度:{document.Confidence}");
}

7. 管理模型

// 获取资源详细信息
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"自定义模型:{resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");

// 获取特定模型
DocumentModelDetails model = await adminClient.GetModelAsync("my-model-id");
Console.WriteLine($"模型:{model.ModelId},创建时间:{model.CreatedOn}");

// 罗列模型
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
    Console.WriteLine($"模型:{modelItem.ModelId}");
}

// 删除模型
await adminClient.DeleteModelAsync("my-model-id");

关键类型参考

类型描述
DocumentIntelligenceClient用于分析的主客户端
DocumentIntelligenceAdministrationClient模型管理
AnalyzeResult文档分析的结果
AnalyzedDocument结果中的单个文档
DocumentField提取的字段,包含值和置信度
DocumentFieldType字符串、日期、数字、货币等
DocumentPage页面信息(行、单词、选择标记)
DocumentTable提取的表格,包含单元格
DocumentModelDetails自定义模型元数据
BlobContentSource训练数据源

构建模式

模式使用场景
DocumentBuildMode.Template固定布局文档(表单)
DocumentBuildMode.Neural可变布局文档

最佳实践

  1. 生产环境使用 DefaultAzureCredential
  2. 重用客户端实例 — 客户端是线程安全的
  3. 处理长时间运行的操作 — 为简单起见使用 WaitUntil.Completed
  4. 检查字段置信度 — 始终验证 Confidence 属性
  5. 使用合适的模型 — 常见文档用预构建,专用文档用自定义
  6. 使用自定义子域 — Entra ID 身份验证所必需

错误处理

using Azure;

try
{
    var operation = await client.AnalyzeDocumentAsync(
        WaitUntil.Completed, 
        "prebuilt-invoice", 
        documentUri);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"错误:{ex.Status} - {ex.Message}");
}

相关 SDK

SDK用途安装
Azure.AI.DocumentIntelligence文档分析(此 SDK)dotnet add package Azure.AI.DocumentIntelligence
Azure.AI.FormRecognizer旧版 SDK(已弃用)改用 DocumentIntelligence

参考链接

资源URL
NuGet 包https://www.nuget.org/packages/Azure.AI.DocumentIntelligence
API 参考https://learn.microsoft.com/dotnet/api/azure.ai.documentintelligence
GitHub 示例https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/documentintelligence/Azure.AI.DocumentIntelligence/samples
Document Intelligence Studiohttps://documentintelligence.ai.azure.com/
预构建模型https://aka.ms/azsdk/formrecognizer/models

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

相关技能