LangGraph StateGraph调用工具时tool_runtime字段缺失报错求助
LangGraph StateGraph代理调用含ToolRuntime的工具报错问题
使用版本
langgraph==1.0.3 langchain==1.0.0 langchain_openai==1.0.0
问题代码
from pydantic import BaseModel, Field from typing import Annotated, Sequence from langchain_core.messages.base import BaseMessage from langgraph.graph import StateGraph, START, END, add_messages from langchain.tools import tool, ToolRuntime from langgraph.prebuilt import ToolNode from langchain_core.messages import AIMessage, ToolCall from langgraph.types import Command class FooState(BaseModel): messages: Annotated[Sequence[BaseMessage], add_messages] called_tool: bool = False @tool("foo_tool", description = "Please call this tool so that I can try how it's working") def foo_tool( tool_runtime: ToolRuntime ) -> Command: msg = tool_runtime.state.messages # 需访问当前状态 ... return Command(update={ "called_tool": True}) tool_node = ToolNode([foo_tool]) def foo_llm(state): return {"messages": AIMessage(content = "foo", tool_calls = [ToolCall(name = "foo_tool", args = {}, id = '1213')])} # 构建图 agent_builder = StateGraph(state_schema = FooState) agent_builder.add_node("foo_llm", foo_llm) agent_builder.add_node("tools", tool_node) # 添加边 agent_builder.add_edge(START, "foo_llm") agent_builder.add_edge("foo_llm", "tools") agent_builder.add_edge("tools", END) agent = agent_builder.compile() output = agent.invoke(input = {}) print(output)
错误输出
{'messages': [AIMessage(content='foo', additional_kwargs={}, response_metadata={}, id='e1e5fef6-c762-4720-983a-9c7792178ced', tool_calls=[{'name': 'foo_tool', 'args': {}, 'id': '1213', 'type': 'tool_call'}]), ToolMessage(content="Error invoking tool 'foo_tool' with kwargs {} with error:\n tool_runtime: Field required\n Please fix the error and try again.", name='foo_tool', id='82b5047b-d58f-4fc7-972d-367a2c8e2cd5', tool_call_id='1213', status='error')]}
预期行为
foo_tool应自动获取注入的tool_runtime(该参数对LLM不可见),但调用因字段缺失失败。
问题原因及解决方案
这是用法不当导致的问题,LangGraph默认的ToolNode不会自动将ToolRuntime注入到工具参数中,可通过以下方式解决:
方案1:自定义ToolNode注入ToolRuntime
手动实现ToolNode的调用逻辑,在调用工具时传入ToolRuntime实例:
from langgraph.prebuilt import ToolNode from langchain_core.messages import ToolMessage class CustomToolNode(ToolNode): def invoke(self, state: FooState, config: dict | None = None) -> dict: last_msg = state.messages[-1] if not (isinstance(last_msg, AIMessage) and last_msg.tool_calls): return {} tool_call = last_msg.tool_calls[0] target_tool = self.tools[tool_call["name"]] # 创建ToolRuntime实例并传入当前状态 runtime = ToolRuntime(state=state, config=config or {}) # 调用工具时注入tool_runtime参数 try: result = target_tool.invoke({**tool_call["args"], "tool_runtime": runtime}) return {"messages": [ToolMessage(content=str(result), tool_call_id=tool_call["id"])]} except Exception as e: return {"messages": [ToolMessage( content=f"Error invoking tool '{tool_call['name']}' with error:\n {str(e)}", tool_call_id=tool_call["id"], status="error" )]} # 使用自定义ToolNode替代默认实现 tool_node = CustomToolNode([foo_tool])
方案2:改用LangGraph预构建Agent框架
使用langgraph.prebuilt.create_react_agent创建代理,该框架会自动处理ToolRuntime的注入:
from langgraph.prebuilt import create_react_agent from langchain_core.language_models import BaseLanguageModel # 替换为实际的LLM实例(如OpenAI模型) llm = ... # 创建React Agent,自动处理工具调用及Runtime注入 agent = create_react_agent(llm, tools=[foo_tool], state_schema=FooState) output = agent.invoke(input={})
方案3:升级LangGraph版本
较新的LangGraph版本(如>=1.1.0)优化了ToolRuntime的注入逻辑,升级后可能无需自定义即可直接使用:
pip install --upgrade langgraph langchain
补充说明
ToolRuntime参数默认不会被LLM看到,LangChain的@tool装饰器会自动将类型为ToolRuntime的参数标记为内部参数,不会暴露在工具的描述或参数列表中。
内容的提问来源于stack exchange,提问作者Facundo
相关产品推荐
相关产品推荐

