LangGraph中ToolNode调用工具提示tool_call_id缺失,如何实现工具+Command模式?
问题解决:LangGraph中工具+Command模式的正确实现
错误原因
tool_call_id参数未被LangGraph的ToolNode正确注入,导致调用工具时缺少必填参数。这通常是因为注入机制需要配合正确的工具定义或版本支持。
方案一:正确使用InjectedToolCallId(推荐)
确保使用最新版的LangChain和LangGraph,然后按照以下方式调整代码:
- 导入必要依赖
from typing import Annotated from pydantic import BaseModel, Field from langchain_core.tools import tool, InjectedToolCallId from langchain_core.messages import ToolMessage from langgraph.prebuilt import ToolNode from langgraph.graph import StateGraph, MessagesState
- 定义对话状态
class ChatState(MessagesState): active_chat: bool = True
- 修正工具定义
注意tool_call_id不需要加入args_schema,它会被自动注入:
class EndConversationSchema(BaseModel): """Call this tool when the user says goodbye""" reason: str = Field(description="Why does the user want to end the conversation?") @tool("end_conversation", args_schema=EndConversationSchema) def end_conversation( reason: str, tool_call_id: Annotated[str, InjectedToolCallId] ) -> dict: """End the conversation with the given reason.""" return { "active_chat": False, "messages": [ToolMessage(f"Conversation finished. Reason: {reason}", tool_call_id=tool_call_id)] }
- 创建并配置图
# 初始化工具节点 tool_node = ToolNode([end_conversation]) # 定义结束判断逻辑 def should_continue(state: ChatState) -> str: return "__end__" if not state["active_chat"] else "tools" # 构建图 graph_builder = StateGraph(ChatState) graph_builder.add_node("tools", tool_node) graph_builder.set_entry_point("tools") graph_builder.add_conditional_edges("tools", should_continue) graph = graph_builder.compile()
方案二:手动获取tool_call_id(兼容旧版本)
如果升级版本后仍有问题,可以直接从工具调用消息中提取tool_call_id,无需依赖注入机制:
from langchain_core.messages import ToolMessage from langgraph.graph import StateGraph, MessagesState from langchain_core.runnables import RunnableConfig class ChatState(MessagesState): active_chat: bool = True def end_conversation(state: ChatState, config: RunnableConfig): last_msg = state["messages"][-1] # 提取工具调用信息 tool_call = last_msg.tool_calls[0] reason = tool_call["args"]["reason"] tool_call_id = tool_call["id"] return { "active_chat": False, "messages": [ToolMessage(f"Conversation finished. Reason: {reason}", tool_call_id=tool_call_id)] } # 构建图 graph_builder = StateGraph(ChatState) graph_builder.add_node("end_convo", end_conversation) graph_builder.set_entry_point("end_convo") graph = graph_builder.compile()
额外注意事项
- 先执行升级命令确保依赖版本正确:
pip install --upgrade langchain langgraph - 返回的更新内容会被LangGraph自动合并到对话状态中,无需手动处理状态修改
内容的提问来源于stack exchange,提问作者Facundo
相关产品推荐
相关产品推荐

