7.LangChain自定义工具调用
自定义工具
在构建代理时,您需要为其提供一个 Tool 列表,以便代理可以使用这些工具。除了实际调用的函数之外,Tool 由几个组件组成:
属性 | 类型 | 描述 |
---|---|---|
name | str | 在提供给LLM或代理的工具集中必须是唯一的。 |
description | str | 描述工具的功能。LLM或代理将使用此描述作为上下文。 |
args_schema | Pydantic BaseModel | 可选但建议,可用于提供更多信息(例如,few-shot 示例)或验证预期参数。 |
return_direct | boolean | 仅对代理相关。当为True时,在调用给定工具后,代理将停止并将结果直接返回给用户。 |
LangChain 提供了三种创建工具的方式:
- 使用
@tool
装饰器 – 定义自定义工具的最简单方式。 - 使用
StructuredTool.from_function
类方法 – 这类似于@tool
装饰器,但允许更多配置和同步和异步实现的规范。 - 通过子类化
BaseTool
– 这是最灵活的方法,它提供了最大程度的控制,但需要更多的工作量和代码。
@tool
或 StructuredTool.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