提升数据提取的精度:如何利用参考示例

93 阅读3分钟
# 提升数据提取的精度:如何利用参考示例

## 引言

在自然语言处理任务中,数据提取是一项复杂但至关重要的工作。为了提高提取结果的质量,引用参考示例是一个有效的策略。本指南将演示如何利用工具调用的少量示例来引导数据提取模型的行为。

## 主要内容

### 理解工具调用和参考示例

工具调用功能通常用于生成从文本中提取结构化信息。引用示例有助于改善提取质量,适用于多种模式,包括工具调用和JSON。

在LangChain中,`tool-call`属性用于结构化工具调用。这一节将展示如何通过构建聊天历史记录来创建参考示例:

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

### 构建提示模板

```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"),
        ("human", "{text}"),
    ]
)

from langchain_core.messages import (
    HumanMessage,
)

prompt.invoke(
    {"text": "this is some text", "examples": [HumanMessage(content="testing 1 2 3")]}
)

定义数据提取的模式和参考示例

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

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]

# Define examples
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)]),
    ),
]

创建提取器

选择支持工具调用功能的模型。以下是一些配置示例:

# 使用API代理服务提高访问稳定性
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()

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

# Without examples
for _ in range(5):
    text = "The solar system is large, but earth has only 1 moon."
    print(runnable.invoke({"text": text, "examples": []}))

# With examples
for _ in range(5):
    text = "The solar system is large, but earth has only 1 moon."
    print(runnable.invoke({"text": text, "examples": messages}))

常见问题和解决方案

  • 问题:模型输出不准确。

    • 解决方案:添加更多的参考示例并确保示例的质量。
  • 问题:API访问不稳定。

    • 解决方案:在某些地区,可以通过使用API代理服务提高访问的稳定性。

总结和进一步学习资源

使用参考示例可以显著提高数据提取的质量。通过调整参考示例的数量和质量,可以改善模型的性能。推荐进一步学习以下资源:

参考资料

  • LangChain官方文档
  • OpenAI API指南

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

---END---