使用LangChain Agents调用API时遇AttributeError问题求助
解决LangChain Agents中AttributeError: 'tuple' object has no attribute 'is_single_input'问题
问题场景
尝试通过LangChain Agents调用API处理文档并获取问题答案时,触发以下错误:
AttributeError Traceback (most recent call last) <ipython-input-3-dea540cbc5b0> in <cell line: 28>() 26 27 # Step 4: Initialize the Agent ---> 28 agent = initialize_agent(tool, llm) 29 30 # Step 5: Use the Agent 3 frames /usr/local/lib/python3.10/dist-packages/langchain/agents/utils.py in validate_tools_single_input(class_name, tools) 7 """Validate tools for single input.""" 8 for tool in tools: ----> 9 if not tool.is_single_input: 10 raise ValueError( 11 f"{class_name} does not support multi-input tool {tool.name}." AttributeError: 'tuple' object has no attribute 'is_single_input'
原代码如下:
from langchain.tools import StructuredTool from langchain.agents import initialize_agent from langchain.llms import OpenAI import requests # Step 1: 实现API函数或类 def process_document(document): # 使用API逻辑处理文档 url = 'api' data = {'file': open(document, 'rb')} response = requests.post(url, auth=requests.auth.HTTPBasicAuth('dfg', ''), files=data) return response # Step 2: 创建Tool tool = StructuredTool.from_function(process_document,description="Process the document using the API") # Step 3: 初始化语言模型 llm = OpenAI(temperature=0, model_name="text-davinci-003", openai_api_key="key") # Step 4: 初始化Agent agent = initialize_agent(tool, llm) # Step 5: 使用Agent document = "" # 提供待处理的文档 result = agent.process(document) # 通过Agent和API处理文档 question = "What is Registration number and registration date?" # 提供关于处理结果的问题 answer = agent.generate(question) # 使用Agent生成问题答案
错误原因
- initialize_agent参数格式错误:该函数的第一个参数要求传入工具列表(list),但代码中直接传入了单个工具对象,导致内部遍历工具时误将其识别为tuple类型,触发属性错误。
- Agent调用方法错误:代码中使用的
agent.process()和agent.generate()不是LangChain Agents的标准调用方式,无法正常触发Agent逻辑。 - API返回值未处理:
process_document函数直接返回requests响应对象,Agent无法直接解析该对象内容用于后续问答。
解决方案及修正代码
修正要点:
- 将单个工具包装为列表传入
initialize_agent - 使用
agent.invoke()(或agent.run())作为标准调用方法 - 处理API响应,返回可被LLM解析的文本/结构化数据
- 添加文档路径的有效性检查(可选)
修正后的完整代码:
from langchain.tools import StructuredTool from langchain.agents import initialize_agent, AgentType from langchain.llms import OpenAI import requests # Step 1: 实现API函数,处理并返回可解析的结果 def process_document(document_path): # 检查文档路径是否为空 if not document_path: return "Error: Document path is empty." try: url = 'your_api_endpoint_here' # 替换为实际API地址 with open(document_path, 'rb') as file: data = {'file': file} response = requests.post( url, auth=requests.auth.HTTPBasicAuth('your_username', 'your_password'), # 替换为实际认证信息 files=data ) response.raise_for_status() # 抛出HTTP错误 # 假设API返回JSON格式结果,根据实际情况调整(如response.text) return response.json() except Exception as e: return f"Error processing document: {str(e)}" # Step 2: 创建Tool并包装为列表 tool = StructuredTool.from_function( func=process_document, description="Process the document using the specified API, returns the processed result." ) tools = [tool] # Step 3: 初始化语言模型 llm = OpenAI( temperature=0, model_name="text-davinci-003", openai_api_key="your_openai_api_key" # 替换为实际API密钥 ) # Step 4: 初始化Agent,指定Agent类型(可选,推荐明确指定) agent = initialize_agent( tools=tools, llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, # 根据需求选择合适的Agent类型 verbose=True # 开启日志,便于调试 ) # Step 5: 使用Agent处理文档并回答问题 document_path = "path/to/your/document.pdf" # 替换为实际文档路径 # 先处理文档,再提问(或合并为一个查询让Agent自动处理) query = f"First process this document: {document_path}. Then answer: What is Registration number and registration date?" result = agent.invoke(query) print("Answer:", result['output'])
额外注意事项
- 确保LangChain版本与代码兼容,若使用v0.1+版本,部分API可能有调整,可参考官方文档适配
- 替换代码中的API地址、认证信息、文档路径、OpenAI密钥为实际有效值
- 根据API返回格式调整
process_document函数的返回内容(如JSON、文本等),确保LLM能正确解析
内容的提问来源于stack exchange,提问作者nidhisharma
相关产品推荐
相关产品推荐

