google/langextract · 上手攻略
- 仓库:google/langextract
- 链接:https://github.com/google/langextract
- 分类:ai / llm-infra
- 作者:Jay
- 更新:2026-07-09
是什么
LangExtract 是 Google 推出的基于 LLM 的结构化信息抽取 Python 库。你给定一段自然语言文本 + 抽取规则(用 prompt 描述)+ 少量示例,LangExtract 就能按 schema 抽取出结构化结果,并精确定位每条抽取结果在原文中的位置,生成交互式 HTML 可视化。
核心定位:把非结构化文档变成带位置溯源的干净结构化数据,无需微调模型。
解决什么问题
- 信息抽取门槛高:传统NER需要标注数据 + 训练模型,周期长、迁移差。
- 闭卷抽取不可控:直接 prompt LLM 抽取出错位置不明,难以审核。
- 大量文本处理:处理书籍、报告等长文档时,"大海捞针"问题突出。
- 可视化审查难:抽了几百个实体,怎么快速检查对错?传统方案缺乏直观手段。
快速安装
pip 安装(推荐)
pip install langextract
开发模式(可改源码)
git clone https://github.com/google/langextract.git
cd langextract
pip install -e ".[dev]" # 含 linting 工具
pip install -e ".[test]" # 含 pytest
Docker 运行
docker build -t langextract .
docker run --rm -e LANGEXTRACT_API_KEY="your-api-key" langextract python your_script.py
依赖环境
- Python 3.x(建议 3.10+)
- 云端模型:需要 API Key(Gemini / OpenAI / Vertex AI)
- 本地模型:通过 Ollama,无需 API Key
核心用法
1. 三步完成抽取(最简示例)
import langextract as lx
# Step 1: 定义抽取 prompt
prompt = """\
Extract characters, emotions, and relationships in order of appearance.
Use exact text for extractions. Do not paraphrase or overlap entities.
Provide meaningful attributes for each entity to add context."""
# Step 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"}
),
]
)
]
# Step 3: 执行抽取
result = lx.extract(
text_or_documents="Lady Juliet gazed longingly at the stars, her heart aching for Romeo",
prompt_description=prompt,
examples=examples,
model_id="gemini-3.5-flash", # 推荐默认模型
)
2. API Key 配置
⚠️ 使用云端模型必须配置 API Key;本地 Ollama 不需要
方式一:环境变量(推荐)
export LANGEXTRACT_API_KEY="your-api-key-here"
方式二:.env 文件(生产推荐)
# .env
LANGEXTRACT_API_KEY=your-api-key-here
# .gitignore
echo ".env" >> .gitignore
方式三:Vertex AI(企业用户)
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gemini-3.5-flash",
language_model_params={
"vertexai": True,
"project": "your-project-id",
"location": "global"
}
)
3. 本地模型(Ollama)
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gemma2:2b", # Ollama 模型名
model_url="http://localhost:11434",
)
⚠️ Ollama 需提前在本地运行
ollama serve
4. 长文档处理
处理《Romeo and Juliet》全文时,LangExtract 通过多轮抽取(extraction_passes=3)+ 并行处理(max_workers=20)+ 小上下文窗口(max_char_buffer=1000)克服大海捞针问题:
result = lx.extract(
text_or_documents="https://www.gutenberg.org/files/1513/1513-0.txt",
prompt_description=prompt,
examples=examples,
model_id="gemini-3.5-flash",
extraction_passes=3, # 多轮抽取提升召回率
max_workers=20, # 并行处理
max_char_buffer=1000, # 小窗口提高准确率
)
5. 生成交互式 HTML 可视化
# 保存为 JSONL
lx.io.save_annotated_documents(
[result],
output_name="extraction_results.jsonl",
output_dir="."
)
# 生成交互式 HTML
html_content = lx.visualize("extraction_results.jsonl")
with open("visualization.html", "w") as f:
f.write(html_content)
生成的 HTML 可在浏览器中直观查看所有抽取实体的原文位置高亮,支持大量结果。
6. OpenAI 模型支持
# 需要: pip install langextract[openai]
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gpt-4o", # 自动路由到 OpenAI provider
)
7. 结构化输出 Schema(高级)
Gemini 和 OpenAI 支持 output_schema,可对属性类型做 enum 等强约束:
# 见文档:https://github.com/google/langextract/blob/main/docs/examples/output_schema.md
典型适用场景
- 医疗记录结构化:从临床笔记中抽取诊断、用药、检验结果,用于二次分析或 EHR 系统集成
- 法律文档摘要:从判决书、合同中抽取关键条款、日期、金额
- 新闻媒体分析:从新闻文章中抽取人物、事件、机构,进行舆情分析
- 学术文献挖掘:从论文中抽取方法、数据集、实验结果,构建知识图谱
- 客服记录分析:从工单文本中抽取问题类型、情绪、解决方案,辅助 BI 分析
- 简历/JD 解析:从简历和职位描述中抽取技能、工作经历,进行匹配
坑与注意
- 示例质量决定效果:示例中的
extraction_text应尽量使用原文verbatim,且按出现顺序排列;否则会有 prompt alignment 警告 - Grounding 问题:LLM 可能从示例而非输入文本中"记忆"抽取——用
char_interval = None过滤这些不可溯源结果 - Gemini 模型生命周期:Gemini 模型有退役日期,大规模生产使用建议关注 官方 model version 文档
- 速率限制:gemini-3.5-flash 有速率限制,大规模抽取建议升级到付费 tier 或使用 Vertex AI Batch API
- 开源模型效果:本地 Ollama 模型(如 gemma2:2b)精度明显低于 Gemini/ GPT,生产环境建议用云端模型
- 抽取结果非事实保证:LLM 可能"脑补"信息(用 world knowledge 而非文本证据),需通过可视化审查过滤
char_interval = None的结果 - batch API:OpenAI Batch API 需要 prompt 数超过阈值(默认50)才触发,文档中有说明
与同类对比
| 工具 | 定位 | 精度 | 溯源能力 | 本地支持 | 上手难度 |
|---|---|---|---|---|---|
| LangExtract | LLM 驱动结构化抽取 | ⭐⭐⭐⭐ 高 | ⭐⭐⭐⭐⭐ 字符级 | Ollama | ⭐⭐⭐ 中 |
| spaCy(规则+NER) | 传统 NLP | ⭐⭐⭐ 中 | ⭐⭐ 实体级 | 完整 | ⭐⭐⭐ 中 |
| DuckDuckBot | LLM 数据抽取 | ⭐⭐⭐ 中 | ⭐⭐ 有限 | 无 | ⭐⭐ 易 |
| Graphlit | 商业抽取平台 | ⭐⭐⭐ 中 | ⭐⭐ 有限 | 无 | ⭐⭐ 易 |
| LlamaIndex Reader | 数据摄取 | ⭐⭐⭐ 中 | ⭐⭐⭐ 有限 | 完整 | ⭐⭐⭐ 中 |
核心差异:LangExtract 是唯一同时做到"prompt 驱动零训练"、"字符级溯源"、"交互式可视化"、"多模型支持"的学术级开源方案。相比传统 NER,无需标注数据;相比通用 LLM 调用,输出格式更可控且可审查。
一句话结论
需要从非结构化文档中抽取干净的结构化数据,且要能审查每一条结果来自哪句话?LangExtract 一步到位。