创建工具,继承BaseTool并且传递了BaseTool中不包含的参数 #25790
Replies: 2 comments 2 replies
-
To create a tool by inheriting from
Here is an example based on your provided code: from typing import Optional, Type, Dict, Any
from pydantic import BaseModel, Field
from langchain_core.tools import BaseTool
# Define the input schema
class CustomToolInput(BaseModel):
param1: str = Field(description="Description for param1")
param2: int = Field(description="Description for param2")
# Create a custom tool class by subclassing BaseTool
class DynamicToolBase(BaseTool):
"""
A base class for dynamically creating tools with customizable attributes.
"""
def __init__(self, name: str, description: str, return_direct: bool, args_schema: Type[BaseModel],
start_url: str, requests_type: str = 'GET', headers: dict = {}):
super().__init__(
name=name,
description=description
)
self.name = name
self.description = description
self.return_direct = return_direct
self.args_schema = args_schema
self.requests_type = requests_type.lower()
self.start_url = start_url
self.headers = headers
def _run(self, *args, **kwargs) -> Dict[str, Any]:
if getattr(server_response, self.requests_type, None) is None:
raise Exception('请求方式异常')
key_dict = self.get_requests_parameter(kwargs)
return getattr(server_response, self.requests_type)(**key_dict)
async def _arun(self, *args, **kwargs) -> Dict[str, Any]:
if getattr(server_request_util, self.requests_type, None) is None:
raise Exception('请求方式异常')
key_dict = self.get_requests_parameter(kwargs)
return await getattr(server_request_util, self.requests_type)(**key_dict)
def get_requests_parameter(self, *args, **kwargs) -> Dict[str, Any]:
key_dict = {'body': {}, 'params': {}, 'json': {}, 'timeout': 20, 'headers': self.headers, 'url': self.start_url}
for key, value in kwargs.items():
key_cut = key.split('_')
if key_cut[0] in key_dict:
key_dict[key_cut[0]]['_'.join(key_cut[1:])] = value
key_dict = {k: v for k, v in key_dict.items() if v}
if 'json' in key_dict:
key_dict['json_data'] = key_dict['json']
del key_dict['json']
return key_dict
# Instantiate and use the custom tool
custom_tool = DynamicToolBase(
name="CustomTool",
description="A custom tool for demonstration",
return_direct=True,
args_schema=CustomToolInput,
start_url="http://example.com",
requests_type="GET",
headers={"Authorization": "Bearer token"}
)
print(custom_tool.name)
print(custom_tool.description)
print(custom_tool.args_schema)
print(custom_tool.return_direct) This example demonstrates how to create a custom tool by inheriting from For more detailed examples and tests, you can refer to the LangChain documentation and codebase [1][2][3][4]. |
Beta Was this translation helpful? Give feedback.
-
class ToolConfig(BaseModel): class DynamicToolBase(BaseTool):
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
File "D:\code\agent_platform_backend\langflow\utils\requests_tool_util.py", line 30, in init
self.requests_type = requests_type.lower()
KeyboardInterrupt
System Info
langchain==0.2.9
python==3.10.1
Beta Was this translation helpful? Give feedback.
All reactions