Agent 与工具调用2738 字

LangChain自定义工具调用

·全库 428 / 611

《LangChain自定义工具调用》共 0.3 万字,通篇围绕 LangChain、prompt、微调、工具调用 展开,归在「Agent 与工具调用」这一层。

覆盖LangChainprompt微调工具调用上下文安全

适合要让 AI 真的去干活、不只是陪人聊天的人

目录骨架(7 节)
  1. 自定义工具
  2. 调用内置工具包和拓展工具
  3. @tool 装饰器
  4. StructuredTool
  5. 处理工具错误
  6. 自定义默认工具
  7. 如何使用内置工具包

示例代码

注:将ppt后缀名改为zip后解压

python版本:3.12.4

自定义工具

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

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

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

  1. 使用@tool装饰器 -- 定义自定义工具的最简单方式。
  2. 使用StructuredTool.from_function 类方法 -- 这类似于@tool装饰器,但允许更多配置和同步和异步实现的规范。
  3. 通过子类化BaseTool -- 这是最灵活的方法,它提供了最大程度的控制,但需要更多的工作量和代码。 @tool或StructuredTool.from_function类方法对于大多数用例应该足够了。 提示 如果工具具有精心选择的名称、描述和 JSON 模式,模型的性能会更好。

@tool 装饰器

这个@tool装饰器是定义自定义工具的最简单方式。该装饰器默认使用函数名称作为工具名称,但可以通过传递字符串作为第一个参数来覆盖。此外,装饰器将使用函数的文档字符串作为工具的描述 - 因此必须提供文档字符串。

#示例:tools_decorator.py
from langchain_core.tools import tool
@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b
# 让我们检查与该工具关联的一些属性。
print(multiply.name)
print(multiply.description)
print(multiply.args)
multiply
multiply(a: int, b: int) -> int - Multiply two numbers.
{'a': {'title': 'A', 'type': 'integer'}, 'b': {'title': 'B', 'type': 'integer'}}

或者创建一个异步实现,如下所示:

#示例:tools_async.py
from langchain_core.tools import tool
@tool
async def amultiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b

您还可以通过将它们传递给工具装饰器来自定义工具名称和 JSON 参数。

from pydantic import BaseModel, Field
class CalculatorInput(BaseModel):
    a: int = Field(description="first number")
    b: int = Field(description="second number")
@tool("multiplication-tool", args_schema=CalculatorInput, return_direct=True)
def multiply(a: int, b: int) -> int:
    """Multiply two numbers."""
    return a * b
# 让我们检查与该工具关联的一些属性。
print(multiply.name)
print(multiply.description)
print(multiply.args)
print(multiply.return_direct)
multiplication-tool
multiplication-tool(a: int, b: int) -> int - Multiply two numbers.
{'a': {'title': 'A', 'description': 'first number', 'type': 'integer'}, 'b': {'title': 'B', 'description': 'second number', 'type': 'integer'}}
True

StructuredTool

StructuredTool.from_function 类方法提供了比@tool装饰器更多的可配置性,而无需太多额外的代码。

from langchain_core.tools import StructuredTool
import asyncio

资料里没有你的场景?

把你手上的数据和想解决的那个环节发上来,我们按具体情况回,不复述方法论。

发布需求