Communitygithub.com

microsoft/azure-ai-document-intelligence-dotnet

SDK Azure AI Document Intelligence pour .NET. Extrayez du texte, des tableaux et des données structurées de documents à l'aide de modèles prédéfinis et personnalisés. Utilisez-le pour le traitement de factures, l'extraction de reçus, l'analyse de documents d'identité et les modèles de documents personnalisés. Déclencheurs : "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

Qu'est-ce que azure-ai-document-intelligence-dotnet ?

Azure.AI.DocumentIntelligence (.NET) est le SDK officiel Azure pour .NET, permettant d'exploiter les capacités d'Azure AI Document Intelligence (anciennement Form Recognizer). Cette compétence permet aux agents IA d'extraire automatiquement du texte, des tableaux, des champs clés (comme les montants de factures ou les noms de commerçants) et des données structurées à partir de documents variés (PDF, images, etc.) en utilisant des modèles prédéfinis (factures, reçus, documents d'identité) ou des modèles personnalisés. Elle supporte également la classification de documents et la gestion de modèles via des workflows asynchrones. L'authentification peut se faire par clé API ou via Microsoft Entra ID (DefaultAzureCredential). Les plateformes cibles incluent les applications .NET, les fonctions Azure et tout environnement capable d'exécuter du code C#. Les fonctionnalités clés incluent l'analyse de documents, l'extraction de layout, la construction de modèles personnalisés (template ou neural) et la classification de documents, le tout avec une gestion d'erreurs robuste et des bonnes pratiques de réutilisation des clients.

Compatible avec~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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Azure.AI.DocumentIntelligence (.NET)

Extrayez du texte, des tableaux et des données structurées de documents à l'aide de modèles prédéfinis et personnalisés.

Installation

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

Version actuelle : v1.0.0 (GA)

Variables d'environnement

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<nom-ressource>.cognitiveservices.azure.com/  # Requis : point de terminaison Document Intelligence
DOCUMENT_INTELLIGENCE_API_KEY=<votre-clé-api>  # Requis uniquement pour l'authentification AzureKeyCredential
BLOB_CONTAINER_SAS_URL=https://<stockage>.blob.core.windows.net/<conteneur>?<jeton-sas>  # Optionnel : URL SAS du conteneur de blobs pour les données d'entraînement
AZURE_TOKEN_CREDENTIALS=prod  # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification

Jeton d'identité Microsoft Entra

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

string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
// Développement local : DefaultAzureCredential. Production : définissez AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utilisez un credential spécifique directement en production :
// Voir 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);

Remarque : Entra ID nécessite un sous-domaine personnalisé (par exemple, https://<nom-ressource>.cognitiveservices.azure.com/), et non un point de terminaison régional.

Clé 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));

Types de clients

ClientObjectif
DocumentIntelligenceClientAnalyser des documents, classer des documents
DocumentIntelligenceAdministrationClientCréer/gérer des modèles et classifieurs personnalisés

Modèles prédéfinis

ID du modèleDescription
prebuilt-readExtraire du texte, des langues, de l'écriture manuscrite
prebuilt-layoutExtraire du texte, des tableaux, des marques de sélection, la structure
prebuilt-invoiceExtraire les champs de facture (fournisseur, articles, totaux)
prebuilt-receiptExtraire les champs de reçu (commerçant, articles, total)
prebuilt-idDocumentExtraire les champs de document d'identité (nom, date de naissance, adresse)
prebuilt-businessCardExtraire les champs de carte de visite
prebuilt-tax.us.w2Extraire les champs du formulaire fiscal W-2
prebuilt-healthInsuranceCard.usExtraire les champs de carte d'assurance maladie

Workflows principaux

1. Analyser une facture

using Azure.AI.DocumentIntelligence;

Uri invoiceUri = new Uri("https://exemple.com/facture.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($"Nom du fournisseur : '{vendorName}', confiance : {vendorNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
        && invoiceTotalField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
        Console.WriteLine($"Total de la facture : '{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
    }
    
    // Extraire les lignes d'articles
    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($"  Article : {descField.ValueString}");
        }
    }
}

2. Extraire la mise en page (texte, tableaux, structure)

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

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

AnalyzeResult result = operation.Value;

// Extraire le texte par page
foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Page {page.PageNumber} : {page.Lines.Count} lignes, {page.Words.Count} mots");
    
    foreach (DocumentLine line in page.Lines)
    {
        Console.WriteLine($"  Ligne : '{line.Content}'");
    }
}

// Extraire les tableaux
foreach (DocumentTable table in result.Tables)
{
    Console.WriteLine($"Tableau : {table.RowCount} lignes x {table.ColumnCount} colonnes");
    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"  Cellule ({cell.RowIndex}, {cell.ColumnIndex}) : {cell.Content}");
    }
}

3. Analyser un reçu

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($"Commerçant : {merchantField.ValueString}");
        
    if (document.Fields.TryGetValue("Total", out DocumentField totalField))
        Console.WriteLine($"Total : {totalField.ValueCurrency.Amount}");
        
    if (document.Fields.TryGetValue("TransactionDate", out DocumentField dateField))
        Console.WriteLine($"Date : {dateField.ValueDate}");
}

4. Créer un modèle personnalisé

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

string modelId = "mon-modele-personnalise";
Uri blobContainerUri = new Uri("<url-sas-conteneur-blob>");

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 du modèle : {model.ModelId}");
Console.WriteLine($"Créé le : {model.CreatedOn}");

foreach (var docType in model.DocumentTypes)
{
    Console.WriteLine($"Type de document : {docType.Key}");
    foreach (var field in docType.Value.FieldSchema)
    {
        Console.WriteLine($"  Champ : {field.Key}, Confiance : {docType.Value.FieldConfidence[field.Key]}");
    }
}

5. Créer un classifieur de documents

string classifierId = "mon-classifieur";
Uri blobContainerUri = new Uri("<url-sas-conteneur-blob>");

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 du classifieur : {classifier.ClassifierId}");

6. Classifier un document

string classifierId = "mon-classifieur";
Uri documentUri = new Uri("https://exemple.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($"Type de document : {document.DocumentType}, confiance : {document.Confidence}");
}

7. Gérer les modèles

// Obtenir les détails de la ressource
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"Modèles personnalisés : {resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");

// Obtenir un modèle spécifique
DocumentModelDetails model = await adminClient.GetModelAsync("mon-id-modele");
Console.WriteLine($"Modèle : {model.ModelId}, Créé le : {model.CreatedOn}");

// Lister les modèles
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
    Console.WriteLine($"Modèle : {modelItem.ModelId}");
}

// Supprimer un modèle
await adminClient.DeleteModelAsync("mon-id-modele");

Référence des types clés

TypeDescription
DocumentIntelligenceClientClient principal pour l'analyse
DocumentIntelligenceAdministrationClientGestion des modèles
AnalyzeResultRésultat de l'analyse de document
AnalyzedDocumentDocument unique dans le résultat
DocumentFieldChamp extrait avec valeur et confiance
DocumentFieldTypeString, Date, Number, Currency, etc.
DocumentPageInformations de page (lignes, mots, marques de sélection)
DocumentTableTableau extrait avec cellules
DocumentModelDetailsMétadonnées du modèle personnalisé
BlobContentSourceSource des données d'entraînement

Modes de construction

ModeCas d'usage
DocumentBuildMode.TemplateDocuments à mise en page fixe (formulaires)
DocumentBuildMode.NeuralDocuments à mise en page variable

Bonnes pratiques

  1. Utilisez DefaultAzureCredential pour la production
  2. Réutilisez les instances de client — les clients sont thread-safe
  3. Gérez les opérations longues — Utilisez WaitUntil.Completed pour simplifier
  4. Vérifiez la confiance des champs — Vérifiez toujours la propriété Confidence
  5. Utilisez le modèle approprié — Prédéfini pour les documents courants, personnalisé pour les spécialisés
  6. Utilisez un sous-domaine personnalisé — Requis pour l'authentification Entra ID

Gestion des erreurs

using Azure;

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

SDKs associés

SDKObjectifInstallation
Azure.AI.DocumentIntelligenceAnalyse de documents (ce SDK)dotnet add package Azure.AI.DocumentIntelligence
Azure.AI.FormRecognizerSDK hérité (obsolète)Utilisez DocumentIntelligence à la place

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.AI.DocumentIntelligence
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.ai.documentintelligence
Exemples GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/documentintelligence/Azure.AI.DocumentIntelligence/samples
Document Intelligence Studiohttps://documentintelligence.ai.azure.com/
Modèles prédéfinishttps://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.

Skills associés