GoogleはLangExtractを発表した。非構造化テキストから構造化情報を抽出するオープンソースの Python ライブラリで、Gemini などの LLM とユーザーのカスタム指示を使う。抽出結果はソーステキスト上の文字オフセットに紐づけられる。
- ソースグラウンディング: 抽出された全てのエンティティを、ソーステキスト内の文字オフセットにマッピングする。
- 構造化出力: 少数の例(few-shot)を渡し、Gemini などの Controlled Generation で構造を揃える。
- 長文向け処理: チャンキング、並列処理、複数回の抽出パスで長文から情報を拾う。
- インタラクティブな可視化: 抽出エンティティを文脈の中でレビューできる、自己完結型のインタラクティブHTMLを生成。
- LLMバックエンド: GoogleのGeminiファミリーやオープンソースのオンデバイスモデルなど、複数のLLMをサポート。
- ドメイン横断: LLMをファインチューニングせず、少数の例だけで抽出タスクを定義できる。
- 世界知識の利用: モデルが持つ世界知識で、抽出結果を補足できる。
リポジトリ:google/langextract
LangExtractの利用例
以下は、シェイクスピアの戯曲の一節から登場人物、感情、関係性を抽出するコード例。
まず、ライブラリをインストールする。
bash
pip install langextract次に、抽出タスクを定義して実行する。明確なプロンプトと質の高い few-shot 例でモデルの出力をガイドする。
python
import textwrap
import langextract as lx
# 1. 簡潔なプロンプトを定義
prompt = textwrap.dedent("""\
登場人物、感情、関係性を出現順に抽出してください。
抽出には正確なテキストを使用し、言い換えやエンティティの重複は避けてください。
各エンティティには文脈を追加するための意味のある属性を提供してください。""")
# 2. モデルをガイドするための高品質な例を提供
examples = [
lx.data.ExampleData(
text=(
"ROMEO. But soft! What light through yonder window breaks? It is"
" the east, and Juliet is the sun."
),
extractions=[
lx.data.Extraction(
extraction_class="character",
extraction_text="ROMEO",
attributes={"emotional_state": "wonder"},
),
lx.data.Extraction(
extraction_class="emotion",
extraction_text="But soft!",
attributes={"feeling": "gentle awe"},
),
lx.data.Extraction(
extraction_class="relationship",
extraction_text="Juliet is the sun",
attributes={"type": "metaphor"},
),
],
)]
# 3. 入力テキストに対して抽出を実行
input_text = (
"Lady Juliet gazed longingly at the stars, her heart aching for Romeo")
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gemini-2.5-pro",)抽出結果はJSONLファイルに保存し、インタラクティブなHTMLファイルとして可視化できる。
python
# 結果をJSONLファイルに保存
lx.io.save_annotated_documents([result], output_name="extraction_results.jsonl")
# ファイルからインタラクティブな可視化を生成
html_content = lx.visualize("extraction_results.jsonl")
with open("visualization.html", "w") as f:
f.write(html_content)