Langchain的学习心得--自定义工具(两种)

一、定义自定义工具

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

name(str),是必需的,并且在提供给代理的工具集中必须是唯一的
description(str),是可选的但建议的,因为代理使用它来确定工具的使用方式
return_direct(bool),默认为 False
args_schema(Pydantic BaseModel),是可选的但建议的,可以用于提供更多信息(例如,few-shot 示例)或用于验证预期参数。

# Import things that are needed generically
from langchain import LLMMathChain, SerpAPIWrapper
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, tool

llm = ChatOpenAI(temperature=0)

二、字符串输入和输出

最简单的工具接受单个查询字符串并返回字符串输出。如果您的工具函数需要多个参数,您可能需要跳到下面的StructuredTool 部分。有两种方法可以做到这一点:要么使用 Tool 数据类,要么通过子类化 BaseTool 类。
工具数据类:“Tool”数据类包装接受单个字符串输入并返回字符串输出的函数。

1.Tool dataclass

代码如下(示例):

# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
    Tool.from_function(
        func=search.run,
        name="Search",
        description="useful for when you need to answer questions about current events"
        # coroutine= ... <- you can specify an async method if desired as well
    ),
]

可以定义自定义“args_schema”来提供有关输入的更多信息

from pydantic import BaseModel, Field

class CalculatorInput(BaseModel):
    question: str = Field()

tools.append(
    Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="useful for when you need to answer questions about math",
        args_schema=CalculatorInput
        # coroutine= ... <- you can specify an async method if desired as well
    )
)
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

agent.run(
    "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)

2.Subclassing the BaseTool class

您也可以直接继承BaseTool。如果您想要对实例变量进行更多控制,或者想要将回调传播到嵌套链或其他工具,这非常有用。

from typing import Optional, Type

from langchain.callbacks.manager import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)


class CustomSearchTool(BaseTool):
    name = "custom_search"
    description = "useful for when you need to answer questions about current events"
	# 接受两个参数:query(类型为 str,表示查询的内容)和 run_manager(类型为 Optional[CallbackManagerForToolRun],可选参数,用于管理工具运行的回调管理器)。返回类型为 str。
    def _run(
        self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> str:
        """Use the tool."""
        return search.run(query)
    #接受两个参数:query(类型为 str)和 run_manager(类型为 Optional[AsyncCallbackManagerForToolRun],可选参数,用于异步操作的回调管理器)。返回类型为 str。抛出 NotImplementedError 异常,指明 CustomSearchTool 不支持异步操作。
    async def _arun(
        self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None
    ) -> str:
        ""
LangChain-Chatchat 0.3.0 是基于 LangChain 构建的聊天应用框架,其中可以集成各种 Agent 工具自定义其功能。通过自定义 agent 工具,您可以根据特定需求添加新的能力到您的 Chatchat 应用程序。 ### 自定义Agent工具的基本步骤: #### 1. 确定需求 首先明确您希望 agent 实现什么样的任务或服务,例如查询数据库、控制智能家居设备等。 #### 2. 创建一个新的Tool类 在 langchain 的 `tools` 文件夹下创建一个新文件,并编写 Tool 类。这个类需要继承 BaseTool 并实现 `_run()` 方法,在这里定义当此 tool 被触发时的具体操作逻辑。 ```python from chatchat.tools.base import BaseTool class MyCustomTool(BaseTool): def __init__(self, name="my_custom_tool", description="A custom tool for ..."): super().__init__() self.name = name self.description = description async def _run(self,*args,**kwargs): # Your logic here... ``` #### 3. 注册并加载工具 将新建好的tool注册进系统中去,在合适的位置引入该模块然后实例化它作为配置的一部分传递给agent. ```python # 导入刚才写的MyCustomTool from .custom_tools.my_custom_tool import MyCustomTool ... # 当初始化Chatchat的时候加入我们的新工具 chatchat_agent = ChattyAgent(tools=[MyCustomTool()]) ``` > 注意:实际项目结构可能会有所不同,以上代码仅作示意用途,请按照官方文档调整路径及语法细节。 完成上述流程之后重启应用程序即可开始测试新增加的功能是否正常工作了! 如果您正在寻找更详细的指南或遇到困难的地方,建议查阅langchain项目的GitHub页面以及社区资源获取更多帮助和支持信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值