7-langchain自定义工具调用

自定义工具

在构建代理时,您需要为其提供一个 Tool 列表,以便代理可以使用这些工具。除了实际调用的函数之外,Tool 由几个组件组成:

属性 类型 描述
name str 在提供给LLM或代理的工具集中必须是唯一的。
description str 描述工具的功能。LLM或代理将使用此描述作为上下文。
args_schema Pydantic BaseModel 可选但建议,可用于提供更多信息(例如,few-shot 示例)或验证预期参数。
return_direct boolean 仅对代理相关。当为True时,在调用给定工具后,代理将停止并将结果直接返回给用户。

LangChain 提供了三种创建工具的方式:

  1. 使用 @tool 装饰器 – 定义自定义工具的最简单方式。
  2. 使用 StructuredTool.from_function 类方法 – 这类似于 @tool 装饰器,但允许更多配置和同步和异步实现的规范。
  3. 通过子类化 BaseTool – 这是最灵活的方法,它提供了最大程度的控制,但需要更多的工作量和代码。

@toolStructuredTool.from_function 类方法对于大多数用例应该足够了。提示:如果工具具有精心选择的名称、描述和 JSON 模式,模型的性能会更好。

from langchain_core.tools import tool

@tool
async def multiply(a:int, b:int) -> int:
    """两个数相乘"""
    return a * b


print(multiply.name)
print(multiply.description)
print(multiply.args)

# multiply
# 两个数相乘
# {'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}
from langchain_core.tools import StructuredTool
import asyncio
from pydantic import BaseModel, Field


class CalculatorInput(BaseModel):
    a: int = Field(description="first num")
    b: int = Field(description="second num")

def multiply(a: int, b: int) -> int:
    """两个数相乘"""
    return a * b


async def a_add(a: int, b: int
### 如何在LangChain中创建或使用自定义工具LangChain框架下,创建自定义工具有助于增强智能代理的能力并满足特定需求。以下是关于如何实现这一目标的具体说明。 #### 创建自定义工具的核心要素 每个自定义工具通常由以下几个部分组成[^1]: - **名称**:用于唯一标识该工具- **描述**:清晰地解释工具的作用及其适用范围。 - **函数逻辑**:这是工具的主要执行体,定义了具体的行为。 - **参数验证**:确保输入的数据符合预期格式和约束条件。 下面是一个简单的例子展示如何定义这样一个基本的自定义工具: ```python from langchain.agents import Tool from typing import Any, Dict def custom_function(input_data: str) -> str: """A simple function that reverses the input string.""" return input_data[::-1] custom_tool = Tool( name="StringReverser", func=custom_function, description="This tool takes a string as input and returns it reversed." ) ``` 上述代码片段展示了如何通过`Tool`类来封装一个反转字符串的小型实用程序作为自定义工具。 #### 集成更复杂的业务逻辑 当需要引入更加复杂的计算或者外部API调用时,则可以通过RunnableLambda 或者 @chain装饰器等方式完成更为精细的操作[^2]。例如: ```python from langchain.schema.runnable import RunnableLambda complex_logic_tool = RunnableLambda(custom_complex_function) @chain def custom_complex_function(data: Dict[str, Any]) -> Dict[str, Any]: processed_result = some_external_api_call(data["input"]) return {"output": processed_result} ``` 这里演示的是怎样把较为繁琐的任务打包进可重用的形式里去,并且保持良好的结构化设计模式。 #### 参数校验的重要性 为了提高系统的健壮性和用户体验,在构建这些工具的时候应该考虑加入必要的参数检验机制。这一步骤可以帮助提前发现错误从而减少后期维护成本。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值