提升数据抽取质量:使用参考示例优化工具调用

64 阅读3分钟

引言

在处理自然语言处理任务时,数据抽取常常需要将非结构化文本中的信息结构化。通过为大语言模型(LLM)提供参考示例,可以显著提升抽取质量。这篇文章将介绍如何使用LangChain构建工具调用的几次示例,以引导抽取行为,并适用于类似应用场景。

主要内容

使用参考示例的概念

在进行数据抽取时,参考示例通过提供多个输入-输出对,帮助LLM更好地理解目标。LangChain中的工具调用特性允许我们通过定义一系列消息,创建类似对话的抽取过程:

  • HumanMessage:包含输入文本
  • AIMessage:包含模型的工具调用
  • ToolMessage:模型请求工具正确性的确认

LangChain工具调用的实现

首先,我们需要创建一个提示模板,这个模板包含一系列消息的占位符:

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

定义数据抽取模式

使用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]

定义和转换参考示例

参考示例包含输入文本和期望的工具调用输出:

from typing import Dict, List, TypedDict
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 = [{"id": str(uuid.uuid4()), "args": tool_call.dict(), "name": tool_call.__class__.__name__} for tool_call in example["tool_calls"]]
    messages.append(AIMessage(content="", tool_calls=tool_calls))
    messages.extend([ToolMessage(content="You have correctly called this tool.", tool_call_id=call["id"]) for call in tool_calls])
    return messages

examples = [
    ("The ocean is vast and blue.", Data(people=[])),
    ("Fiona traveled far from France to Spain.", Data(people=[Person(name="Fiona")]))
]

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

代码示例

下面是一个完整的代码示例:

from langchain_openai import ChatOpenAI

# 配置API密钥
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"

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

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

text = "The solar system is large, but earth has only 1 moon."
result = runnable.invoke({"text": text, "examples": messages})
print(result)

常见问题和解决方案

  • API访问问题:某些地区的开发者可能面临API访问限制,可以考虑使用API代理服务提高访问稳定性。
  • 模型输出不一致:确保示例格式与API要求的一致性,并使用结构化输出来提高精度。

总结和进一步学习资源

使用参考示例可显著改善数据抽取的精度。建议进一步阅读以下资源:

  • LangChain官方文档
  • OpenAI API指南
  • Pydantic文档

参考资料

  1. LangChain 官方文档
  2. OpenAI API 参考
  3. Pydantic 文档

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

---END---