Python类工具方法在自定义CrewAI Agent调用时缺失self参数的问题
问题
我正在基于Python开发自定义AI Agent,该Agent依赖LangChain工具与PostgreSQL数据库交互。ToolWithConnection类负责初始化数据库连接,并定义了list_tables、tables_schema等工具方法,供CrewAI Agent执行各类任务。相关代码包含连接方法、ToolWithConnection类、CrewAIWrapper类及Chain配置。运行时调用list_tables工具出现错误:
I encountered an error while trying to use the tool. This was the error: ToolWithConnection.list_tables() missing 1 required positional argument: 'self'.
现提出两个问题:
- 调用
list_tables时为何会缺失self参数? - 如何正确将类的实例方法作为工具传递给Agent以避免该错误?
答案
1. 缺失self参数的原因
list_tables是ToolWithConnection类的实例方法,这类方法必须绑定到类的实例上才能被调用——self参数会自动传入当前实例对象。如果直接把ToolWithConnection.list_tables(类的未绑定方法)传给Agent,调用时没有实例对象作为self传入,就会触发缺失参数的错误。
本质是你传递的是类本身的方法,而非类实例的绑定方法,Python无法自动填充self参数。
2. 正确传递实例方法作为工具的方案
核心是确保传递的是绑定了类实例的方法,有三种常用实现方式:
方案一:直接传递实例的方法
先创建ToolWithConnection的实例,再将实例的list_tables方法传给Agent:
# 初始化ToolWithConnection实例(传入数据库连接参数) db_tool_instance = ToolWithConnection(db_host="xxx", db_user="xxx", db_pass="xxx") # 将实例的方法作为工具传入Agent agent = Agent( tools=[db_tool_instance.list_tables, db_tool_instance.tables_schema], # 其他Agent配置... )
方案二:用functools.partial绑定实例
如果需要延迟绑定或特殊场景,可使用functools.partial将实例与方法绑定:
from functools import partial # 初始化实例 db_tool_instance = ToolWithConnection(db_params) # 绑定实例到方法上 bound_list_tables = partial(db_tool_instance.list_tables) bound_tables_schema = partial(db_tool_instance.tables_schema) # 传递绑定后的方法给Agent agent = Agent( tools=[bound_list_tables, bound_tables_schema], # 其他配置... )
方案三:结合LangChain的@tool装饰器
如果基于LangChain定义工具,可在实例方法上直接使用@tool装饰器,确保方法被正确识别为绑定工具:
from langchain.tools import tool class ToolWithConnection: def __init__(self, db_params): self.db_conn = self._init_db_connection(db_params) @tool("list-database-tables") def list_tables(self): """工具描述:列出当前数据库中的所有表""" # 数据库查询逻辑 cursor = self.db_conn.cursor() cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';") return [row[0] for row in cursor.fetchall()] # 实例化后传递装饰后的方法 db_tool_instance = ToolWithConnection(db_params) agent = Agent(tools=[db_tool_instance.list_tables])
内容的提问来源于stack exchange,提问作者AndCh
相关产品推荐
相关产品推荐

