opción
HogarHogar Skill Ciencia de datos y aprendizaje automático azure-ai-document-intelligence-ts

azure-ai-document-intelligence-ts

microsoft/skills microsoft/skills

Extraiga texto, tablas y datos estructurados de documentos utilizando Azure Document Intelligence. Procese facturas, recibos, identificaciones, formularios o cree modelos de documentos personalizados.

...Expandir todo
0
Tiempo actualizado 19 de septiembre de 2026

SDK de REST de Azure Document Intelligence para TypeScript

Extrae texto, tablas y datos estructurados de documentos utilizando modelos predefinidos y personalizados.

Instalación

npm install @azure-rest/ai-document-intelligence @azure/identity

Variables de entorno

DOCUMENT_INTELLIGENCE_ENDPOINT=https://<recurso>.cognitiveservices.azure.com
DOCUMENT_INTELLIGENCE_API_KEY=<clave-api>
AZURE_TOKEN_CREDENTIALS=prod # Solo es necesario si se usa DefaultAzureCredential en producción
</clave-api></recurso>

Autenticación

Importante: Este es un cliente REST. DocumentIntelligence es una función, no una clase.

DefaultAzureCredential

import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

// Desarrollo local: DefaultAzureCredential. Producción: establezca AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// O utilice una credencial específica directamente en producción:
// Consulte https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

const client = DocumentIntelligence(
  process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
  credential
);
</credencial_específica>

Clave de API

import DocumentIntelligence from "@azure-rest/ai-document-intelligence";

const client = DocumentIntelligence(
  process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
  { key: process.env.DOCUMENT_INTELLIGENCE_API_KEY! }
);

Analizar documento (URL)

import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  AnalyzeOperationOutput
} from "@azure-rest/ai-document-intelligence";

const respuestaInicial = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      urlSource: "https://example.com/document.pdf"
    },
    queryParameters: { locale: "en-US" }
  });

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

console.log("Páginas:", resultado.analyzeResult?.pages?.length);
console.log("Tablas:", resultado.analyzeResult?.tables?.length);

Analizar documento (archivo local)

import { readFile } from "node:fs/promises";

const bufferArchivo = await readFile("./document.pdf");
const fuenteBase64 = bufferArchivo.toString("base64");

const respuestaInicial = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-invoice")
  .post({
    contentType: "application/json",
    body: { base64Source }
  });

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

Modelos predefinidos

ID del modeloDescripción
`prebuilt-read`OCR: extracción de texto e idioma
`prebuilt-layout`Texto, tablas, marcas de selección, estructura
`prebuilt-invoice`Campos de factura
`prebuilt-receipt`Campos de recibo
`prebuilt-idDocument`Campos de documento de identidad
`prebuilt-tax.us.w2`Campos del formulario fiscal W-2
`prebuilt-healthInsuranceCard.us`Campos de la tarjeta de seguro de salud
`prebuilt-contract`Campos de contrato
`prebuilt-bankStatement.us`Campos del estado de cuenta bancario

Extraer campos de factura

const respuestaInicial = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-invoice")
  .post({
    contentType: "application/json",
    body: { urlSource: urlFactura }
  });

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

const factura = resultado.analyzeResult?.documents?.[0];
if (factura) {
  console.log("Proveedor:", factura.fields?.VendorName?.content);
  console.log("Total:", factura.fields?.InvoiceTotal?.content);
  console.log("Fecha de vencimiento:", factura.fields?.DueDate?.content);
}

Extraer campos de recibo

const respuestaInicial = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-receipt")
  .post({
    contentType: "application/json",
    body: { urlSource: urlRecibo }
  });

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

const recibo = resultado.analyzeResult?.documents?.[0];
if (recibo) {
  console.log("Comerciante:", recibo.fields?.MerchantName?.content);
  console.log("Total:", recibo.fields?.Total?.content);

  for (const item of recibo.fields?.Items?.values || []) {
    console.log("Artículo:", item.properties?.Description?.content);
    console.log("Precio:", item.properties?.TotalPrice?.content);
  }
}

Listar modelos de documentos

import DocumentIntelligence, { isUnexpected, paginate } from "@azure-rest/ai-document-intelligence";

const respuesta = await client.path("/documentModels").get();

if (isUnexpected(respuesta)) {
  throw respuesta.body.error;
}

for await (const modelo of paginate(client, respuesta)) {
  console.log(modelo.modelId);
}

Crear modelo personalizado

const respuestaInicial = await client.path("/documentModels:build").post({
  body: {
    modelId: "mi-modelo-personalizado",
    description: "Modelo personalizado para órdenes de compra",
    buildMode: "template",  // o "neural"
    azureBlobSource: {
      containerUrl: process.env.TRAINING_CONTAINER_SAS_URL!,
      prefix: "datos-entrenamiento/"
    }
  }
});

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = await poller.pollUntilDone();
console.log("Modelo creado:", resultado.body);

Crear clasificador de documentos

import { DocumentClassifierBuildOperationDetailsOutput } from "@azure-rest/ai-document-intelligence";

const urlSasContenedor = process.env.TRAINING_CONTAINER_SAS_URL!;

const respuestaInicial = await client.path("/documentClassifiers:build").post({
  body: {
    classifierId: "mi-clasificador",
    description: "Clasificador de facturas vs recibos",
    docTypes: {
      invoices: {
        azureBlobSource: { containerUrl: urlSasContenedor, prefix: "facturas/" }
      },
      receipts: {
        azureBlobSource: { containerUrl: urlSasContenedor, prefix: "recibos/" }
      }
    }
  }
});

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = (await poller.pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput;
console.log("Clasificador:", resultado.result?.classifierId);

Clasificar documento

const respuestaInicial = await client
  .path("/documentClassifiers/{classifierId}:analyze", "mi-clasificador")
  .post({
    contentType: "application/json",
    body: { urlSource: urlDocumento },
    queryParameters: { split: "auto" }
  });

if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

const poller = getLongRunningPoller(client, respuestaInicial);
const resultado = await poller.pollUntilDone();
console.log("Clasificación:", resultado.body.analyzeResult?.documents);

Obtener información del servicio

const respuesta = await client.path("/info").get();

if (isUnexpected(respuesta)) {
  throw respuesta.body.error;
}

console.log("Límite de modelos personalizados:", response.body.customDocumentModels.limit);
console.log("Cantidad de modelos personalizados:", response.body.customDocumentModels.count);

Patrón de sondeo (Polling)

import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  AnalyzeOperationOutput
} from "@azure-rest/ai-document-intelligence";

// 1. Iniciar operación
const respuestaInicial = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({ contentType: "application/json", body: { urlSource } });

// 2. Comprobar errores
if (isUnexpected(respuestaInicial)) {
  throw respuestaInicial.body.error;
}

// 3. Crear sondeador
const poller = getLongRunningPoller(client, respuestaInicial);

// 4. Opcional: Supervisar el progreso
poller.onProgress((state) => {
  console.log("Estado:", state.status);
});

// 5. Esperar a que se complete
const resultado = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

Tipos clave

import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  paginate,
  parseResultIdFromResponse,
  AnalyzeOperationOutput,
  DocumentClassifierBuildOperationDetailsOutput
} from "@azure-rest/ai-document-intelligence";

Mejores prácticas

  1. Utilice getLongRunningPoller(): El análisis de documentos es asíncrono; siempre sondee para obtener resultados.
  2. Compruebe isUnexpected(): Control de tipos para un manejo adecuado de errores.
  3. Elija el modelo adecuado: Utilice modelos predefinidos cuando sea posible; utilice modelos personalizados para documentos especializados.
  4. Gestione las puntuaciones de confianza: Los campos tienen valores de confianza; establezca umbrales para su caso de uso.
  5. Utilice paginación: Utilice la función auxiliar paginate() para listar modelos.
  6. Prefiera el modo neural: Para modelos personalizados, el modo neural maneja más variaciones que el modo plantilla.
Ver en GitHub
---
name: azure-ai-document-intelligence-ts
description: Extract text, tables, and structured data from documents using Azure Document Intelligence. Process invoices, receipts, IDs, forms, or build custom document models.
license: MIT
---

# Azure Document Intelligence REST SDK for TypeScript

Extract text, tables, and structured data from documents using prebuilt and custom models.

## Installation

```bash
npm install @azure-rest/ai-document-intelligence @azure/identity
```

## Environment Variables

```bash
DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
DOCUMENT_INTELLIGENCE_API_KEY=<api-key>
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication

**Important**: This is a REST client. `DocumentIntelligence` is a **function**, not a class.

### DefaultAzureCredential

```typescript
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

const client = DocumentIntelligence(
  process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
  credential
);
```

### API Key

```typescript
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";

const client = DocumentIntelligence(
  process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
  { key: process.env.DOCUMENT_INTELLIGENCE_API_KEY! }
);
```

## Analyze Document (URL)

```typescript
import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  AnalyzeOperationOutput
} from "@azure-rest/ai-document-intelligence";

const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({
    contentType: "application/json",
    body: {
      urlSource: "https://example.com/document.pdf"
    },
    queryParameters: { locale: "en-US" }
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

console.log("Pages:", result.analyzeResult?.pages?.length);
console.log("Tables:", result.analyzeResult?.tables?.length);
```

## Analyze Document (Local File)

```typescript
import { readFile } from "node:fs/promises";

const fileBuffer = await readFile("./document.pdf");
const base64Source = fileBuffer.toString("base64");

const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-invoice")
  .post({
    contentType: "application/json",
    body: { base64Source }
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
```

## Prebuilt Models

| Model ID | Description |
|----------|-------------|
| `prebuilt-read` | OCR - text and language extraction |
| `prebuilt-layout` | Text, tables, selection marks, structure |
| `prebuilt-invoice` | Invoice fields |
| `prebuilt-receipt` | Receipt fields |
| `prebuilt-idDocument` | ID document fields |
| `prebuilt-tax.us.w2` | W-2 tax form fields |
| `prebuilt-healthInsuranceCard.us` | Health insurance card fields |
| `prebuilt-contract` | Contract fields |
| `prebuilt-bankStatement.us` | Bank statement fields |

## Extract Invoice Fields

```typescript
const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-invoice")
  .post({
    contentType: "application/json",
    body: { urlSource: invoiceUrl }
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

const invoice = result.analyzeResult?.documents?.[0];
if (invoice) {
  console.log("Vendor:", invoice.fields?.VendorName?.content);
  console.log("Total:", invoice.fields?.InvoiceTotal?.content);
  console.log("Due Date:", invoice.fields?.DueDate?.content);
}
```

## Extract Receipt Fields

```typescript
const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-receipt")
  .post({
    contentType: "application/json",
    body: { urlSource: receiptUrl }
  });

const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;

const receipt = result.analyzeResult?.documents?.[0];
if (receipt) {
  console.log("Merchant:", receipt.fields?.MerchantName?.content);
  console.log("Total:", receipt.fields?.Total?.content);
  
  for (const item of receipt.fields?.Items?.values || []) {
    console.log("Item:", item.properties?.Description?.content);
    console.log("Price:", item.properties?.TotalPrice?.content);
  }
}
```

## List Document Models

```typescript
import DocumentIntelligence, { isUnexpected, paginate } from "@azure-rest/ai-document-intelligence";

const response = await client.path("/documentModels").get();

if (isUnexpected(response)) {
  throw response.body.error;
}

for await (const model of paginate(client, response)) {
  console.log(model.modelId);
}
```

## Build Custom Model

```typescript
const initialResponse = await client.path("/documentModels:build").post({
  body: {
    modelId: "my-custom-model",
    description: "Custom model for purchase orders",
    buildMode: "template",  // or "neural"
    azureBlobSource: {
      containerUrl: process.env.TRAINING_CONTAINER_SAS_URL!,
      prefix: "training-data/"
    }
  }
});

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = await poller.pollUntilDone();
console.log("Model built:", result.body);
```

## Build Document Classifier

```typescript
import { DocumentClassifierBuildOperationDetailsOutput } from "@azure-rest/ai-document-intelligence";

const containerSasUrl = process.env.TRAINING_CONTAINER_SAS_URL!;

const initialResponse = await client.path("/documentClassifiers:build").post({
  body: {
    classifierId: "my-classifier",
    description: "Invoice vs Receipt classifier",
    docTypes: {
      invoices: {
        azureBlobSource: { containerUrl: containerSasUrl, prefix: "invoices/" }
      },
      receipts: {
        azureBlobSource: { containerUrl: containerSasUrl, prefix: "receipts/" }
      }
    }
  }
});

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = (await poller.pollUntilDone()).body as DocumentClassifierBuildOperationDetailsOutput;
console.log("Classifier:", result.result?.classifierId);
```

## Classify Document

```typescript
const initialResponse = await client
  .path("/documentClassifiers/{classifierId}:analyze", "my-classifier")
  .post({
    contentType: "application/json",
    body: { urlSource: documentUrl },
    queryParameters: { split: "auto" }
  });

if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

const poller = getLongRunningPoller(client, initialResponse);
const result = await poller.pollUntilDone();
console.log("Classification:", result.body.analyzeResult?.documents);
```

## Get Service Info

```typescript
const response = await client.path("/info").get();

if (isUnexpected(response)) {
  throw response.body.error;
}

console.log("Custom model limit:", response.body.customDocumentModels.limit);
console.log("Custom model count:", response.body.customDocumentModels.count);
```

## Polling Pattern

```typescript
import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  AnalyzeOperationOutput
} from "@azure-rest/ai-document-intelligence";

// 1. Start operation
const initialResponse = await client
  .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
  .post({ contentType: "application/json", body: { urlSource } });

// 2. Check for errors
if (isUnexpected(initialResponse)) {
  throw initialResponse.body.error;
}

// 3. Create poller
const poller = getLongRunningPoller(client, initialResponse);

// 4. Optional: Monitor progress
poller.onProgress((state) => {
  console.log("Status:", state.status);
});

// 5. Wait for completion
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
```

## Key Types

```typescript
import DocumentIntelligence, {
  isUnexpected,
  getLongRunningPoller,
  paginate,
  parseResultIdFromResponse,
  AnalyzeOperationOutput,
  DocumentClassifierBuildOperationDetailsOutput
} from "@azure-rest/ai-document-intelligence";
```

## Best Practices

1. **Use getLongRunningPoller()** - Document analysis is async, always poll for results
2. **Check isUnexpected()** - Type guard for proper error handling
3. **Choose the right model** - Use prebuilt models when possible, custom for specialized docs
4. **Handle confidence scores** - Fields have confidence values, set thresholds for your use case
5. **Use pagination** - Use `paginate()` helper for listing models
6. **Prefer neural mode** - For custom models, neural handles more variation than template

Todos los archivos

0 archivos

Instalar azure-ai-document-intelligence-ts

Descarga y extrae los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/azure-ai-document-intelligence-ts # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuración rápida: Copie la carpeta de habilidades a .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

web-search
Tiempo actualizado 29 de junio de 2026
webapp-testing
Tiempo actualizado 29 de junio de 2026
lark-base
Tiempo actualizado 5 de julio de 2026
agentmail
Tiempo actualizado 29 de junio de 2026
OR