Communitygithub.com

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET。從文件中提取文字、表格和結構化資料,支援預建模型和自訂模型。適用於發票處理、收據提取、身分證件分析以及自訂文件模型。觸發詞:「Document Intelligence」、「DocumentIntelligenceClient」、「form recognizer」、「invoice extraction」、「receipt OCR」、「document analysis .NET」。

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

此技能提供完整的 Azure AI Document Intelligence .NET SDK 整合,讓開發者能夠從文件中提取文字、表格和結構化資料。它支援多種預建模型,如發票、收據、身分證件、名片、W-2 稅表等,並允許建立自訂模型與文件分類器。技能涵蓋了透過 Microsoft Entra 權杖憑證或 API 金鑰進行驗證、分析文件、提取版面配置、建立自訂模型、訓練分類器以及管理模型生命週期。安裝簡單,僅需兩個 NuGet 套件,並透過環境變數設定端點與憑證。此技能適用於 Cursor、Codex 等支援 .NET 的 AI 代理平台,讓開發者以 C# 程式碼直接與 Azure 文件智慧服務互動。

相容平台~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 (GA)

環境變數

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource-name>.cognitiveservices.azure.com/  # 必要:Document Intelligence 端點
DOCUMENT_INTELLIGENCE_API_KEY=<your-api-key>  # 僅在 AzureKeyCredential 驗證時需要
BLOB_CONTAINER_SAS_URL=https://<storage>.blob.core.windows.net/<container>?<sas-token>  # 選用:訓練資料的 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=<specific_credential>
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://<resource-name>.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.

相關技能