为语言模型和聊天模型添加即时工具调用功能

在现代人工智能应用中,结合语言模型(LLM)和聊天模型的即时工具调用功能变得越来越重要。尽管有些模型已经经过微调以支持工具调用,并提供专门的API,但在某些情况下,我们需要为不支持此功能的模型实现工具调用。本指南将演示如何通过编写提示的方式,为一个聊天模型添加工具调用功能。

技术背景介绍

随着AI技术的发展,越来越多的应用需要语言模型能够直接调用外部工具,以执行计算、查询数据库或调用其他API等任务。一些模型已经针对这种需求进行了微调,但对于那些没有原生支持工具调用的模型,我们可以通过设计合理的提示(prompt)来实现这种能力。

核心原理解析

通过让模型理解我们将提供的工具和相应参数,我们可以设计提示来指示模型如何生成适当的工具调用请求。该请求通常采用JSON格式,包含工具名称和参数。

代码实现演示

以下是具体的代码实现步骤:

环境准备

首先,安装所需的Python包:

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

创建工具

我们将创建两个简单的工具:加法和乘法。

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]

编写提示

创建一个系统提示来描述工具并期望以JSON格式输出。

from langchain_core.output_parsers import JsonOutputParser
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}")]
)

调用工具并处理输出

解析模型输出并实际调用工具。

from langchain_core.runnables import RunnablePassthrough

chain = (
    prompt | model | JsonOutputParser() | RunnablePassthrough.assign(output=invoke_tool)
)
result = chain.invoke({"input": "what's thirteen times 4.14137281"})
print(result)

工具执行函数

创建函数以执行模型请求的工具。

from typing import Any, Dict, Optional, TypedDict

class ToolCallRequest(TypedDict):
    name: str
    arguments: Dict[str, Any]

def invoke_tool(
    tool_call_request: ToolCallRequest, config: Optional[RunnableConfig] = None
):
    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"], config=config)

应用场景分析

这种实现方式非常适合于快速原型开发,尤其是在开发阶段或资源有限的情况下。它允许开发人员在不需要微调模型的情况下,灵活地扩展模型的功能。

实践建议

  • 在设计提示时,尽量详细描述工具及其参数。
  • 对于复杂工具,考虑提供一些示例或使用少量镜头方法(few-shot learning)来指导模型。
  • 实现错误处理机制,例如捕获异常并重新触发模型以修正输出。

如果遇到问题欢迎在评论区交流。

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值