如何获取Vertex AI LangchainAgent调用query方法后的完整推理历史?
获取Vertex AI LangchainAgent完整推理历史的可行方案
问题背景
调用vertexai.preview.reasoning_engines.LangchainAgent的query方法时,无法获取包含“思考”环节的完整推理链路,仅能看到工具函数调用记录,而纯LangChain的ReAct Agent可正常查看完整推理过程。
已验证的可行解决步骤
正确配置
agent_executor_kwargs参数
在实例化LangchainAgent时,确保在agent_executor_kwargs中同时设置return_intermediate_steps=True和verbose=True,示例代码如下:from vertexai.preview.reasoning_engines import LangchainAgent agent = LangchainAgent.from_llm( llm=your_gemini_model, tools=your_tools_list, agent_executor_kwargs={ "return_intermediate_steps": True, "verbose": True } )调用
query后,返回结果会包含intermediate_steps字段,其中每一步的action.log会包含Agent的思考内容(例如“我需要调用XX工具来获取XX信息”)。扩展回调处理器以捕获思考内容
自定义BaseCallbackHandler时,除了on_agent_action和on_llm_end,还可以实现on_chain_end方法,从返回的结果中提取intermediate_steps;或者在on_llm_end中解析LLM的输出,直接获取思考文本:from langchain.callbacks.base import BaseCallbackHandler class CustomCallbackHandler(BaseCallbackHandler): def on_llm_end(self, response, **kwargs): # 解析LLM输出中的思考内容 for generation in response.generations[0]: print(f"思考内容:{generation.text}") def on_chain_end(self, outputs, **kwargs): # 提取完整中间步骤(含思考和动作) if "intermediate_steps" in outputs: for step in outputs["intermediate_steps"]: print(f"思考:{step[0].log}") print(f"动作:{step[1]}")实例化Agent时将回调处理器传入
agent_executor_kwargs的callbacks列表:agent = LangchainAgent.from_llm( llm=your_gemini_model, tools=your_tools_list, agent_executor_kwargs={ "return_intermediate_steps": True, "verbose": True, "callbacks": [CustomCallbackHandler()] } )确认LLM Prompt配置
部分情况下,Vertex AI封装的Agent可能默认使用的Prompt并未明确要求输出思考步骤,可以通过自定义ReAct风格的Prompt来强制Agent输出思考内容,示例如下:from langchain.prompts import PromptTemplate react_prompt = PromptTemplate( template="""Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Question: {input} Thought:""", input_variables=["input", "tools", "tool_names"], ) agent = LangchainAgent.from_llm( llm=your_gemini_model, tools=your_tools_list, prompt=react_prompt, agent_executor_kwargs={ "return_intermediate_steps": True, "verbose": True } )
关键说明
- 切勿将
return_intermediate_steps放在model_kwargs中,该参数属于Agent Executor的配置项,仅在agent_executor_kwargs中生效。 verbose=True需要与return_intermediate_steps=True配合使用,才能确保思考步骤被记录到返回结果中。
内容的提问来源于stack exchange,提问作者Thulium
相关产品推荐
相关产品推荐

