使用ChatOllama调用函数时出现'NoneType'不可迭代错误求助
问题定位与解决方案
可能的报错根源
代码触发'NoneType' object is not iterable错误,大概率来自以下几个点:
- 未校验
messages参数合法性:调用时若传入的messages为None,遍历message in messages时直接报错。 - AgentExecutor未关联记忆组件:代码中声明了
memory = self.memory但未传入AgentExecutor,导致MessagesPlaceholder("chat_history")无法获取有效历史数据,内部处理时触发None迭代错误。 - ainvoke输入格式错误:
create_openai_functions_agent的输入不需要messages键,传入格式不符合Agent预期,导致内部解析失败返回异常。 - 工具绑定不完整:部分场景下需显式为ChatOllama绑定工具,避免函数调用逻辑异常。
代码修改方案
1. 增加参数合法性校验
在函数开头先检查messages是否为有效列表:
async def get_response(self, messages, model): try: # 新增:校验messages参数 if not isinstance(messages, list) or len(messages) == 0: logging.error("Invalid messages input: must be non-empty list") return "Error: Invalid input messages." memory = self.memory llm = ChatOllama(model=model) # ... 后续代码
2. 关联记忆到AgentExecutor
初始化AgentExecutor时传入memory参数:
agent_executor = AgentExecutor(agent=agent, tools=self.tools, memory=memory)
3. 修正ainvoke的输入格式
create_openai_functions_agent的输入只需要input和chat_history(如果有),不需要messages键,调整输入构造逻辑:
# 提取用户输入(确保messages非空后再执行) user_input = next((msg["content"] for msg in messages if msg["role"] == "user"), "") # 构造正确的输入:chat_history是除当前用户输入外的历史消息 chat_history = [msg for msg in messages if msg["role"] != "user"] formatted_input = { "input": user_input, "chat_history": chat_history } response = await agent_executor.ainvoke(formatted_input)
4. 显式绑定工具(可选但推荐)
显式绑定工具可避免潜在逻辑异常:
llm = ChatOllama(model=model).bind_tools(self.tools)
完整修改后的代码片段
async def get_response(self, messages, model): try: # 校验messages参数合法性 if not isinstance(messages, list) or len(messages) == 0: logging.error("Invalid messages input: must be non-empty list") return "Error: Invalid input messages." memory = self.memory # 显式绑定工具 llm = ChatOllama(model=model).bind_tools(self.tools) config = {"configurable": {"thread_id": "abc123"}} prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful assistant"), MessagesPlaceholder("chat_history", optional=True), ("user", "{input}"), MessagesPlaceholder("agent_scratchpad"), ] ) agent = create_openai_functions_agent(llm=llm, tools=self.tools, prompt=prompt) # 关联memory到AgentExecutor agent_executor = AgentExecutor(agent=agent, tools=self.tools, memory=memory) # 提取用户输入和历史消息 user_input = next((msg["content"] for msg in messages if msg["role"] == "user"), "") chat_history = [msg for msg in messages if msg["role"] != "user"] formatted_input = { "input": user_input, "chat_history": chat_history } response = await agent_executor.ainvoke(formatted_input) if response is None: logging.error("Received None response from ainvoke") return "Error: No response received from the agent." # 处理响应 if isinstance(response, dict): intermediate_steps = response.get('intermediate_steps', None) final_answer = response.get('output', response.get('final_answer', 'No final answer found.')) if intermediate_steps is not None: for step in intermediate_steps: logging.debug(f"Intermediate Step: {step}") return final_answer except Exception as e: # 新增全局异常捕获,方便排查 logging.error(f"Agent execution failed: {str(e)}", exc_info=True) return f"Error: {str(e)}"
额外注意事项
- 确保
self.memory是正确初始化的LangChain记忆组件(比如ConversationBufferMemory),且配置了正确的输出键。 - 若使用较新版本的LangChain,
create_openai_functions_agent返回的响应中,最终答案的键可能是output而非final_answer,需优先取output。
内容的提问来源于stack exchange,提问作者Neo Mx
相关产品推荐
相关产品推荐

