The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
feat(langchain_v1): injected runtime (#33500)
Sydney Runkle89c3428d85c4
diff --git a/libs/langchain_v1/langchain/tools/__init__.py b/libs/langchain_v1/langchain/tools/__init__.pyindex 190f6955c4..92aca31aec 100644--- a/libs/langchain_v1/langchain/tools/__init__.py+++ b/libs/langchain_v1/langchain/tools/__init__.py@@ -14,7 +14,7 @@ from langchain_core.tools import (tool,)-from langchain.tools.tool_node import InjectedState, InjectedStore+from langchain.tools.tool_node import InjectedState, InjectedStore, ToolRuntime__all__ = ["BaseTool",@@ -23,5 +23,6 @@ __all__ = ["InjectedToolArg","InjectedToolCallId","ToolException",+ "ToolRuntime","tool",]diff --git a/libs/langchain_v1/langchain/tools/tool_node.py b/libs/langchain_v1/langchain/tools/tool_node.pyindex 1d79c490e4..2c86c4f3c0 100644--- a/libs/langchain_v1/langchain/tools/tool_node.py+++ b/libs/langchain_v1/langchain/tools/tool_node.py@@ -46,9 +46,10 @@ from typing import (TYPE_CHECKING,Annotated,Any,+ Generic,Literal,- Optional,TypedDict,+ TypeVar,Union,cast,get_args,@@ -65,6 +66,7 @@ from langchain_core.messages import (convert_to_messages,)from langchain_core.runnables.config import (+ RunnableConfig,get_config_list,get_executor_for_config,)@@ -78,16 +80,18 @@ from langchain_core.tools.base import (from langgraph._internal._runnable import RunnableCallablefrom langgraph.errors import GraphBubbleUpfrom langgraph.graph.message import REMOVE_ALL_MESSAGES-from langgraph.runtime import get_runtime-from langgraph.types import Command, Send+from langgraph.store.base import BaseStore # noqa: TC002+from langgraph.types import Command, Send, StreamWriterfrom pydantic import BaseModel, ValidationErrorfrom typing_extensions import Unpackif TYPE_CHECKING:from collections.abc import Sequence- from langchain_core.runnables import RunnableConfig- from langgraph.store.base import BaseStore+ from langgraph.runtime import Runtime++StateT = TypeVar("StateT")+ContextT = TypeVar("ContextT")INVALID_TOOL_NAME_ERROR_TEMPLATE = ("Error: {requested_tool} is not a valid tool, try one of [{available_tools}]."@@ -125,7 +129,7 @@ class ToolCallRequest:tool_call: ToolCalltool: BaseToolstate: Any- runtime: Any+ runtime: ToolRuntimedef override(self, **overrides: Unpack[_ToolCallRequestOverrides]) -> ToolCallRequest:"""Replace the request with a new request with the given overrides.@@ -570,6 +574,7 @@ class _ToolNode(RunnableCallable):self._tools_by_name: dict[str, BaseTool] = {}self._tool_to_state_args: dict[str, dict[str, str | None]] = {}self._tool_to_store_arg: dict[str, str | None] = {}+ self._tool_to_runtime_arg: dict[str, str | None] = {}self._handle_tool_errors = handle_tool_errorsself._messages_key = messages_keyself._wrap_tool_call = wrap_tool_call@@ -582,6 +587,7 @@ class _ToolNode(RunnableCallable):self._tools_by_name[tool_.name] = tool_self._tool_to_state_args[tool_.name] = _get_state_args(tool_)self._tool_to_store_arg[tool_.name] = _get_store_arg(tool_)+ self._tool_to_runtime_arg[tool_.name] = _get_runtime_arg(tool_)@propertydef tools_by_name(self) -> dict[str, BaseTool]:@@ -592,26 +598,36 @@ class _ToolNode(RunnableCallable):self,input: list[AnyMessage] | dict[str, Any] | BaseModel,config: RunnableConfig,- *,- store: Optional[BaseStore], # noqa: UP045+ runtime: Runtime,) -> Any:- try:- runtime = get_runtime()- except RuntimeError:- # Running outside of LangGraph runtime context (e.g., unit tests)- runtime = None-tool_calls, input_type = self._parse_input(input)- tool_calls = [self._inject_tool_args(call, input, store) for call in tool_calls]-config_list = get_config_list(config, len(tool_calls))++ # Construct ToolRuntime instances at the top level for each tool call+ tool_runtimes = []+ for call, cfg in zip(tool_calls, config_list, strict=False):+ state = self._extract_state(input)+ tool_runtime = ToolRuntime(+ state=state,+ tool_call_id=call["id"],+ config=cfg,+ context=runtime.context,+ store=runtime.store,+ stream_writer=runtime.stream_writer,+ )+ tool_runtimes.append(tool_runtime)++ # Inject tool arguments (including runtime)++ injected_tool_calls = []input_types = [input_type] * len(tool_calls)- inputs = [input] * len(tool_calls)- runtimes = [runtime] * len(tool_calls)+ for call, tool_runtime in zip(tool_calls, tool_runtimes, strict=False):+ injected_call = self._inject_tool_args(call, tool_runtime)+ injected_tool_calls.append(injected_call)with get_executor_for_config(config) as executor:- outputs = [- *executor.map(self._run_one, tool_calls, input_types, config_list, inputs, runtimes)- ]+ outputs = list(+ executor.map(self._run_one, injected_tool_calls, input_types, tool_runtimes)+ )return self._combine_tool_outputs(outputs, input_type)@@ -619,20 +635,32 @@ class _ToolNode(RunnableCallable):self,input: list[AnyMessage] | dict[str, Any] | BaseModel,config: RunnableConfig,- *,- store: Optional[BaseStore], # noqa: UP045+ runtime: Runtime,) -> Any:- try:- runtime = get_runtime()- except RuntimeError:- # Running outside of LangGraph runtime context (e.g., unit tests)- runtime = None-tool_calls, input_type = self._parse_input(input)- tool_calls = [self._inject_tool_args(call, input, store) for call in tool_calls]- outputs = await asyncio.gather(- *(self._arun_one(call, input_type, config, input, runtime) for call in tool_calls)- )+ config_list = get_config_list(config, len(tool_calls))++ # Construct ToolRuntime instances at the top level for each tool call+ tool_runtimes = []+ for call, cfg in zip(tool_calls, config_list, strict=False):+ state = self._extract_state(input)+ tool_runtime = ToolRuntime(+ state=state,+ tool_call_id=call["id"],+ config=cfg,+ context=runtime.context,+ store=runtime.store,+ stream_writer=runtime.stream_writer,+ )+ tool_runtimes.append(tool_runtime)++ injected_tool_calls = []+ coros = []+ for call, tool_runtime in zip(tool_calls, tool_runtimes, strict=False):+ injected_call = self._inject_tool_args(call, tool_runtime)+ injected_tool_calls.append(injected_call)+ coros.append(self._arun_one(injected_call, input_type, tool_runtime))+ outputs = await asyncio.gather(*coros)return self._combine_tool_outputs(outputs, input_type)@@ -699,6 +727,7 @@ class _ToolNode(RunnableCallable):"""call = request.tool_calltool = request.tool+call_args = {**call, "type": "tool_call"}try:@@ -763,18 +792,14 @@ class _ToolNode(RunnableCallable):self,call: ToolCall,input_type: Literal["list", "dict", "tool_calls"],- config: RunnableConfig,- input: list[AnyMessage] | dict[str, Any] | BaseModel,- runtime: Any,+ tool_runtime: ToolRuntime,) -> ToolMessage | Command:"""Execute single tool call with wrap_tool_call wrapper if configured.Args:call: Tool call dict.input_type: Input format.- config: Runnable configuration.- input: Agent state.- runtime: LangGraph runtime or None.+ tool_runtime: Tool runtime.Returns:ToolMessage or Command.@@ -784,17 +809,16 @@ class _ToolNode(RunnableCallable):tool = self.tools_by_name[call["name"]]- # Extract state from ToolCallWithContext if present- state = self._extract_state(input)-# Create the tool request with state and runtimetool_request = ToolCallRequest(tool_call=call,tool=tool,- state=state,- runtime=runtime,+ state=tool_runtime.state,+ runtime=tool_runtime,)+ config = tool_runtime.config+if self._wrap_tool_call is None:# No wrapper - execute directlyreturn self._execute_tool_sync(tool_request, input_type, config)@@ -841,6 +865,7 @@ class _ToolNode(RunnableCallable):"""call = request.tool_calltool = request.tool+call_args = {**call, "type": "tool_call"}try:@@ -905,18 +930,14 @@ class _ToolNode(RunnableCallable):self,call: ToolCall,input_type: Literal["list", "dict", "tool_calls"],- config: RunnableConfig,- input: list[AnyMessage] | dict[str, Any] | BaseModel,- runtime: Any,+ tool_runtime: ToolRuntime,) -> ToolMessage | Command:"""Execute single tool call asynchronously with awrap_tool_call wrapper if configured.Args:call: Tool call dict.input_type: Input format.- config: Runnable configuration.- input: Agent state.- runtime: LangGraph runtime or None.+ tool_runtime: Tool runtime.Returns:ToolMessage or Command.@@ -926,17 +947,16 @@ class _ToolNode(RunnableCallable):tool = self.tools_by_name[call["name"]]- # Extract state from ToolCallWithContext if present- state = self._extract_state(input)-# Create the tool request with state and runtimetool_request = ToolCallRequest(tool_call=call,tool=tool,- state=state,- runtime=runtime,+ state=tool_runtime.state,+ runtime=tool_runtime,)+ config = tool_runtime.config+if self._awrap_tool_call is None and self._wrap_tool_call is None:# No wrapper - execute directlyreturn await self._execute_tool_async(tool_request, input_type, config)@@ -1039,15 +1059,16 @@ class _ToolNode(RunnableCallable):def _inject_state(self,tool_call: ToolCall,- input: list[AnyMessage] | dict[str, Any] | BaseModel,+ state: list[AnyMessage] | dict[str, Any] | BaseModel,) -> ToolCall:state_args = self._tool_to_state_args[tool_call["name"]]- if state_args and isinstance(input, list):++ if state_args and isinstance(state, list):required_fields = list(state_args.values())if (len(required_fields) == 1 and required_fields[0] == self._messages_key) or required_fields[0] is None:- input = {self._messages_key: input}+ state = {self._messages_key: state}else:err_msg = (f"Invalid input to ToolNode. Tool {tool_call['name']} requires "@@ -1058,12 +1079,6 @@ class _ToolNode(RunnableCallable):err_msg += f" State should contain fields {required_fields_str}."raise ValueError(err_msg)- # Extract state from ToolCallWithContext if present- if isinstance(input, dict) and input.get("__type") == "tool_call_with_context":- state = input["state"]- else:- state = input-if isinstance(state, dict):tool_state_args = {tool_arg: state[state_field] if state_field else state@@ -1099,19 +1114,38 @@ class _ToolNode(RunnableCallable):}return tool_call+ def _inject_runtime(self, tool_call: ToolCall, tool_runtime: ToolRuntime) -> ToolCall:+ """Inject ToolRuntime into tool call arguments.++ Args:+ tool_call: The tool call to inject runtime into.+ tool_runtime: The ToolRuntime instance to inject.++ Returns:+ The tool call with runtime injected if needed.+ """+ runtime_arg = self._tool_to_runtime_arg.get(tool_call["name"])+ if not runtime_arg:+ return tool_call++ tool_call["args"] = {+ **tool_call["args"],+ runtime_arg: tool_runtime,+ }+ return tool_call+def _inject_tool_args(self,tool_call: ToolCall,- input: list[AnyMessage] | dict[str, Any] | BaseModel,- store: BaseStore | None,+ tool_runtime: ToolRuntime,) -> ToolCall:- """Inject graph state and store into tool call arguments.+ """Inject graph state, store, and runtime into tool call arguments.This is an internal method that enables tools to access graph context thatshould not be controlled by the model. Tools can declare dependencies on graph- state or persistent storage using InjectedState and InjectedStore annotations.- This method automatically identifies these dependencies and injects the- appropriate values.+ state, persistent storage, or runtime context using InjectedState, InjectedStore,+ and ToolRuntime annotations. This method automatically identifies these+ dependencies and injects the appropriate values.The injection process preserves the original tool call structure while addingthe necessary context arguments. This allows tools to be both model-callable@@ -1120,10 +1154,8 @@ class _ToolNode(RunnableCallable):Args:tool_call: The tool call dictionary to augment with injected arguments.Must contain 'name', 'args', 'id', and 'type' fields.- input: The current graph state to inject into tools requiring state access.- Can be a message list, state dictionary, or BaseModel instance.- store: The persistent store instance to inject into tools requiring storage.- Will be None if no store is configured for the graph.+ tool_runtime: The ToolRuntime instance containing all runtime context+ (state, config, store, context, stream_writer) to inject into tools.Returns:A new ToolCall dictionary with the same structure as the input but with@@ -1141,8 +1173,9 @@ class _ToolNode(RunnableCallable):return tool_calltool_call_copy: ToolCall = copy(tool_call)- tool_call_with_state = self._inject_state(tool_call_copy, input)- return self._inject_store(tool_call_with_state, store)+ tool_call_with_state = self._inject_state(tool_call_copy, tool_runtime.state)+ tool_call_with_store = self._inject_store(tool_call_with_state, tool_runtime.store)+ return self._inject_runtime(tool_call_with_store, tool_runtime)def _validate_tool_command(self,@@ -1298,6 +1331,66 @@ def tools_condition(return "__end__"+@dataclass+class ToolRuntime(InjectedToolArg, Generic[StateT, ContextT]):+ """Runtime context automatically injected into tools.++ When a tool function has a parameter named 'tool_runtime' with type hint+ 'ToolRuntime', the tool execution system will automatically inject+ an instance containing:++ - state: The current graph state+ - tool_call_id: The ID of the current tool call+ - config: RunnableConfig for the current execution+ - context: Runtime context (from langgraph Runtime)+ - store: BaseStore instance for persistent storage (from langgraph Runtime)+ - stream_writer: StreamWriter for streaming output (from langgraph Runtime)++ No `Annotated` wrapper is needed - just use `tool_runtime: ToolRuntime`+ as a parameter.++ Example:+ ```python+ from langchain_core.tools import tool+ from langchain.tools import ToolRuntime++ @tool+ def my_tool(x: int, tool_runtime: ToolRuntime) -> str:+ \"\"\"Tool that accesses runtime context.\"\"\"+ # Access state+ messages = tool_runtime.state["messages"]++ # Access tool_call_id+ print(f"Tool call ID: {tool_runtime.tool_call_id}")++ # Access config+ print(f"Run ID: {tool_runtime.config.get('run_id')}")++ # Access runtime context+ user_id = tool_runtime.context.get("user_id")++ # Access store+ tool_runtime.store.put(("metrics",), "count", 1)++ # Stream output+ tool_runtime.stream_writer.write("Processing...")++ return f"Processed {x}"+ ```++ Note:+ This is a marker class used for type checking and detection.+ The actual runtime object will be constructed during tool execution.+ """++ state: StateT+ context: ContextT+ config: RunnableConfig+ stream_writer: StreamWriter+ tool_call_id: str | None+ store: BaseStore | None++class InjectedState(InjectedToolArg):"""Annotation for injecting graph state into tool arguments.@@ -1449,7 +1542,10 @@ class InjectedStore(InjectedToolArg):"""-def _is_injection(type_arg: Any, injection_type: type[InjectedState | InjectedStore]) -> bool:+def _is_injection(+ type_arg: Any,+ injection_type: type[InjectedState | InjectedStore | ToolRuntime],+) -> bool:"""Check if a type argument represents an injection annotation.This utility function determines whether a type annotation indicates that@@ -1543,3 +1639,41 @@ def _get_store_arg(tool: BaseTool) -> str | None:return namereturn None+++def _get_runtime_arg(tool: BaseTool) -> str | None:+ """Extract runtime injection argument from tool annotations.++ This function analyzes a tool's input schema to identify the argument that+ should be injected with the ToolRuntime instance. Only one runtime argument+ is supported per tool.++ Args:+ tool: The tool to analyze for runtime injection requirements.++ Returns:+ The name of the argument that should receive the runtime injection, or None+ if no runtime injection is required.++ Raises:+ ValueError: If a tool argument has multiple ToolRuntime annotations.+ """+ full_schema = tool.get_input_schema()+ for name, type_ in get_all_basemodel_annotations(full_schema).items():+ # Check if the type itself is ToolRuntime (direct usage)+ if _is_injection(type_, ToolRuntime):+ return name+ # Check if ToolRuntime is in Annotated args+ injections = [+ type_arg for type_arg in get_args(type_) if _is_injection(type_arg, ToolRuntime)+ ]+ if len(injections) > 1:+ msg = (+ "A tool argument should not be annotated with ToolRuntime more than "+ f"once. Received arg {name} with annotations {injections}."+ )+ raise ValueError(msg)+ if len(injections) == 1:+ return name++ return Nonediff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_tool_call_decorator.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_tool_call_decorator.pyindex 2f33e036de..b602c43208 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_tool_call_decorator.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_tool_call_decorator.py@@ -4,7 +4,6 @@ These tests verify the decorator-based approach for wrapping tool calls,focusing on the handler pattern (not generators)."""-import pytestfrom collections.abc import Callablefrom langchain_core.messages import HumanMessage, ToolCall, ToolMessage@@ -210,7 +209,7 @@ def test_wrap_tool_call_access_runtime() -> None:# Middleware should have accessed runtimeassert len(runtime_data) >= 1- assert runtime_data[0] == "Runtime"+ assert runtime_data[0] == "ToolRuntime"def test_wrap_tool_call_retry_on_error() -> None:diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py b/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.pynew file mode 100644index 0000000000..b342da1fa2--- /dev/null+++ b/libs/langchain_v1/tests/unit_tests/agents/test_injected_runtime_create_agent.py@@ -0,0 +1,544 @@+"""Test ToolRuntime injection with create_agent.++This module tests the injected runtime functionality when using tools+with the create_agent factory. The ToolRuntime provides tools access to:+- state: Current graph state+- tool_call_id: ID of the current tool call+- config: RunnableConfig for the execution+- context: Runtime context from LangGraph+- store: BaseStore for persistent storage+- stream_writer: For streaming custom output++These tests verify that runtime injection works correctly across both+sync and async execution paths, with middleware, and in various agent+configurations.+"""++from __future__ import annotations++import pytest+from langchain_core.messages import AIMessage, HumanMessage, ToolMessage+from langchain_core.tools import tool+from langgraph.store.memory import InMemoryStore++from langchain.agents import create_agent+from langchain.agents.middleware.types import AgentState+from langchain.tools import ToolRuntime++from .model import FakeToolCallingModel+++def test_tool_runtime_basic_injection() -> None:+ """Test basic ToolRuntime injection in tools with create_agent."""+ # Track what was injected+ injected_data = {}++ @tool+ def runtime_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool that accesses runtime context."""+ injected_data["state"] = tool_runtime.state+ injected_data["tool_call_id"] = tool_runtime.tool_call_id+ injected_data["config"] = tool_runtime.config+ injected_data["context"] = tool_runtime.context+ injected_data["store"] = tool_runtime.store+ injected_data["stream_writer"] = tool_runtime.stream_writer+ return f"Processed {x}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 42}, "id": "call_123", "name": "runtime_tool"}],+ [],+ ]+ ),+ tools=[runtime_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test")]})++ # Verify tool executed+ assert len(result["messages"]) == 4+ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Processed 42"+ assert tool_message.tool_call_id == "call_123"++ # Verify runtime was injected+ assert injected_data["state"] is not None+ assert "messages" in injected_data["state"]+ assert injected_data["tool_call_id"] == "call_123"+ assert injected_data["config"] is not None+ # Context, store, stream_writer may be None depending on graph setup+ assert "context" in injected_data+ assert "store" in injected_data+ assert "stream_writer" in injected_data+++async def test_tool_runtime_async_injection() -> None:+ """Test ToolRuntime injection works with async tools."""+ injected_data = {}++ @tool+ async def async_runtime_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Async tool that accesses runtime context."""+ injected_data["state"] = tool_runtime.state+ injected_data["tool_call_id"] = tool_runtime.tool_call_id+ injected_data["config"] = tool_runtime.config+ return f"Async processed {x}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 99}, "id": "async_call_456", "name": "async_runtime_tool"}],+ [],+ ]+ ),+ tools=[async_runtime_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = await agent.ainvoke({"messages": [HumanMessage("Test async")]})++ # Verify tool executed+ assert len(result["messages"]) == 4+ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Async processed 99"+ assert tool_message.tool_call_id == "async_call_456"++ # Verify runtime was injected+ assert injected_data["state"] is not None+ assert "messages" in injected_data["state"]+ assert injected_data["tool_call_id"] == "async_call_456"+ assert injected_data["config"] is not None+++def test_tool_runtime_state_access() -> None:+ """Test that tools can access and use state via ToolRuntime."""++ @tool+ def state_aware_tool(query: str, tool_runtime: ToolRuntime) -> str:+ """Tool that uses state to provide context-aware responses."""+ messages = tool_runtime.state.get("messages", [])+ msg_count = len(messages)+ return f"Query: {query}, Message count: {msg_count}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"query": "test"}, "id": "state_call", "name": "state_aware_tool"}],+ [],+ ]+ ),+ tools=[state_aware_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Hello"), HumanMessage("World")]})++ # Check that tool accessed state correctly+ tool_message = result["messages"][3]+ assert isinstance(tool_message, ToolMessage)+ # Should have original 2 HumanMessages + 1 AIMessage before tool execution+ assert "Message count: 3" in tool_message.content+++def test_tool_runtime_with_store() -> None:+ """Test ToolRuntime provides access to store."""+ # Note: create_agent doesn't currently expose a store parameter,+ # so tool_runtime.store will be None in this test.+ # This test demonstrates the runtime injection works correctly.++ @tool+ def store_tool(key: str, value: str, tool_runtime: ToolRuntime) -> str:+ """Tool that uses store."""+ if tool_runtime.store is None:+ return f"No store (key={key}, value={value})"+ tool_runtime.store.put(("test",), key, {"data": value})+ return f"Stored {key}={value}"++ @tool+ def check_runtime_tool(tool_runtime: ToolRuntime) -> str:+ """Tool that checks runtime availability."""+ has_store = tool_runtime.store is not None+ has_context = tool_runtime.context is not None+ return f"Runtime: store={has_store}, context={has_context}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"key": "foo", "value": "bar"}, "id": "call_1", "name": "store_tool"}],+ [{"args": {}, "id": "call_2", "name": "check_runtime_tool"}],+ [],+ ]+ ),+ tools=[store_tool, check_runtime_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test store")]})++ # Find the tool messages+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]+ assert len(tool_messages) == 2++ # First tool indicates no store is available (expected since create_agent doesn't expose store)+ assert "No store" in tool_messages[0].content++ # Second tool confirms runtime was injected+ assert "Runtime:" in tool_messages[1].content+++def test_tool_runtime_with_multiple_tools() -> None:+ """Test multiple tools can all access ToolRuntime."""+ call_log = []++ @tool+ def tool_a(x: int, tool_runtime: ToolRuntime) -> str:+ """First tool."""+ call_log.append(("tool_a", tool_runtime.tool_call_id, x))+ return f"A: {x}"++ @tool+ def tool_b(y: str, tool_runtime: ToolRuntime) -> str:+ """Second tool."""+ call_log.append(("tool_b", tool_runtime.tool_call_id, y))+ return f"B: {y}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [+ {"args": {"x": 1}, "id": "call_a", "name": "tool_a"},+ {"args": {"y": "test"}, "id": "call_b", "name": "tool_b"},+ ],+ [],+ ]+ ),+ tools=[tool_a, tool_b],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Use both tools")]})++ # Verify both tools were called with correct runtime+ assert len(call_log) == 2+ # Tools may execute in parallel, so check both calls are present+ call_ids = {(name, call_id) for name, call_id, _ in call_log}+ assert ("tool_a", "call_a") in call_ids+ assert ("tool_b", "call_b") in call_ids++ # Verify tool messages+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]+ assert len(tool_messages) == 2+ contents = {msg.content for msg in tool_messages}+ assert "A: 1" in contents+ assert "B: test" in contents+++def test_tool_runtime_config_access() -> None:+ """Test tools can access config through ToolRuntime."""+ config_data = {}++ @tool+ def config_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool that accesses config."""+ config_data["config_exists"] = tool_runtime.config is not None+ config_data["has_configurable"] = (+ "configurable" in tool_runtime.config if tool_runtime.config else False+ )+ # Config may have run_id or other fields depending on execution context+ if tool_runtime.config:+ config_data["config_keys"] = list(tool_runtime.config.keys())+ return f"Config accessed for {x}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 5}, "id": "config_call", "name": "config_tool"}],+ [],+ ]+ ),+ tools=[config_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test config")]})++ # Verify config was accessible+ assert config_data["config_exists"] is True+ assert "config_keys" in config_data++ # Verify tool executed+ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Config accessed for 5"+++def test_tool_runtime_with_custom_state() -> None:+ """Test ToolRuntime works with custom state schemas."""+ from typing_extensions import Annotated, TypedDict++ from langchain.agents.middleware.types import AgentMiddleware++ class CustomState(AgentState):+ custom_field: str++ runtime_state = {}++ @tool+ def custom_state_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool that accesses custom state."""+ runtime_state["custom_field"] = tool_runtime.state.get("custom_field", "not found")+ return f"Custom: {x}"++ class CustomMiddleware(AgentMiddleware):+ state_schema = CustomState++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 10}, "id": "custom_call", "name": "custom_state_tool"}],+ [],+ ]+ ),+ tools=[custom_state_tool],+ system_prompt="You are a helpful assistant.",+ middleware=[CustomMiddleware()],+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Test custom state")], "custom_field": "custom_value"}+ )++ # Verify custom field was accessible+ assert runtime_state["custom_field"] == "custom_value"++ # Verify tool executed+ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Custom: 10"+++def test_tool_runtime_no_runtime_parameter() -> None:+ """Test that tools without runtime parameter work normally."""++ @tool+ def regular_tool(x: int) -> str:+ """Regular tool without runtime."""+ return f"Regular: {x}"++ @tool+ def runtime_tool(y: int, tool_runtime: ToolRuntime) -> str:+ """Tool with runtime."""+ return f"Runtime: {y}, call_id: {tool_runtime.tool_call_id}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [+ {"args": {"x": 1}, "id": "regular_call", "name": "regular_tool"},+ {"args": {"y": 2}, "id": "runtime_call", "name": "runtime_tool"},+ ],+ [],+ ]+ ),+ tools=[regular_tool, runtime_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test mixed tools")]})++ # Verify both tools executed correctly+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]+ assert len(tool_messages) == 2+ assert tool_messages[0].content == "Regular: 1"+ assert "Runtime: 2, call_id: runtime_call" in tool_messages[1].content+++async def test_tool_runtime_parallel_execution() -> None:+ """Test ToolRuntime injection works with parallel tool execution."""+ execution_log = []++ @tool+ async def parallel_tool_1(x: int, tool_runtime: ToolRuntime) -> str:+ """First parallel tool."""+ execution_log.append(("tool_1", tool_runtime.tool_call_id, x))+ return f"Tool1: {x}"++ @tool+ async def parallel_tool_2(y: int, tool_runtime: ToolRuntime) -> str:+ """Second parallel tool."""+ execution_log.append(("tool_2", tool_runtime.tool_call_id, y))+ return f"Tool2: {y}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [+ {"args": {"x": 10}, "id": "parallel_1", "name": "parallel_tool_1"},+ {"args": {"y": 20}, "id": "parallel_2", "name": "parallel_tool_2"},+ ],+ [],+ ]+ ),+ tools=[parallel_tool_1, parallel_tool_2],+ system_prompt="You are a helpful assistant.",+ )++ result = await agent.ainvoke({"messages": [HumanMessage("Run parallel")]})++ # Verify both tools executed+ assert len(execution_log) == 2++ # Find the tool messages (order may vary due to parallel execution)+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]+ assert len(tool_messages) == 2++ contents = {msg.content for msg in tool_messages}+ assert "Tool1: 10" in contents+ assert "Tool2: 20" in contents++ call_ids = {msg.tool_call_id for msg in tool_messages}+ assert "parallel_1" in call_ids+ assert "parallel_2" in call_ids+++def test_tool_runtime_error_handling() -> None:+ """Test error handling with ToolRuntime injection."""++ @tool+ def error_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool that may error."""+ # Access runtime to ensure it's injected even during errors+ _ = tool_runtime.tool_call_id+ if x == 0:+ msg = "Cannot process zero"+ raise ValueError(msg)+ return f"Processed: {x}"++ # create_agent uses default error handling which doesn't catch ValueError+ # So we need to handle this differently+ @tool+ def safe_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool that handles errors safely."""+ try:+ if x == 0:+ return "Error: Cannot process zero"+ return f"Processed: {x}"+ except Exception as e:+ return f"Error: {e}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 0}, "id": "error_call", "name": "safe_tool"}],+ [{"args": {"x": 5}, "id": "success_call", "name": "safe_tool"}],+ [],+ ]+ ),+ tools=[safe_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test error handling")]})++ # Both tool calls should complete+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]+ assert len(tool_messages) == 2++ # First call returned error message+ assert "Error:" in tool_messages[0].content or "Cannot process zero" in tool_messages[0].content++ # Second call succeeded+ assert "Processed: 5" in tool_messages[1].content+++def test_tool_runtime_with_middleware() -> None:+ """Test ToolRuntime injection works with agent middleware."""+ from typing import Any++ from langchain.agents.middleware.types import AgentMiddleware++ middleware_calls = []+ runtime_calls = []++ class TestMiddleware(AgentMiddleware):+ def before_model(self, state, runtime) -> dict[str, Any]:+ middleware_calls.append("before_model")+ return {}++ def after_model(self, state, runtime) -> dict[str, Any]:+ middleware_calls.append("after_model")+ return {}++ @tool+ def middleware_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool with runtime in middleware agent."""+ runtime_calls.append(("middleware_tool", tool_runtime.tool_call_id))+ return f"Middleware result: {x}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 7}, "id": "mw_call", "name": "middleware_tool"}],+ [],+ ]+ ),+ tools=[middleware_tool],+ system_prompt="You are a helpful assistant.",+ middleware=[TestMiddleware()],+ )++ result = agent.invoke({"messages": [HumanMessage("Test with middleware")]})++ # Verify middleware ran+ assert "before_model" in middleware_calls+ assert "after_model" in middleware_calls++ # Verify tool with runtime executed+ assert len(runtime_calls) == 1+ assert runtime_calls[0] == ("middleware_tool", "mw_call")++ # Verify result+ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Middleware result: 7"+++def test_tool_runtime_type_hints() -> None:+ """Test that ToolRuntime provides access to state fields."""+ typed_runtime = {}++ # Use ToolRuntime without generic type hints to avoid forward reference issues+ @tool+ def typed_runtime_tool(x: int, tool_runtime: ToolRuntime) -> str:+ """Tool with runtime access."""+ # Access state dict - verify we can access standard state fields+ if isinstance(tool_runtime.state, dict):+ # Count messages in state+ typed_runtime["message_count"] = len(tool_runtime.state.get("messages", []))+ else:+ typed_runtime["message_count"] = len(getattr(tool_runtime.state, "messages", []))+ return f"Typed: {x}"++ agent = create_agent(+ model=FakeToolCallingModel(+ tool_calls=[+ [{"args": {"x": 3}, "id": "typed_call", "name": "typed_runtime_tool"}],+ [],+ ]+ ),+ tools=[typed_runtime_tool],+ system_prompt="You are a helpful assistant.",+ )++ result = agent.invoke({"messages": [HumanMessage("Test")]})++ # Verify typed runtime worked - should see 2 messages (HumanMessage + AIMessage) before tool executes+ assert typed_runtime["message_count"] == 2++ tool_message = result["messages"][2]+ assert isinstance(tool_message, ToolMessage)+ assert tool_message.content == "Typed: 3"diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py b/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.pyindex 71da2d0157..9a098f512f 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_tool_node.py@@ -7,8 +7,8 @@ from typing import (Any,NoReturn,TypeVar,- Union,)+from unittest.mock import Mockimport pytestfrom langchain_core.messages import (@@ -19,6 +19,7 @@ from langchain_core.messages import (ToolCall,ToolMessage,)+from langchain_core.runnables.config import RunnableConfigfrom langchain_core.tools import BaseTool, ToolExceptionfrom langchain_core.tools import tool as dec_toolfrom langgraph.config import get_stream_writer@@ -45,6 +46,29 @@ from .model import FakeToolCallingModelpytestmark = pytest.mark.anyio+def _create_mock_runtime(store: BaseStore | None = None) -> Mock:+ """Create a mock Runtime object for testing ToolNode outside of graph context.++ This helper is needed because ToolNode._func expects a Runtime parameter+ which is injected by RunnableCallable from config["configurable"]["__pregel_runtime"].+ When testing ToolNode directly (outside a graph), we need to provide this manually.+ """+ mock_runtime = Mock()+ mock_runtime.store = store+ mock_runtime.context = None+ mock_runtime.stream_writer = lambda *args, **kwargs: None+ return mock_runtime+++def _create_config_with_runtime(store: BaseStore | None = None) -> RunnableConfig:+ """Create a RunnableConfig with mock Runtime for testing ToolNode.++ Returns:+ RunnableConfig with __pregel_runtime in configurable dict.+ """+ return {"configurable": {"__pregel_runtime": _create_mock_runtime(store)}}++def tool1(some_val: int, some_other_val: str) -> str:"""Tool 1 docstring."""if some_val == 0:@@ -102,7 +126,8 @@ async def test_tool_node() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result["messages"][-1]@@ -124,7 +149,8 @@ async def test_tool_node() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result2["messages"][-1]@@ -146,7 +172,8 @@ async def test_tool_node() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result3["messages"][-1]assert tool_message.type == "tool"@@ -170,7 +197,8 @@ async def test_tool_node() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result4["messages"][-1]assert tool_message.type == "tool"@@ -186,7 +214,7 @@ async def test_tool_node_tool_call_input() -> None:"id": "some 0","type": "tool_call",}- result = _ToolNode([tool1]).invoke([tool_call_1])+ result = _ToolNode([tool1]).invoke([tool_call_1], config=_create_config_with_runtime())assert result["messages"] == [ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),]@@ -198,7 +226,9 @@ async def test_tool_node_tool_call_input() -> None:"id": "some 1","type": "tool_call",}- result = _ToolNode([tool1]).invoke([tool_call_1, tool_call_2])+ result = _ToolNode([tool1]).invoke(+ [tool_call_1, tool_call_2], config=_create_config_with_runtime()+ )assert result["messages"] == [ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),ToolMessage(content="2 - bar", tool_call_id="some 1", name="tool1"),@@ -207,7 +237,9 @@ async def test_tool_node_tool_call_input() -> None:# Test with unknown tooltool_call_3 = tool_call_1.copy()tool_call_3["name"] = "tool2"- result = _ToolNode([tool1]).invoke([tool_call_1, tool_call_3])+ result = _ToolNode([tool1]).invoke(+ [tool_call_1, tool_call_3], config=_create_config_with_runtime()+ )assert result["messages"] == [ToolMessage(content="1 - foo", tool_call_id="some 0", name="tool1"),ToolMessage(@@ -235,7 +267,8 @@ def test_tool_node_error_handling_default_invocation() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert all(m.type == "tool" for m in result["messages"])@@ -263,7 +296,8 @@ def test_tool_node_error_handling_default_exception() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)@@ -306,7 +340,8 @@ async def test_tool_node_error_handling() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert all(m.type == "tool" for m in result_error["messages"])@@ -351,7 +386,8 @@ async def test_tool_node_error_handling_callable() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result_error["messages"][-1]assert tool_message.type == "tool"@@ -382,7 +418,8 @@ async def test_tool_node_error_handling_callable() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert str(exc_info.value) == "Test error"@@ -407,7 +444,8 @@ async def test_tool_node_error_handling_callable() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert str(exc_info.value) == "Test error"@@ -428,7 +466,8 @@ async def test_tool_node_handle_tool_errors_false() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert str(exc_info.value) == "Test error"@@ -448,7 +487,8 @@ async def test_tool_node_handle_tool_errors_false() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert str(exc_info.value) == "Test error"@@ -469,7 +509,8 @@ async def test_tool_node_handle_tool_errors_false() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)@@ -489,7 +530,8 @@ def test_tool_node_individual_tool_error_handling() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result_individual_tool_error_handler["messages"][-1]@@ -514,7 +556,8 @@ def test_tool_node_incorrect_tool_name() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message: ToolMessage = result_incorrect_name["messages"][-1]@@ -550,7 +593,8 @@ def test_tool_node_node_interrupt() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert exc_info.value == "foo"@@ -637,7 +681,7 @@ async def test_tool_node_command(input_type: str) -> None:input_ = {"messages": [AIMessage("", tool_calls=tool_calls)]}elif input_type == "tool_calls":input_ = tool_calls- result = _ToolNode([add, transfer_to_bob]).invoke(input_)+ result = _ToolNode([add, transfer_to_bob]).invoke(input_, config=_create_config_with_runtime())assert result == [{@@ -669,7 +713,8 @@ async def test_tool_node_command(input_type: str) -> None:# test sync toolsfor tool in [transfer_to_bob, custom_tool]:result = _ToolNode([tool]).invoke(- {"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]}+ {"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]},+ config=_create_config_with_runtime(),)assert result == [Command(@@ -690,7 +735,8 @@ async def test_tool_node_command(input_type: str) -> None:# test async toolsfor tool in [async_transfer_to_bob, async_custom_tool]:result = await _ToolNode([tool]).ainvoke(- {"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]}+ {"messages": [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]},+ config=_create_config_with_runtime(),)assert result == [Command(@@ -720,7 +766,8 @@ async def test_tool_node_command(input_type: str) -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert result == [Command(@@ -767,7 +814,8 @@ async def test_tool_node_command(input_type: str) -> None:tool_calls=[{"args": {}, "id": "1", "name": "list_update_tool"}],)]- }+ },+ config=_create_config_with_runtime(),)# test validation (missing tool message in the update for current graph)@@ -786,7 +834,8 @@ async def test_tool_node_command(input_type: str) -> None:tool_calls=[{"args": {}, "id": "1", "name": "no_update_tool"}],)]- }+ },+ config=_create_config_with_runtime(),)# test validation (tool message with a wrong tool call ID)@@ -811,7 +860,8 @@ async def test_tool_node_command(input_type: str) -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# test validation (missing tool message in the update for parent graph is OK)@@ -828,7 +878,8 @@ async def test_tool_node_command(input_type: str) -> None:tool_calls=[{"args": {}, "id": "1", "name": "node_update_parent_tool"}],)]- }+ },+ config=_create_config_with_runtime(),) == [Command(update={"messages": []}, graph=Command.PARENT)]@@ -906,7 +957,8 @@ async def test_tool_node_command_list_input() -> None:{"args": {}, "id": "2", "name": "transfer_to_bob"},],)- ]+ ],+ config=_create_config_with_runtime(),)assert result == [@@ -935,7 +987,8 @@ async def test_tool_node_command_list_input() -> None:# test sync toolsfor tool in [transfer_to_bob, custom_tool]:result = _ToolNode([tool]).invoke(- [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]+ [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])],+ config=_create_config_with_runtime(),)assert result == [Command(@@ -954,7 +1007,8 @@ async def test_tool_node_command_list_input() -> None:# test async toolsfor tool in [async_transfer_to_bob, async_custom_tool]:result = await _ToolNode([tool]).ainvoke(- [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])]+ [AIMessage("", tool_calls=[{"args": {}, "id": "1", "name": tool.name}])],+ config=_create_config_with_runtime(),)assert result == [Command(@@ -980,7 +1034,8 @@ async def test_tool_node_command_list_input() -> None:{"args": {}, "id": "2", "name": "custom_transfer_to_bob"},],)- ]+ ],+ config=_create_config_with_runtime(),)assert result == [Command(@@ -1023,7 +1078,8 @@ async def test_tool_node_command_list_input() -> None:"",tool_calls=[{"args": {}, "id": "1", "name": "list_update_tool"}],)- ]+ ],+ config=_create_config_with_runtime(),)# test validation (missing tool message in the update for current graph)@@ -1040,7 +1096,8 @@ async def test_tool_node_command_list_input() -> None:"",tool_calls=[{"args": {}, "id": "1", "name": "no_update_tool"}],)- ]+ ],+ config=_create_config_with_runtime(),)# test validation (tool message with a wrong tool call ID)@@ -1057,7 +1114,8 @@ async def test_tool_node_command_list_input() -> None:"",tool_calls=[{"args": {}, "id": "1", "name": "mismatching_tool_call_id_tool"}],)- ]+ ],+ config=_create_config_with_runtime(),)# test validation (missing tool message in the update for parent graph is OK)@@ -1072,7 +1130,8 @@ async def test_tool_node_command_list_input() -> None:"",tool_calls=[{"args": {}, "id": "1", "name": "node_update_parent_tool"}],)- ]+ ],+ config=_create_config_with_runtime(),) == [Command(update=[], graph=Command.PARENT)]@@ -1127,7 +1186,8 @@ def test_tool_node_parent_command_with_send() -> None:]result = _ToolNode([transfer_to_alice, transfer_to_bob]).invoke(- [AIMessage("", tool_calls=tool_calls)]+ [AIMessage("", tool_calls=tool_calls)],+ config=_create_config_with_runtime(),)assert result == [@@ -1177,7 +1237,10 @@ async def test_tool_node_command_remove_all_messages() -> None:"args": {},"id": "tool_call_123",}- result = await tool_node.ainvoke({"messages": [AIMessage(content="", tool_calls=[tool_call])]})+ result = await tool_node.ainvoke(+ {"messages": [AIMessage(content="", tool_calls=[tool_call])]},+ config=_create_config_with_runtime(),+ )assert isinstance(result, list)assert len(result) == 1@@ -1253,7 +1316,9 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:"type": "tool_call",}msg = AIMessage("hi?", tool_calls=[tool_call])- result = node.invoke(schema_(messages=[msg], foo="bar"))+ result = node.invoke(+ schema_(messages=[msg], foo="bar"), config=_create_config_with_runtime()+ )tool_message = result["messages"][-1]assert tool_message.content == "bar", f"Failed for tool={tool_name}"@@ -1263,10 +1328,10 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:failure_input = schema_(messages=[msg], notfoo="bar")if failure_input is not None:with pytest.raises(KeyError):- node.invoke(failure_input)+ node.invoke(failure_input, config=_create_config_with_runtime())with pytest.raises(ValueError):- node.invoke([msg])+ node.invoke([msg], config=_create_config_with_runtime())else:failure_input = Nonetry:@@ -1276,10 +1341,10 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:# anywaypassif failure_input is not None:- messages_ = node.invoke(failure_input)+ messages_ = node.invoke(failure_input, config=_create_config_with_runtime())tool_message = messages_["messages"][-1]assert "KeyError" in tool_message.content- tool_message = node.invoke([msg])[-1]+ tool_message = node.invoke([msg], config=_create_config_with_runtime())[-1]assert "KeyError" in tool_message.contenttool_call = {@@ -1289,11 +1354,11 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:"type": "tool_call",}msg = AIMessage("hi?", tool_calls=[tool_call])- result = node.invoke(schema_(messages=[msg], foo=""))+ result = node.invoke(schema_(messages=[msg], foo=""), config=_create_config_with_runtime())tool_message = result["messages"][-1]assert tool_message.content == "hi?"- result = node.invoke([msg])+ result = node.invoke([msg], config=_create_config_with_runtime())tool_message = result[-1]assert tool_message.content == "hi?"@@ -1340,7 +1405,9 @@ def test_tool_node_inject_store() -> None:"type": "tool_call",}msg = AIMessage("hi?", tool_calls=[tool_call])- node_result = node.invoke({"messages": [msg]}, store=store)+ node_result = node.invoke(+ {"messages": [msg]}, config=_create_config_with_runtime(store=store)+ )graph_result = graph.invoke({"messages": [msg]})for result in (node_result, graph_result):result["messages"][-1]@@ -1356,7 +1423,9 @@ def test_tool_node_inject_store() -> None:"type": "tool_call",}msg = AIMessage("hi?", tool_calls=[tool_call])- node_result = node.invoke({"messages": [msg], "bar": "baz"}, store=store)+ node_result = node.invoke(+ {"messages": [msg], "bar": "baz"}, config=_create_config_with_runtime(store=store)+ )graph_result = graph.invoke({"messages": [msg], "bar": "baz"})for result in (node_result, graph_result):result["messages"][-1]@@ -1381,7 +1450,8 @@ def test_tool_node_ensure_utf8() -> None:tools = [get_day_list]tool_calls = [ToolCall(name=get_day_list.name, args={"days": data}, id="test_id")]outputs: list[ToolMessage] = _ToolNode(tools).invoke(- [AIMessage(content="", tool_calls=tool_calls)]+ [AIMessage(content="", tool_calls=tool_calls)],+ config=_create_config_with_runtime(),)assert outputs[0].content == json.dumps(data, ensure_ascii=False)diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_imports.py b/libs/langchain_v1/tests/unit_tests/tools/test_imports.pyindex d552cda53c..17b66c6f77 100644--- a/libs/langchain_v1/tests/unit_tests/tools/test_imports.py+++ b/libs/langchain_v1/tests/unit_tests/tools/test_imports.py@@ -7,6 +7,7 @@ EXPECTED_ALL = {"InjectedToolArg","InjectedToolCallId","ToolException",+ "ToolRuntime","tool",}diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.pyindex 21d1a35dfb..fca75964f0 100644--- a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py+++ b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py@@ -1,10 +1,13 @@"""Unit tests for tool call interceptor in ToolNode."""from collections.abc import Callable+from unittest.mock import Mockimport pytestfrom langchain_core.messages import AIMessage, ToolCall, ToolMessage+from langchain_core.runnables import RunnableConfigfrom langchain_core.tools import tool+from langgraph.store.base import BaseStorefrom langgraph.types import Commandfrom langchain.tools.tool_node import (@@ -15,6 +18,18 @@ from langchain.tools.tool_node import (pytestmark = pytest.mark.anyio+def _create_mock_runtime(store: BaseStore | None = None) -> Mock:+ mock_runtime = Mock()+ mock_runtime.store = store+ mock_runtime.context = None+ mock_runtime.stream_writer = lambda _: None+ return mock_runtime+++def _create_config_with_runtime(store: BaseStore | None = None) -> RunnableConfig:+ return {"configurable": {"__pregel_runtime": _create_mock_runtime(store)}}++@tooldef add(a: int, b: int) -> int:"""Add two numbers."""@@ -60,7 +75,8 @@ def test_passthrough_handler() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -96,7 +112,8 @@ async def test_passthrough_handler_async() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -135,7 +152,8 @@ def test_modify_arguments() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -170,7 +188,8 @@ def test_handler_validation_no_return() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)assert isinstance(result, dict)@@ -208,7 +227,8 @@ def test_handler_validation_no_yield() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Result contains None in messages (bad handler behavior)@@ -248,7 +268,8 @@ def test_handler_with_handle_tool_errors_true() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -295,7 +316,8 @@ def test_multiple_tool_calls_with_handler() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Handler should be called once for each tool call@@ -316,7 +338,7 @@ def test_tool_call_request_dataclass() -> None:state: dict = {"messages": []}runtime = None- request = ToolCallRequest(tool_call=tool_call, tool=add, state=state, runtime=runtime)+ request = ToolCallRequest(tool_call=tool_call, tool=add, state=state, runtime=runtime) # type: ignore[arg-type]assert request.tool_call == tool_callassert request.tool == add@@ -359,7 +381,8 @@ async def test_handler_with_async_execution() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -399,7 +422,8 @@ def test_short_circuit_with_tool_message() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -439,7 +463,8 @@ async def test_short_circuit_with_tool_message_async() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -487,7 +512,8 @@ def test_conditional_short_circuit() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message1 = result1["messages"][-1]@@ -508,7 +534,8 @@ def test_conditional_short_circuit() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message2 = result2["messages"][-1]@@ -546,7 +573,8 @@ def test_direct_return_tool_message() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -586,7 +614,8 @@ async def test_direct_return_tool_message_async() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message = result["messages"][-1]@@ -632,7 +661,8 @@ def test_conditional_direct_return() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message1 = result1["messages"][-1]@@ -653,7 +683,8 @@ def test_conditional_direct_return() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)tool_message2 = result2["messages"][-1]@@ -691,7 +722,8 @@ def test_handler_can_throw_exception() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should get error message due to handle_tool_errors=True@@ -731,7 +763,8 @@ def test_handler_throw_without_handle_errors() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)@@ -775,7 +808,8 @@ def test_retry_middleware_with_exception() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should succeed after 1 attempt@@ -814,7 +848,8 @@ async def test_async_handler_can_throw_exception() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should get error message due to handle_tool_errors=True@@ -854,7 +889,8 @@ def test_handler_cannot_yield_multiple_tool_messages() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should succeed - handlers can only return once@@ -891,7 +927,8 @@ def test_handler_cannot_yield_request_after_tool_message() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should succeed with cached result@@ -926,7 +963,8 @@ def test_handler_can_short_circuit_with_command() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should get Command in result list@@ -964,7 +1002,8 @@ def test_handler_cannot_yield_multiple_commands() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should succeed - handlers naturally return once@@ -1002,7 +1041,8 @@ def test_handler_cannot_yield_request_after_command() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Should succeed with Command@@ -1043,7 +1083,8 @@ def test_tool_returning_command_sent_to_handler() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Handler should have received the Command@@ -1087,7 +1128,8 @@ def test_handler_can_modify_command_from_tool() -> None:],)]- }+ },+ config=_create_config_with_runtime(),)# Final result should be the modified Command in result list@@ -1121,7 +1163,7 @@ def test_state_extraction_with_dict_input() -> None:"other_field": "value",}- tool_node.invoke(input_state)+ tool_node.invoke(input_state, config=_create_config_with_runtime())# State should be the dict we passed inassert len(state_seen) == 1@@ -1153,7 +1195,7 @@ def test_state_extraction_with_list_input() -> None:)]- tool_node.invoke(input_state)+ tool_node.invoke(input_state, config=_create_config_with_runtime())# State should be the list we passed inassert len(state_seen) == 1@@ -1194,7 +1236,7 @@ def test_state_extraction_with_tool_call_with_context() -> None:"state": actual_state,}- tool_node.invoke(tool_call_with_context)+ tool_node.invoke(tool_call_with_context, config=_create_config_with_runtime())# State should be the extracted state from ToolCallWithContext, not the wrapperassert len(state_seen) == 1@@ -1236,7 +1278,7 @@ async def test_state_extraction_with_tool_call_with_context_async() -> None:"state": actual_state,}- await tool_node.ainvoke(tool_call_with_context)+ await tool_node.ainvoke(tool_call_with_context, config=_create_config_with_runtime())# State should be the extracted state from ToolCallWithContextassert len(state_seen) == 1