You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangGraph自定义ReAct Agent工具读写状态时被忽略的问题求助

解决LangGraph ReAct Agent工具读写状态时被忽略的问题

核心排查与修复步骤

1. 修正工具定义,明确绑定状态读写逻辑

工具必须显式处理状态的读写,不能依赖隐式注入。示例如下:

from langgraph.prebuilt import tool

@tool
def example_tool(state: MyState) -> dict:
    # 读取State中的user_query
    query = state["user_query"]
    # 执行工具逻辑,生成要添加到model_context的内容
    new_context = f"Processed query: {query}"
    # 返回更新State的指令,对应operator.add注解自动追加列表
    return {"model_context": [new_context]}

确保工具函数接收MyState类型参数,并返回包含要更新字段的字典,让LangGraph能正确合并状态。

2. 强化Reasoner的Prompt提示

LLM忽略工具通常是因为Prompt未明确告知其调用时机。在agent_main_reasoner的Prompt中必须补充:

当你需要使用用户原始查询内容(user_query),或者需要将处理结果追加到对话上下文(model_context)时,必须调用对应的工具,禁止自行处理。

3. 检查tools_condition函数的分支逻辑

确保条件函数正确识别LLM的工具调用请求,不要过滤涉及状态的工具调用。示例:

def tools_condition(state: MyState) -> str:
    # 假设reasoner将决策存在state的next_action字段中
    if state.get("next_action") == "call_tool":
        return "tools"
    return "__end__"

若使用LangGraph默认ReAct模板,需确保函数能正确解析LLM输出中的工具调用指令,返回"tools"分支。

4. 验证ToolNode的状态映射配置

如果自定义ToolNode逻辑,要确保工具的输入输出正确映射到State:

# 确保ToolNode正确处理状态输入与输出更新
tools_node = ToolNode(mytools)
# 若需自定义映射,用lambda函数处理状态流转
builder.add_node("tools", lambda state: tools_node.invoke(state))

确认工具执行后的返回值被正确合并到State,尤其是model_context的追加操作符合operator.add的注解规则。

5. 调试状态流转,确认数据传递

在编译后的图中添加调试节点,打印各环节的State变化:

def debug_state(state: MyState) -> MyState:
    print("Current State:", state)
    return state

builder.add_node("debug", debug_state)
builder.add_edge("reasoner", "debug")
builder.add_edge("debug", "tools")

通过调试确认user_query是否正确传递到工具,model_context是否被工具更新后返回。


内容的提问来源于stack exchange,提问作者Joey O'Neill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 21:59:53