Runtime context automatically injected into tools.
This is distinct from Runtime (from langgraph.runtime), which is injected
into graph nodes and middleware. ToolRuntime includes additional tool-specific
attributes like config, state, and tool_call_id that Runtime does not
have.
When a tool function has a parameter named runtime with type hint
ToolRuntime, the tool execution system will automatically inject an instance
containing:
state: The current graph statetool_call_id: The ID of the current tool callconfig: RunnableConfig for the current executioncontext: Runtime context (shared with Runtime)store: BaseStore instance for persistent storage (shared with Runtime)stream_writer: StreamWriter for streaming output (shared with Runtime)No Annotated wrapper is needed - just use runtime: ToolRuntime
as a parameter.
ToolRuntime(
self,
state: StateT,
context: ContextT,
config: RunnableConfig,
stream_writer: StreamWriter,
tool_call_id: str | None,
store: BaseStore | None
)Example:
from langchain_core.tools import tool
from langchain.tools import ToolRuntime
@tool
def my_tool(x: int, 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}"
This is a marker class used for type checking and detection. The actual runtime object will be constructed during tool execution.
| Name | Type |
|---|---|
| state | StateT |
| context | ContextT |
| config | RunnableConfig |
| stream_writer | StreamWriter |
| tool_call_id | str | None |
| store | BaseStore | None |