Communitygithub.com

microsoft/azure-ai-document-intelligence-dotnet

.NET 用 Azure AI Document Intelligence SDK。事前構築モデルとカスタムモデルを使用して、ドキュメントからテキスト、表、構造化データを抽出します。請求書処理、領収書抽出、ID 文書分析、カスタムドキュメントモデルに使用します。トリガー:「Document Intelligence」「DocumentIntelligenceClient」「form recognizer」「invoice extraction」「receipt OCR」「document analysis .NET」。

azure-ai-document-intelligence-dotnet とは?

このスキルは、Azure AI Document Intelligence .NET SDK を活用して、ドキュメントからテキスト、表、構造化データを抽出するための包括的なガイドを提供します。事前構築済みモデル(請求書、領収書、ID 文書など)と、固定レイアウトまたは可変レイアウトのドキュメント用のカスタムモデルの両方をサポートしています。主な機能には、ドキュメント分析、カスタムモデルの構築、ドキュメント分類、モデル管理などがあります。認証方法としては、Microsoft Entra ID(トークン資格情報)と API キーの両方をサポートしています。スキルには、請求書分析、レイアウト抽出、領収書分析、カスタムモデルの構築と分類、モデル管理のための完全な C# コード例が含まれています。環境変数、ベストプラクティス、エラー処理についても説明しています。プラットフォームは .NET で、Visual Studio、VS Code、.NET CLI などのツールと互換性があります。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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-idDocumentID 文書フィールド(名前、生年月日、住所)を抽出
prebuilt-businessCard名刺フィールドを抽出
prebuilt-tax.us.w2W-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.

関連スキル