Node.js SDK(非公式)

LangExtract情報抽出のJavaScript/TypeScriptクライアント

重要なお知らせ

これはLangExtractの非公式Node.js SDKです。Googleとの関連や承認はありません。公式Pythonライブラリについては、 公式GitHubリポジトリ.

インストール

npmまたはyarnを使用してLangExtract Node.js SDKをインストール:

# npm
npm install langextract

# yarn
yarn add langextract

# pnpm
pnpm add langextract

クイックスタート

このシンプルな例でNode.jsでLangExtractを始めましょう:

基本的な使用法

TypeScriptを使用してテキストから情報を抽出:

import { extract, ExampleData } from "langextract";

const examples: ExampleData[] = [
  {
    text: "John Smith is 30 years old and works at Google.",
    extractions: [
      {
        extractionClass: "person",
        extractionText: "John Smith",
        attributes: {
          age: "30",
          employer: "Google"
        }
      }
    ]
  }
];

async function extractPersonInfo() {
  const result = await extract("Alice Johnson is 25 and works at Microsoft.", {
    promptDescription: "Extract person information including name, age, and employer",
    examples: examples,
    modelType: "gemini",
    apiKey: process.env.LANGEXTRACT_API_KEY
  });
  
  console.log(result.extractions);
}

設定

APIキーの設定

Geminiなどのクラウドモデル用のAPIキーを設定:

# .envファイル
LANGEXTRACT_API_KEY=your-api-key-here

サポートされるモデル

SDKは複数のLLMプロバイダーをサポート:

  • Google Geminiモデル(推奨)
  • OpenAI GPTモデル
  • ローカルOllamaモデル

APIリファレンス

extract()

テキストから情報を抽出するメインメソッド

async function extract(
  text: string,
  options: {
    promptDescription: string;
    examples: ExampleData[];
    modelType: "gemini" | "openai" | "ollama";
    apiKey?: string;
    modelId?: string;
  }
): Promise<ExtractionResult>

visualize()

抽出結果のインタラクティブHTMLビジュアライゼーションを生成

function visualize(
  results: ExtractionResult[],
  options?: {
    theme?: "light" | "dark";
    highlightColors?: string[];
  }
): string

batchExtract()

複数のドキュメントを並列処理

async function batchExtract(
  documents: string[],
  options: ExtractOptions & {
    concurrency?: number;
    onProgress?: (completed: number, total: number) => void;
  }
): Promise<ExtractionResult[]>

コード例

基本的な抽出

シンプルなテキストからエンティティを抽出

const result = await extract("The product costs $99.99", {
  promptDescription: "Extract product price",
  examples: [{
    text: "Price: $50",
    extractions: [{
      extractionClass: "price",
      extractionText: "$50"
    }]
  }],
  modelType: "gemini"
});

高度な機能

属性とカスタム抽出クラスの使用

const examples = [{
  text: "Dr. Smith prescribed 500mg aspirin",
  extractions: [{
    extractionClass: "medication",
    extractionText: "aspirin",
    attributes: {
      dosage: "500mg",
      prescriber: "Dr. Smith"
    }
  }]
}];

バッチ処理

複数のドキュメントを効率的に処理

const documents = [
  "Document 1 content...",
  "Document 2 content...",
  "Document 3 content..."
];

const results = await batchExtract(documents, {
  promptDescription: "Extract entities",
  examples: examples,
  modelType: "gemini",
  concurrency: 3,
  onProgress: (done, total) => {
    console.log(`Progress: ${done}/${total}`);
  }
});

ビジュアライゼーション

インタラクティブビジュアライゼーションの生成と保存

const html = visualize(results, {
  theme: "light",
  highlightColors: ["#3B82F6", "#10B981", "#F59E0B"]
});

// Save to file
import { writeFileSync } from "fs";
writeFileSync("results.html", html);

TypeScriptサポート

型定義を含む完全なTypeScriptサポート:

  • すべてのAPIメソッドの完全な型定義
  • VS Codeや他のIDEでのIntelliSenseサポート
  • 型安全な抽出結果
  • カスタム抽出クラスのジェネリック型

エラーハンドリング

適切なエラーハンドリングパターン:

エラーハンドリングの例

APIエラーと検証失敗の処理

try {
  const result = await extract(text, options);
  console.log("Extraction successful:", result);
} catch (error) {
  if (error.code === "INVALID_API_KEY") {
    console.error("Invalid API key provided");
  } else if (error.code === "RATE_LIMIT_EXCEEDED") {
    console.error("Rate limit exceeded, retry after:", error.retryAfter);
  } else if (error.code === "VALIDATION_ERROR") {
    console.error("Validation error:", error.details);
  } else {
    console.error("Unexpected error:", error.message);
  }
}

ベストプラクティス

  • 1より良い抽出精度のために高品質な例を提供する
  • 2複数のドキュメントにはバッチ処理を使用する
  • 3API呼び出しを減らすために抽出結果をキャッシュする
  • 4適切なエラーハンドリングとリトライを実装する
  • 5APIキーには環境変数を使用する

始める準備はできましたか?

pipでLangExtractをインストールし、数分でテキストデータから構造化情報の抽出を開始できます。

npm install langextract