文章目录
一、定义自定义工具
当构建自己的代理时,您需要为其提供一组工具列表,代理可以使用这些工具。除了调用的实际函数之外,工具由几个组件组成:
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
) -&g