Communitygithub.com

microsoft/azure-ai-document-intelligence-dotnet

SDK de IA de Documentos do Azure para .NET. Extraia texto, tabelas e dados estruturados de documentos usando modelos predefinidos e personalizados. Use para processamento de faturas, extração de recibos, análise de documentos de identificação e modelos personalizados. Gatilhos: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "extração de fatura", "OCR de recibo", "análise de documentos .NET".

O que é azure-ai-document-intelligence-dotnet?

Este SDK .NET fornece uma interface robusta para o serviço Azure AI Document Intelligence, permitindo que você extraia texto, tabelas e dados estruturados de documentos utilizando modelos pré-construídos e personalizados. Ele é ideal para tarefas como processamento de faturas, extração de recibos, análise de documentos de identidade e criação de modelos de documentos personalizados. A habilidade oferece suporte a plataformas .NET e utiliza os pacotes `Azure.AI.DocumentIntelligence` e `Azure.Identity`. O funcionamento é baseado na autenticação via Microsoft Entra ID ou chave de API, e os fluxos de trabalho principais incluem análise de documentos com modelos predefinidos, extração de layout, construção de modelos personalizados e classificação de documentos. A SKILL.md documenta detalhadamente a instalação, configuração de variáveis de ambiente, exemplos de código C# para vários cenários e melhores práticas, como reutilização de instâncias do cliente e verificação de confiança dos campos extraídos.

Funciona com~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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.AI.DocumentIntelligence (.NET)

Extraia texto, tabelas e dados estruturados de documentos usando modelos predefinidos e personalizados.

Instalação

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

Versão Atual: v1.0.0 (GA)

Variáveis de Ambiente

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource-name>.cognitiveservices.azure.com/  # Obrigatório: endpoint do Document Intelligence
DOCUMENT_INTELLIGENCE_API_KEY=<your-api-key>  # Obrigatório apenas para autenticação AzureKeyCredential
BLOB_CONTAINER_SAS_URL=https://<storage>.blob.core.windows.net/<container>?<sas-token>  # Opcional: URL SAS do contêiner de blob para dados de treinamento
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação

Credencial de Token do Microsoft Entra

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

string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_específico>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// Consulte 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);

Nota: O Entra ID requer um subdomínio personalizado (ex.: https://<resource-name>.cognitiveservices.azure.com/), não um endpoint regional.

Chave de 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));

Tipos de Cliente

ClienteFinalidade
DocumentIntelligenceClientAnalisar documentos, classificar documentos
DocumentIntelligenceAdministrationClientConstruir/gerenciar modelos e classificadores personalizados

Modelos Predefinidos

ID do ModeloDescrição
prebuilt-readExtrair texto, idiomas, manuscrito
prebuilt-layoutExtrair texto, tabelas, marcas de seleção, estrutura
prebuilt-invoiceExtrair campos de fatura (fornecedor, itens, totais)
prebuilt-receiptExtrair campos de recibo (comerciante, itens, total)
prebuilt-idDocumentExtrair campos de documento de identificação (nome, data de nascimento, endereço)
prebuilt-businessCardExtrair campos de cartão de visita
prebuilt-tax.us.w2Extrair campos do formulário fiscal W-2
prebuilt-healthInsuranceCard.usExtrair campos de cartão de seguro saúde

Fluxos de Trabalho Principais

1. Analisar Fatura

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($"Nome do Fornecedor: '{vendorName}', confiança: {vendorNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
        && invoiceTotalField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
        Console.WriteLine($"Total da Fatura: '{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
    }
    
    // Extrair itens de linha
    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($"  Item: {descField.ValueString}");
        }
    }
}

2. Extrair Layout (Texto, Tabelas, Estrutura)

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

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

AnalyzeResult result = operation.Value;

// Extrair texto por página
foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Página {page.PageNumber}: {page.Lines.Count} linhas, {page.Words.Count} palavras");
    
    foreach (DocumentLine line in page.Lines)
    {
        Console.WriteLine($"  Linha: '{line.Content}'");
    }
}

// Extrair tabelas
foreach (DocumentTable table in result.Tables)
{
    Console.WriteLine($"Tabela: {table.RowCount} linhas x {table.ColumnCount} colunas");
    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"  Célula ({cell.RowIndex}, {cell.ColumnIndex}): {cell.Content}");
    }
}

3. Analisar Recibo

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($"Comerciante: {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($"Data: {dateField.ValueDate}");
}

4. Construir Modelo Personalizado

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

string modelId = "meu-modelo-personalizado";
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 do Modelo: {model.ModelId}");
Console.WriteLine($"Criado em: {model.CreatedOn}");

foreach (var docType in model.DocumentTypes)
{
    Console.WriteLine($"Tipo de documento: {docType.Key}");
    foreach (var field in docType.Value.FieldSchema)
    {
        Console.WriteLine($"  Campo: {field.Key}, Confiança: {docType.Value.FieldConfidence[field.Key]}");
    }
}

5. Construir Classificador de Documentos

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

var sourceA = new BlobContentSource(blobContainerUri) { Prefix = "TipoA/treino" };
var sourceB = new BlobContentSource(blobContainerUri) { Prefix = "TipoB/treino" };

var docTypes = new Dictionary<string, ClassifierDocumentTypeDetails>()
{
    { "TipoA", new ClassifierDocumentTypeDetails(sourceA) },
    { "TipoB", 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 do Classificador: {classifier.ClassifierId}");

6. Classificar Documento

string classifierId = "meu-classificador";
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($"Tipo de documento: {document.DocumentType}, confiança: {document.Confidence}");
}

7. Gerenciar Modelos

// Obter detalhes do recurso
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"Modelos personalizados: {resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");

// Obter modelo específico
DocumentModelDetails model = await adminClient.GetModelAsync("meu-id-modelo");
Console.WriteLine($"Modelo: {model.ModelId}, Criado em: {model.CreatedOn}");

// Listar modelos
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
    Console.WriteLine($"Modelo: {modelItem.ModelId}");
}

// Excluir modelo
await adminClient.DeleteModelAsync("meu-id-modelo");

Referência de Tipos Principais

TipoDescrição
DocumentIntelligenceClientCliente principal para análise
DocumentIntelligenceAdministrationClientGerenciamento de modelos
AnalyzeResultResultado da análise de documento
AnalyzedDocumentDocumento único dentro do resultado
DocumentFieldCampo extraído com valor e confiança
DocumentFieldTypeString, Date, Number, Currency, etc.
DocumentPageInformações da página (linhas, palavras, marcas de seleção)
DocumentTableTabela extraída com células
DocumentModelDetailsMetadados do modelo personalizado
BlobContentSourceFonte de dados de treinamento

Modos de Construção

ModoCaso de Uso
DocumentBuildMode.TemplateDocumentos com layout fixo (formulários)
DocumentBuildMode.NeuralDocumentos com layout variável

Melhores Práticas

  1. Use DefaultAzureCredential para produção
  2. Reutilize instâncias do cliente — os clientes são thread-safe
  3. Lide com operações de longa duração — Use WaitUntil.Completed para simplicidade
  4. Verifique a confiança dos campos — Sempre verifique a propriedade Confidence
  5. Use o modelo apropriado — Predefinido para documentos comuns, personalizado para especializados
  6. Use subdomínio personalizado — Obrigatório para autenticação com Entra ID

Tratamento de Erros

using Azure;

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

SDKs Relacionados

SDKFinalidadeInstalação
Azure.AI.DocumentIntelligenceAnálise de documentos (este SDK)dotnet add package Azure.AI.DocumentIntelligence
Azure.AI.FormRecognizerSDK legado (obsoleto)Use DocumentIntelligence no lugar

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.AI.DocumentIntelligence
Referência de APIhttps://learn.microsoft.com/dotnet/api/azure.ai.documentintelligence
Exemplos no GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/documentintelligence/Azure.AI.DocumentIntelligence/samples
Document Intelligence Studiohttps://documentintelligence.ai.azure.com/
Modelos Predefinidoshttps://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.

Habilidades Relacionadas