使用LangChain自定义tools的三种方式

LLM对外部工具的使用现在可谓其必备技能之一。当我们使用LangChain/LangGraph等框架去编排定制一些或简单或复杂的LLM应用时,自定义LLM在处理用户提问时需要用到的工具是一个非常常见的步骤,熟练掌握自定义工具的过程是很有必要的。由此,本篇博客将尽可能详细地介绍如何基于LangChain相关python库中提供的模块组件进行工具的自定义,一起来学习吧!

本篇博客内容将参考 LangChain 关于创建自定义工具的官方文档,并结合案例代码运行效果展示和较为详细的文字解释(这部分大概率有 ChatGPT 参与帮忙),帮助大家快速了解自定义工具的构建方式。

工具的组成部分

  • 名称 (name)(字符串):工具的名称,必需提供且唯一

  • 描述 (description)(字符串):工具的功能描述。可选但推荐使用,因为LLM和agent会把该描述作为context,以实现对工具的准确选择。

  • 参数模式 (args_schema)(Pydantic BaseModel):可选但推荐使用,可以用于提供更多信息(例如提供少量示例)或验证传入参数是否符合预期。

  • return_direct(布尔值):仅对agents生效。当该参数设置为 True,在agent调用给定工具后,将直接把结果返回给用户。

工具的三种创建方式

1. 基于函数

@tool 装饰器

通过函数创建工具是一个最简单直接高效的创建方式,只需通过一个简单的 @tool 装饰器就可以完成,且足以满足大部分场景需求,但若需要对工具进行更多配置,如同时指定同步和异步实现,则可使用StructuredTool.from_function 类方法进行实现。

默认情况下,@tool 装饰器使用函数名作为工具名,但可以通过传递一个字符串作为第一个参数来覆盖。此外,@tool 装饰器会将函数的文档字符串用作工具的描述,因此文档字符串是必须要提供的。

代码示例(无传入参数)

比如我们希望编排一个非常简单的LLM应用,可以基于调用外部api获取到的黄金数据(黄金现货、黄金期货等品种的最新价、开盘价、最高价、最低价等价格信息)进行相关问题的回答,那我们就需要把调用该api获取返回信息的步骤封装到一个函数中作为工具。

  1. 从 langchain_core.tools 导入 tool(pip install langchain-core
from langchain_core.tools import tool
import requests

url = "https://api.jisuapi.com/gold/shgold"
params = {
   
"appkey": "你的appkey"
}
  1. 用 @tool 装饰器 创建工具名为 get_current_gold_price 的函数(注意,函数的docstring,即工具的描述,是必须要提供的,否则会报错,因为装饰器中名为 parse_docstring 默认为 True,即@tool(parse_docstring=True),想了解更多可查看 API 文档)
@tool
def get_current_gold_price():
    """
    Retrieves the current gold price from the specified API.

    This function sends a GET request to the gold price API and returns
    the result. If the request is successful, it returns the gold price data.
    Otherwise, it returns an error message with the status code.

    Returns:
    - dict: A dictionary containing the result or an error message.
    """
    response = requests.get(url, params=params)

    # 检查响应状态并输出结果
    if response.status_code == 200:
        data = response.json()
        result = data["result"]
    else:
        result = ["Failed to retrieve data, status code: {}".format(response.status_code)]

    return {
   "messages": result}
  1. 打印出tool的名称、描述和参数
# 工具的名称
print(get_current_gold_price.name)
get_current_gold_price
# 工具的描述
print(get_current_gold_price.description)
Retrieves the current gold price from the specified API.

This function sends a GET request to the gold price API and returns
the result. If the request is successful, it returns the gold price data.
Otherwise, it returns an error message with the status code.

Returns:
- dict: A dictionary containing the result or an error message.
# 函数传入的参数信息,因为没有所以为空
print(get_current_gold_price.args)
{
   }
代码示例(有传入参数)

接下来我们看一个 官方文档 中提供的有传入参数,且传入参数需要符合一定规范的通过函数来自定义工具的例子。

  1. 导入所需模块并创建继承自 BaseModel 的子类 CalculatorInput

这里让ChatGPT介绍一下从 pydantic 第三方python库中导出的 BaseModelField

pydantic.BaseModelpydantic.Field

  • 这两者来自 pydantic 库,主要用于数据验证和结构化定义输入参数。通过使用 pydantic,你可以定义强类型的输入模型,并为每个字段添加描述、默认值、限制等。
  • BaseModel:这是 pydantic 中的一个基础类,允许我们创建验证数据输入的类。
  • Field:用于定义每个字段的属性和描述信息。在这段代码中,ab 是两个整数字段,并分别有自己的描述信息。
from langchain_core.tools import tool
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值