YouTip LogoYouTip

Langchain State Store

```html

LangChain Tool Access β€” InjectedState and InjectedStore

Sometimes tools need to access more context information, such as the current conversation state, user's persistent data, etc.

LangChain uses a dependency injection mechanism to allow tool functions to automatically obtain this information.


InjectedState β€” Accessing Agent State in Tools

By default, tools can only receive data from the model through parameters. However, sometimes tools need to know the context of the current conversation β€” such as previous conversation history, user-confirmed information, etc.

InjectedState allows tools to directly read the complete state of the Agent.

Example

from typing import Annotated, Any

from dotenv import load_dotenv

 load_dotenv()

from langchain.tools import tool, InjectedState

from langchain.agents import create_agent

from langchain.chat_models import init_chat_model

from langchain.messages import HumanMessage

@tool

def remember_preference(

 preference: str,

 state: Annotated[dict[str, Any], InjectedState],

) ->str:

"""Remember the user's preference settings.
Args:

 preference: The user's preference content

 state: The automatically injected current Agent state

 """

# Get previous message history from state

 messages = state.get("messages",[])

 message_count =len(messages)

# Can read any field in the state

 previous_prefs = state.get("user_preferences","None")

return(

 f"Remembered preference: {preference}."

 f"(Current conversation has {message_count} messages,"

 f"previous preferences: {previous_prefs})"

)

# InjectedState is automatically injected, Agent doesn't need to pass this parameter

 result = remember_preference.invoke({

"preference": "Dark theme",

# state doesn't need to be passed, automatically injected by the framework

})

print(result)

Running result:

Remembered preference: Dark theme. (Current conversation has 0 messages, previous preferences: None)

Using InjectedState in Agents

Example

from typing import Annotated, Any

from langchain.tools import tool, InjectedState

from langchain.agents import create_agent

from langchain.chat_models import init_chat_model

from langchain.messages import HumanMessage

@tool

def conversation_stats(

 state: Annotated[dict[str, Any], InjectedState],

) ->str:

"""Get current conversation statistics, such as message count, conversation length, etc.
No parameters needed, statistics are automatically read from the current state.

 """

 messages = state.get("messages",[])

 human_msgs =[m for m in messages if m.type=="human"]

 ai_msgs =[m for m in messages if m.type=="ai"]

 tool_msgs =[m for m in messages if m.type=="tool"]

return(

 f"Conversation statistics: {len(messages)} total messages | "

 f"User messages: {len(human_msgs)} | "

 f"AI responses: {len(ai_msgs)} | "

 f"Tool calls: {len(tool_msgs)} times"

)

InjectedState allows you to access all fields in AgentState. If you extend the state_schema (adding custom fields), these fields can also be read by InjectedState.


InjectedStore β€” Accessing Persistent Storage in Tools

Agent state is conversation-level and disappears when the conversation ends. Store is a cross-session persistent storage that can be used to save user preferences, learning progress, and other long-term information.

InjectedStore allows tools to directly read and write to Store.

Example

from typing import Annotated

from langgraph.store.base import BaseStore

from langgraph.store.mem
```
← Langchain Agent WorkflowLangchain Tool Basics β†’