Annotation for injecting graph state into tool arguments.
This annotation enables tools to access graph state without exposing state
management details to the language model. Tools annotated with InjectedState
receive state data automatically during execution while remaining invisible
to the model's tool-calling interface.
InjectedState(
self,
field: str | None = None,
)Example:
from typing import List
from typing_extensions import Annotated, TypedDict
from langchain_core.messages import BaseMessage, AIMessage
from langchain.tools import InjectedState, ToolNode, tool
class AgentState(TypedDict):
messages: List[BaseMessage]
foo: str
@tool
def state_tool(x: int, state: Annotated[dict, InjectedState]) -> str:
'''Do something with state.'''
if len(state["messages"]) > 2:
return state["foo"] + str(x)
else:
return "not enough messages"
@tool
def foo_tool(x: int, foo: Annotated[str, InjectedState("foo")]) -> str:
'''Do something else with state.'''
return foo + str(x + 1)
node = ToolNode([state_tool, foo_tool])
tool_call1 = {"name": "state_tool", "args": {"x": 1}, "id": "1", "type": "tool_call"}
tool_call2 = {"name": "foo_tool", "args": {"x": 1}, "id": "2", "type": "tool_call"}
state = {
"messages": [AIMessage("", tool_calls=[tool_call1, tool_call2])],
"foo": "bar",
}
node.invoke(state)
[
ToolMessage(content="not enough messages", name="state_tool", tool_call_id="1"),
ToolMessage(content="bar2", name="foo_tool", tool_call_id="2"),
]
InjectedState arguments are automatically excluded from tool schemas
presented to language modelsToolNode handles the injection process during execution| Name | Type | Description |
|---|---|---|
field | str | None | Default: NoneOptional key to extract from the state dictionary. If |
| Name | Type |
|---|---|
| field | str | None |