LangExtract 是一个 Python 库,它使用 LLM 根据用户定义的指令从非结构化文本文档中提取结构化信息。它处理临床记录或报告等材料,识别和组织关键细节,同时确保提取的数据与源文本相对应。
**注意:**使用像 Gemini 这样的云托管模型需要 API 密钥。请参阅 API 密钥设置 部分,了解如何获取和配置密钥。
只需几行代码即可提取结构化信息。
首先,创建一个提示,清晰地描述您想要提取的内容。然后,提供一个高质量的示例来指导模型。
import langextract as lx
import textwrap
# 1. Define the prompt and extraction rules
prompt = textwrap.dedent("""\
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.""")
# 2. Provide a high-quality example to guide the model
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"}
),
]
)
]
将输入文本和提示材料提供给 lx.extract
函数。
# The input text to be processed
input_text = "Lady Juliet gazed longingly at the stars, her heart aching for Romeo"
# Run the extraction
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gemini-2.5-flash",
)
模型选择:推荐默认使用
gemini-2.5-flash
,它在速度、成本和质量之间实现了极佳的平衡。对于需要深度推理的高度复杂任务,gemini-2.5-pro
可能能够提供更佳的结果。对于大规模或生产环境,建议使用 Tier 2 Gemini 配额来提高吞吐量并避免速率限制。详情请参阅 速率限制文档。模型生命周期:请注意,Gemini 模型具有明确的生命周期和退役日期。用户应查阅 官方模型版本文档,以了解最新的稳定版本和旧版本。
提取结果可以保存为 .jsonl
文件,这是一种处理语言模型数据的常用格式。LangExtract 可以根据此文件生成交互式 HTML 可视化效果,以便在上下文中查看实体。
# Save the results to a JSONL file
lx.io.save_annotated_documents([result], output_name="extraction_results.jsonl", output_dir=".")
# Generate the visualization from the file
html_content = lx.visualize("extraction_results.jsonl")
with open("visualization.html", "w") as f:
if hasattr(html_content, 'data'):
f.write(html_content.data) # For Jupyter/Colab
else:
f.write(html_content)
这将创建一个动画和交互式 HTML 文件:
关于 LLM 知识利用的说明: 本示例演示了如何紧跟文本证据的提取——提取对朱丽叶夫人情绪状态的“渴望”,并从“渴望地凝视星空”中识别出“渴望”。该任务可以修改,以生成更多基于 LLM 世界知识的属性(例如,添加“identity”:“Capulet family daughter”或“literary_context”:“tragic heroine”)。文本证据和知识推理之间的平衡由您的提示说明和示例属性控制。
对于更大的文本,您可以直接从 URL 处理整个文档,并进行并行处理和增强敏感度:
# Process Romeo & Juliet directly from Project Gutenberg
result = lx.extract(
text_or_documents="https://www.gutenberg.org/files/1513/1513-0.txt",
prompt_description=prompt,
examples=examples,
model_id="gemini-2.5-flash",
extraction_passes=3, # Improves recall through multiple passes
max_workers=20, # Parallel processing for speed
max_char_buffer=1000 # Smaller contexts for better accuracy
)
这种方法可以从整部小说中提取数百个实体,同时保持较高的准确率。交互式可视化功能可以无缝处理大型结果集,让您轻松探索输出 JSONL 文件中的数百个实体。查看完整的《罗密欧与朱丽叶》提取示例 →,了解详细结果和性能洞察。
pip install langextract
建议大多数用户使用。对于隔离环境,请考虑使用虚拟环境:
python -m venv langextract_env
source langextract_env/bin/activate # On Windows: langextract_env\Scripts\activate
pip install langextract
LangExtract 使用现代 Python 打包工具 pyproject.toml
进行依赖管理:
使用 -e
安装会将软件包置于开发模式,让您无需重新安装即可修改代码。
git clone https://github.com/google/langextract.git
cd langextract
# For basic installation:
pip install -e .
# For development (includes linting tools):
pip install -e ".[dev]"
# For testing (includes pytest):
pip install -e ".[test]"
docker build -t langextract .
docker run --rm -e LANGEXTRACT_API_KEY="your-api-key" langextract python your_script.py
当将 LangExtract 与云托管模型(例如 Gemini 或 OpenAI)一起使用时,您需要设置 API 密钥。设备上的模型不需要 API 密钥。对于使用本地 LLM 的开发者,LangExtract 提供对 Ollama 的内置支持,并且可以通过更新推理端点扩展到其他第三方 API。
Get API keys from:
选项 1: 环境变量
export LANGEXTRACT_API_KEY="your-api-key-here"
选项 2:.env 文件(推荐)
Add your API key to a .env
file:
# Add API key to .env file
cat >> .env << 'EOF'
LANGEXTRACT_API_KEY=your-api-key-here
EOF
# Keep your API key secure
echo '.env' >> .gitignore
In your Python code:
import langextract as lx
result = lx.extract(
text_or_documents=input_text,
prompt_description="Extract information...",
examples=[...],
model_id="gemini-2.5-flash"
)
选项 3:直接提供API密钥(不建议用于生产环境)
您也可以直接在代码中提供 API 密钥,但不建议用于生产环境:
result = lx.extract(
text_or_documents=input_text,
prompt_description="Extract information...",
examples=[...],
model_id="gemini-2.5-flash",
api_key="your-api-key-here" # Only use this for testing/development
)
LangExtract 通过轻量级插件系统支持自定义 LLM 提供程序。您可以添加对新模型的支持,而无需更改核心代码。
请参阅 提供程序系统文档 中的详细指南,了解如何:
@registry.register(...)
注册提供程序get_schema_class()
提供结构化输出的架构create_model(...)
与工厂集成LangExtract 支持 OpenAI 模型(需要可选依赖项:pip install langextract[openai]
):
import langextract as lx
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gpt-4o", # Automatically selects OpenAI provider
api_key=os.environ.get('OPENAI_API_KEY'),
fence_output=True,
use_schema_constraints=False
)
注意:OpenAI 模型需要 fence_output=True
和 use_schema_constraints=False
,因为 LangExtract 尚未实现 OpenAI 的模式约束。
LangExtract 支持使用 Ollama 进行本地推理,允许您无需 API 密钥即可运行模型:
import langextract as lx
result = lx.extract(
text_or_documents=input_text,
prompt_description=prompt,
examples=examples,
model_id="gemma2:2b", # Automatically selects Ollama provider
model_url="http://localhost:11434",
fence_output=False,
use_schema_constraints=False
)
快速设置: 从 ollama.com 安装 Ollama,运行 ollama pull gemma2:2b
,然后运行 ollama serve
。
有关详细的安装、Docker 设置和示例,请参阅 examples/ollama/
。
更多 LangExtract 实际应用示例:
LangExtract 可以直接从 URL 处理完整文档。此示例演示了如何从古腾堡计划 (Project Gutenberg) 的《罗密欧与朱丽叶》全文(147,843 个字符)中提取文本,展示了并行处理、顺序提取过程以及针对长文档处理的性能优化。
免责声明: 本演示仅用于说明 LangExtract 的基本功能。它不代表成品或已获批准的产品,不用于诊断或建议任何疾病或病症的治疗,也不应用于医疗建议。
LangExtract 擅长从临床文本中提取结构化医疗信息。这些示例演示了基本实体识别(药物名称、剂量、给药途径)和关系提取(将药物与其属性关联),展现了 LangExtract 在医疗保健应用中的有效性。
探索 RadExtract,这是一个在 HuggingFace Spaces 上实时互动的演示,展示了 LangExtract 如何自动构建放射学报告。无需任何设置,即可直接在浏览器中试用。
欢迎贡献!请参阅 CONTRIBUTING.md 开始开发、测试和拉取请求。提交补丁之前,您必须签署 贡献者许可协议。
从源码本地运行测试:
# 克隆代码库
git clone https://github.com/google/langextract.git
cd langextract
# 安装测试依赖项
pip install -e ".[test]"
# 运行所有测试
pytest 测试
或者使用 tox 在本地复现完整的持续集成矩阵:
tox # 在 Python 3.10 和 3.11 上运行 pylint + pytest
如果您已在本地安装 Ollama,则可以运行集成测试:
# 测试 Ollama 集成(需要 Ollama 运行 gemma2:2b 模型)
tox -e ollama-integration
此测试将自动检测 Ollama 是否可用并运行真实的推理测试。
本项目使用自动格式化工具来保持一致的代码风格:
# 自动格式化所有代码
./autoformat.sh
# 或单独运行格式化程序
isort langextract tests --profile google --line-length 80
pyink langextract tests --config pyproject.toml
用于自动格式化检查:
pre-commit install # 一次性设置
pre-commit run --all-files # 手动运行
提交 PR 前运行代码检查:
pylint --rcfile=.pylintrc langextract tests
查看完整的开发指南,请参阅 CONTRIBUTING.md。
本产品并非 Google 官方支持的产品。如果您在生产或出版物中使用
LangExtract,请注明来源并
注明使用。使用需遵守 Apache 2.0 许可证。
对于健康相关的应用程序,使用 LangExtract 还需遵守
健康 AI 开发者基金会使用条款。