LangExtract:基于LLM的信息抽取框架 学习笔记

Motivation

任务需求:在非标准的文本里面提取特定的字段(比如人物、时间、地点等等),以形成结构化的数据,如保存到 Excel 、数据库。

如果数据量较小,则人工就可以完成此项任务;

但如果数据量很大,则需要借助程序(使用规则匹配)来实现,但由于程序是固定写定的,只遵循设定好的规则,很容易由于不理解自然语言而得到错误答案。

Google 在 7 月 30 日开源的 LangExtract 正是为此而生------它利用 Gemini-family、OpenAI、乃至本地 Ollama 等多种 LLM,实现"按指令抽取+源文对齐+一键可视化"的完整闭环。

作者团队

Google ,发布于2025 年 7 月30日,持续更新ing。

Introduction

LangExtract是一个Python库,利用大型语言模型(LLMs),根据用户定义的指令从非结构化文本文档中提取结构化信息。它能处理临床笔记或报告等材料,识别并整理关键细节,同时确保提取的数据与源文本保持一致。

特点介绍

Precise Source Grounding

将每次的提取,映射到其在源文本中的具体位置,支持视觉高亮显示,便于追溯和验证。

Reliable Structured Outputs

通过 few-shot 和 Gemini 的 Controlled Generation,保证生成的结构化结果,严格遵循预定义的JSON Schema。

Optimized for Long Documents

通过优化的文本分块、并行处理和多轮提取策略,克服了大型文档提取中的"大海捞针"难题,从而提高召回率。

Interactive Visualization

即时生成一个独立的交互式HTML文件,以可视化和审查实体及其原始上下文,方便审核和错误分析。即便是千级实体亦可流畅浏览。

Flexible LLM Support

支持从 Google Gemini 系列等云端 LLM,到通过内置 Ollama 接口访问的本地开源模型。

Adaptable to Any Domai只需少量示例即可为任何领域定义提取任务。LangExtract 会适应需求,无需进行任何模型微调。

Leverages LLM World Knowledge

利用精确的提示词措辞和 Few-shot 示例来影响提取任务如何利用 LLM 知识。 推断信息的准确性及其对任务规范的遵守程度,取决于所选的 LLM、任务的复杂性、提示指令的清晰度以及提示示例的性质。

如何使用

环境配置

bash 复制代码
pip install langextract        # PyPI 安装
# 或者源码开发模式
git clone https://github.com/google/langextract.git
cd langextract && pip install -e ".[dev]"

Define Your Extraction Task

首先,创建一个prompt,可以清晰描述想要提取的内容。

然后,提供一个或若干个高质量的例子来引导模型。

python 复制代码
# 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"}
            ),
        ]
    )
]

Run the Extraction

将输入文本和提示材料提供给 lx.extract 函数。

python 复制代码
# 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,它在速度、成本和质量之间提供了出色的平衡。

Visualize the Results

提取结果可以保存为.jsonl文件,这是一种常用于处理语言模型数据的流行格式。

随后,LangExtract可以从该文件生成交互式HTML可视化界面,以便在上下文中查看实体。

python 复制代码
# 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文件:

相关推荐
柳安忆3 小时前
idea生成数据集调研
人工智能·笔记
AnySpaceOne3 小时前
笔记本电脑如何连接打印机?完整连接教程送上
学习·电脑
aramae3 小时前
详细分析平衡树--红黑树(万字长文/图文详解)
开发语言·数据结构·c++·笔记·算法
dxnb223 小时前
Datawhale25年10月组队学习:math for AI+Task2线性代数
人工智能·学习·线性代数
wanfeng_094 小时前
python爬虫学习
爬虫·python·学习
h7997104 小时前
go资深之路笔记(九)kafka浅析
笔记·golang·kafka
云小逸4 小时前
【Win32 多线程程序设计基础第六章笔记】
笔记
A9better4 小时前
嵌入式开发学习日志39——stm32之I2C总线物理层与常用术语
stm32·单片机·嵌入式硬件·学习
摇滚侠5 小时前
Spring Boot 3零基础教程,WEB 开发 默认的自动配置,笔记25
前端·spring boot·笔记