mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-10-20 23:11:43 +02:00
## Summary Extends `ToolNode` so that a single tool invocation can return `list[Command | ToolMessage]` instead of only a single `Command` or `ToolMessage`. This brings `ToolNode`'s per-tool-call contract in line with the rest of LangGraph, where nodes can already return multiple Commands. Depends on langchain-ai/langchain#36963 which allows `list[ToolOutputMixin]` to pass through `BaseTool._format_output` unchanged. ## Changes ### `libs/prebuilt/langgraph/prebuilt/tool_node.py` **New list-return gate in `_execute_tool_sync` / `_execute_tool_async`** — After the existing `Command` and `ToolMessage` checks, a new branch accepts `list[Command | ToolMessage]` and routes it through `_validate_tool_command_list`. Lists with non-`Command`/`ToolMessage` elements raise `TypeError`. Both sync and async paths are updated symmetrically. **`_validate_tool_command_list`** — Enforces the terminating-ToolMessage rule: exactly one `ToolMessage` in the list must carry `tool_call_id == <outer_id>` (top-level or nested inside a `Command.update["messages"]`). Zero or multiple terminators raise `_MissingToolMessageError`. Individual Commands in the list are validated via the existing `_validate_tool_command`; when a Command lacks the terminator (which is allowed since the list-level check handles it), the `_MissingToolMessageError` is caught and the already-normalized command from the exception is used. **`_MissingToolMessageError`** — A `ValueError` subclass raised by `_validate_tool_command` (and `_validate_tool_command_list`) when no matching `ToolMessage` is found. Carries the already-normalized command so callers can recover without re-doing deepcopy/message-conversion work. Using a typed exception avoids brittle string-matching on error messages. **`_combine_tool_outputs`** — Flattens list entries at the top of the method so downstream combiner logic (parent-`goto` accumulation, ToolMessage wrapping) is unchanged. **Response processing moved inside try/except** — In both sync and async execute methods, the response validation (Command/ToolMessage/list checks) now runs inside the existing error-handling try block, so validation errors from the list path go through `_handle_tool_errors` like other tool errors. **Return type signatures** widened on `_execute_tool_sync`, `_execute_tool_async`, `_run_one`, `_arun_one` to include `list[Command | ToolMessage]`. ### `libs/prebuilt/tests/test_tool_node.py` New tests covering: valid list returns (top-level terminator, nested terminator, parent-goto + terminator), regression tests for single Command/ToolMessage returns, invalid cases (no terminator, multiple terminators), async parity, integration with mixed list/non-list tool calls, and `_handle_tool_errors` interaction. --------- Co-authored-by: Sydney Runkle <sydneymarierunkle@gmail.com>
LangGraph Prebuilt
This library defines high-level APIs for creating and executing LangGraph agents and tools.
Important
This library is meant to be bundled with
langgraph, don't install it directly
Agents
langgraph-prebuilt provides an implementation of a tool-calling ReAct-style agent - create_react_agent:
pip install langchain-anthropic
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent
# Define the tools for the agent to use
def search(query: str):
"""Call to surf the web."""
# This is a placeholder, but don't tell the LLM that...
if "sf" in query.lower() or "san francisco" in query.lower():
return "It's 60 degrees and foggy."
return "It's 90 degrees and sunny."
tools = [search]
model = ChatAnthropic(model="claude-3-7-sonnet-latest")
app = create_react_agent(model, tools)
# run the agent
app.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
)
Tools
ToolNode
langgraph-prebuilt provides an implementation of a node that executes tool calls - ToolNode:
from langgraph.prebuilt import ToolNode
from langchain_core.messages import AIMessage
def search(query: str):
"""Call to surf the web."""
# This is a placeholder, but don't tell the LLM that...
if "sf" in query.lower() or "san francisco" in query.lower():
return "It's 60 degrees and foggy."
return "It's 90 degrees and sunny."
tool_node = ToolNode([search])
tool_calls = [{"name": "search", "args": {"query": "what is the weather in sf"}, "id": "1"}]
ai_message = AIMessage(content="", tool_calls=tool_calls)
# execute tool call
tool_node.invoke({"messages": [ai_message]})
ValidationNode
langgraph-prebuilt provides an implementation of a node that validates tool calls against a pydantic schema - ValidationNode:
from pydantic import BaseModel, field_validator
from langgraph.prebuilt import ValidationNode
from langchain_core.messages import AIMessage
class SelectNumber(BaseModel):
a: int
@field_validator("a")
def a_must_be_meaningful(cls, v):
if v != 37:
raise ValueError("Only 37 is allowed")
return v
validation_node = ValidationNode([SelectNumber])
validation_node.invoke({
"messages": [AIMessage("", tool_calls=[{"name": "SelectNumber", "args": {"a": 42}, "id": "1"}])]
})
Agent Inbox
The library contains schemas for using the Agent Inbox with LangGraph agents. Learn more about how to use Agent Inbox here.
from langgraph.types import interrupt
from langgraph.prebuilt.interrupt import HumanInterrupt, HumanResponse
def my_graph_function():
# Extract the last tool call from the `messages` field in the state
tool_call = state["messages"][-1].tool_calls[0]
# Create an interrupt
request: HumanInterrupt = {
"action_request": {
"action": tool_call['name'],
"args": tool_call['args']
},
"config": {
"allow_ignore": True,
"allow_respond": True,
"allow_edit": False,
"allow_accept": False
},
"description": _generate_email_markdown(state) # Generate a detailed markdown description.
}
# Send the interrupt request inside a list, and extract the first response
response = interrupt([request])[0]
if response['type'] == "response":
# Do something with the response
...