如何解决LangChain中agent_scratchpad应为消息列表的ValueError?
LangChain Agent执行报错解决方法
问题场景
使用Python 3.9,搭配LangChain 0.3.x系列依赖包,运行结构化聊天Agent代码时,抛出错误:
ValueError: variable agent_scratchpad should be a list of base messages, got of type <class 'str'>
错误原因
create_structured_chat_agent在LangChain 0.3+版本中,要求agent_scratchpad必须是LangChain消息对象列表,但原代码中使用FakeMessagesListChatModel返回的是仅包含JSON字符串的AIMessage,无法被Agent正确解析为消息列表格式。
解决步骤
需要调整两处代码:
- 修改Fake模型的响应消息结构,加入
ToolCall类型的消息,匹配结构化聊天Agent的预期格式 - 确保Agent执行时的消息流转符合新版本要求
修改后的完整代码
import asyncio import json from langchain.agents import AgentExecutor, create_structured_chat_agent, Tool from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.messages import AIMessage, ToolMessage, HumanMessage from langchain_community.chat_models.fake import FakeMessagesListChatModel # 1. 定义工具函数 def simple_tool_function(input: str) -> str: """A simple tool that returns a fixed string.""" print(f"Tool called with input: '{input}'") return "The tool says hello back!" tools = [ Tool( name="simple_tool", func=simple_tool_function, description="A simple test tool.", ) ] # 2. 调整Fake模型的响应格式:包含ToolCall和对应的ToolMessage responses = [ # 第一步:Agent发起工具调用 AIMessage( content="", tool_calls=[{ "name": "simple_tool", "args": {"input": "hello"}, "id": "tool_call_1" }] ), # 第二步:模拟工具返回结果的ToolMessage ToolMessage( content="The tool says hello back!", tool_call_id="tool_call_1" ), # 第三步:Agent返回最终答案 AIMessage( content="The tool call was successful. The tool said: 'The tool says hello back!'" ) ] llm = FakeMessagesListChatModel(responses=responses) # 3. 保持原有Prompt结构不变 prompt = ChatPromptTemplate.from_messages([ ("system", """Respond to the human as helpfully and accurately as possible. You have access to the following tools: {tools} Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid "action" values: "Final Answer" or {tool_names} Provide only ONE action per $JSON_BLOB, as shown:
{{
"action": $TOOL_NAME,
"action_input": $INPUT
}}
Follow this format: Question: input question to answer Thought: consider previous and subsequent steps Action:
$JSON_BLOB
Observation: action result ... (repeat Thought/Action/Observation as needed) Thought: I know what to respond Action:
{{
"action": "Final Answer",
"action_input": "Final response to human"
}}
Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation"""), ("human", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad"), ]) # 4. 创建Agent和执行器 agent = create_structured_chat_agent(llm, tools, prompt) agent_executor = AgentExecutor( agent=agent, tools=tools, verbose=True, handle_parsing_errors=True, max_iterations=3 ) # 5. 运行Agent result = asyncio.run(agent_executor.ainvoke({"input": "call the tool"}))
关键修改点说明
- 消息结构调整:将原有的纯JSON字符串
AIMessage替换为带tool_calls参数的AIMessage,并添加ToolMessage模拟工具返回结果,让Agent能正确识别工具调用流程。 - 移除冗余JSON包装:最终的答案消息直接返回文本内容,无需再用JSON包裹,符合新版本Agent的输出要求。
内容的提问来源于stack exchange,提问作者hitesh
相关产品推荐
相关产品推荐

