azure-ai-document-intelligence-ts について
Azure Document Intelligence REST SDKを使うTypeScript向けスキルです。事前構築モデルやカスタムモデルによる文書分析、分類、モデル管理の手順を扱います。
主な機能
- 01事前構築モデルで文書を分析
- 02テキスト、表、フィールドを抽出
- 03カスタムモデルと分類器を構築
- 04非同期処理のポーリングとエラー処理
- 05ページネーションでモデルを一覧表示
活用シーン
- 01請求書やレシートの項目抽出
- 02PDFのレイアウトとテキストの読み取り
- 03専門文書向けモデルの学習
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-ai-document-intelligence-tsインストール後、Claude Code で/azure-ai-document-intelligence-tsを入力して読み込まれたか確認します。
詳細
TypeScript 用 Azure Document Intelligence REST SDK
事前構築済みモデルとカスタムモデルを使用して、ドキュメントからテキスト、表、構造化データを抽出します。
インストール
互換性のある REST SDK/API のバージョンを固定し、対象リージョンでモデルが利用可能か確認してください。ドキュメントのアップロードや URL 分析ではコンテンツが Azure に開示され、料金が発生する場合があります。許可されたドキュメントのみを使用し、有効期間が短くスコープを限定した SAS と、承認済みの保持設定を使用してください。抽出された ID、医療情報や銀行情報、SAS URL は決してログに記録しないでください。信頼度スコアは較正された保証ではありません。重要な合計値や日付を元のドキュメントと照合し、不確かな結果はレビューに回してください。ポーリングには期限または中止シグナルを設定し、操作の最終ステータスを確認してください。レスポンス型をキャストしても、成功が証明されるわけではありません。
npm install @azure-rest/ai-document-intelligence @azure/identity
環境変数
DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
DOCUMENT_INTELLIGENCE_API_KEY=<api-key>
認証
重要:これは REST クライアントです。DocumentIntelligence はクラスではなく関数です。
DefaultAzureCredential
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
import { DefaultAzureCredential } from "@azure/identity";
const client = DocumentIntelligence(
process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
new DefaultAzureCredential()
);
API キー
import DocumentIntelligence from "@azure-rest/ai-document-intelligence";
const client = DocumentIntelligence(
process.env.DOCUMENT_INTELLIGENCE_ENDPOINT!,
{ key: process.env.DOCUMENT_INTELLIGENCE_API_KEY! }
);
ドキュメントを分析する https://example.com
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);
ドキュメントを分析する(ローカルファイル)
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 | ID ドキュメントのフィールド |
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("Vendor:", invoice.fields?.VendorName?.content);
console.log("Total:", invoice.fields?.InvoiceTotal?.content);
console.log("Due Date:", invoice.fields?.DueDate?.content);
}
領収書のフィールドを抽出する
const initialResponse = await client
.path("/documentModels/{modelId}:analyze", "prebuilt-receipt")
.post({
contentType: "application/json",
body: { urlSource: receiptUrl }
});
if (isUnexpected(initialResponse)) throw initialResponse.body.error;
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);
}
}
ドキュメントモデルを一覧表示する
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: "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);
ドキュメント分類器を構築する
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);
ドキュメントを分類する
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);
サービス情報を取得する
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);
ポーリングパターン
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;
主要な型
import DocumentIntelligence, {
isUnexpected,
getLongRunningPoller,
paginate,
parseResultIdFromResponse,
AnalyzeOperationOutput,
DocumentClassifierBuildOperationDetailsOutput
} from "@azure-rest/ai-document-intelligence";
ベストプラクティス
- getLongRunningPoller() を使用する - ドキュメント分析は非同期処理のため、必ず結果をポーリングしてください
- isUnexpected() を確認する - 適切なエラー処理のための型ガードです
- 適切なモデルを選択する - 可能な場合は事前構築済みモデルを使用し、特殊なドキュメントにはカスタムモデルを使用してください
- 信頼度スコアを処理する - フィールドには信頼度の値があります。用途に応じてしきい値を設定してください
- ページネーションを使用する - モデルの一覧表示には
paginate()ヘルパーを使用してください - ニューラルモードを優先する - カスタムモデルでは、ニューラルモードはテンプレートよりも多様な形式に対応します
使用する場面
このスキルは、概要に記載されたワークフローやアクションを実行する場合に適用できます。
制限事項
- このスキルは、タスクが上記の説明の範囲に明確に該当する場合にのみ使用してください。
- 出力を、環境固有の検証、テスト、専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、作業を中断して確認してください。
コメント
Markdown 対応