引导大型语言模型调用工具:构建多功能聊天助手

## 引言

在构建智能聊天助手时,工具调用能力是一个重要功能。尽管有些模型已经针对工具调用进行了微调,但本文介绍如何通过自定义提示,为不具备原生工具调用功能的聊天模型添加该能力。我们将通过一个具体例子来演示这一过程。

## 主要内容

### 1. 环境设置

首先,确保安装必要的包:

```bash
%pip install --upgrade --quiet langchain langchain-community

2. 创建工具

为了演示,我们将创建两个简单的数学工具:加法和乘法。

from langchain_core.tools import tool

@tool
def multiply(x: float, y: float) -> float:
    """Multiply two numbers together."""
    return x * y

@tool
def add(x: int, y: int) -> int:
    """Add two numbers."""
    return x + y

tools = [multiply, add]

3. 编写提示

我们将编写一个系统提示,告诉模型如何选择和调用工具。

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import render_text_description

rendered_tools = render_text_description(tools)

system_prompt = f"""\
You are an assistant that has access to the following set of tools. 
Here are the names and descriptions for each tool:

{rendered_tools}

Given the user input, return the name and input of the tool to use. 
Return your response as a JSON blob with 'name' and 'arguments' keys.
"""

prompt = ChatPromptTemplate.from_messages(
    [("system", system_prompt), ("user", "{input}")]
)

4. 调用工具并解析输出

通过以下逻辑,我们可以解析模型的输出并实际执行工具调用。

from langchain_core.output_parsers import JsonOutputParser

chain = prompt | model | JsonOutputParser()

def invoke_tool(tool_call_request):
    tool_name_to_tool = {tool.name: tool for tool in tools}
    name = tool_call_request["name"]
    requested_tool = tool_name_to_tool[name]
    return requested_tool.invoke(tool_call_request["arguments"])

result = chain.invoke({"input": "what's thirteen times 4.14137281"})
print(result)

常见问题和解决方案

  1. 输出不正确:可能需要提供示例来指导模型生成正确的请求格式。
  2. 工具调用出错:添加错误处理逻辑,捕获异常并提示模型纠正输出。

总结和进一步学习资源

通过上述方法,你可以为不支持原生工具调用的模型添加该功能。更多关于工具创建和模型集成的信息,可以参考以下资源:

参考资料

  1. LangChain Core 文档
  2. 工具调用API使用指南

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值