azure-ai-document-intelligence-ts
microsoft/skills
Azure Document Intelligence를 사용하여 문서에서 텍스트, 테이블 및 구조화된 데이터를 추출합니다. 송장, 영수증, 신분증, 양식을 처리하거나 사용자 정의 문서 모델을 구축할 수 있습니다.
...모든 것을 확장하십시오Azure Document Intelligence REST SDK for TypeScript
사전 구축된 모델과 사용자 정의 모델을 사용하여 문서에서 텍스트, 표 및 구조화된 데이터를 추출합니다.
설치
npm install @azure-rest/ai-document-intelligence @azure/identity
환경 변수
DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
DOCUMENT_INTELLIGENCE_API_KEY=<api-key>
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필요
</api-key></resource>인증
중요: 이것은 REST 클라이언트입니다. DocumentIntelligence는 클래스가 아닌 함수입니다.
DefaultAzureCredential
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";
// 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=<specific_credential> 설정
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// 또는 프로덕션에서 특정 자격 증명을 직접 사용:
// 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
);
</specific_credential>API 키
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(
process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
{ key: process.env.DOCUMENT_INTELLIGENCE_API_KEY! }
);
문서 분석 (URL)
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("페이지 수:", result.analyzeResult?.pages?.length);
console.log("표 수:", result.analyzeResult?.tables?.length);
문서 분석 (로컬 파일)
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;
사전 구축 모델
| 모델 ID | 설명 |
|---|---|
| `prebuilt-read` | OCR - 텍스트 및 언어 추출 |
| `prebuilt-layout` | 텍스트, 표, 선택 표시, 구조 |
| `prebuilt-invoice` | 송장 필드 |
| `prebuilt-receipt` | 영수증 필드 |
| `prebuilt-idDocument` | 신분증 필드 |
| `prebuilt-tax.us.w2` | W-2 세금 양식 필드 |
| `prebuilt-healthInsuranceCard.us` | 건강 보험 카드 필드 |
| `prebuilt-contract` | 계약 필드 |
| `prebuilt-bankStatement.us` | 은행 명세서 필드 |
송장 필드 추출
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("공급자:", invoice.fields?.VendorName?.content);
console.log("합계:", invoice.fields?.InvoiceTotal?.content);
console.log("만기일:", invoice.fields?.DueDate?.content);
}
영수증 필드 추출
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("상점:", receipt.fields?.MerchantName?.content);
console.log("합계:", receipt.fields?.Total?.content);
for (const item of receipt.fields?.Items?.values || []) {
console.log("항목:", item.properties?.Description?.content);
console.log("가격:", item.properties?.TotalPrice?.content);
}
}
문서 모델 목록 조회
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);
}
사용자 정의 모델 빌드
const initialResponse = await client.path("/documentModels:build").post({
body: {
modelId: "my-custom-model",
description: "구매 주문용 사용자 정의 모델",
buildMode: "template", // 또는 "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("모델 빌드 완료:", result.body);
문서 분류기 빌드
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: "송장 대 영수증 분류기",
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("분류기:", result.result?.classifierId);
문서 분류
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("분류 결과:", result.body.analyzeResult?.documents);
서비스 정보 가져오기
const response = await client.path("/info").get();
if (isUnexpected(response)) {
throw response.body.error;
}
console.log("사용자 정의 모델 제한:", response.body.customDocumentModels.limit);
console.log("사용자 정의 모델 수:", response.body.customDocumentModels.count);
폴링 패턴
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
AnalyzeOperationOutput
} from "@azure-rest/ai-document-intelligence";
// 1. 작업 시작
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-layout")
.post({ contentType: "application/json", body: { urlSource } });
// 2. 오류 확인
if (isUnexpected(initialResponse)) {
throw initialResponse.body.error;
}
// 3. 폴커 생성
const poller = getLongRunningPoller(client, initialResponse);
// 4. 선택 사항: 진행 상황 모니터링
poller.onProgress((state) => {
console.log("상태:", state.status);
});
// 5. 완료 대기
const result = (await poller.pollUntilDone()).body as AnalyzeOperationOutput;
주요 타입
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
paginate,
parseResultIdFromResponse,
AnalyzeOperationOutput,
DocumentClassifierBuildOperationDetailsOutput
} from "@azure-rest/ai-document-intelligence";
모범 사례
- getLongRunningPoller() 사용 - 문서 분석은 비동기이므로 항상 결과를 폴링하십시오.
- isUnexpected() 확인 - 적절한 오류 처리를 위한 타입 가드입니다.
- 올바른 모델 선택 - 가능한 경우 사전 구축 모델을 사용하고, 특수한 문서에는 사용자 정의 모델을 사용하십시오.
- 신뢰도 점수 처리 - 필드에는 신뢰도 값이 있으므로 사용 사례에 따라 임계값을 설정하십시오.
- 페이지네이션 사용 - 모델 목록 조회에는
paginate()도우미를 사용하십시오. - 신경망 모드 선호 - 사용자 정의 모델의 경우, 신경망 모드가 템플릿 모드보다 더 많은 변형을 처리합니다.
---
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
모든 파일
0개 파일azure-ai-document-intelligence-ts 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉토리에 추출하세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
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
복사





집
