Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Tool Access — InjectedState and InjectedStore

LangChain Tool Access——InjectedState, InjectedStore, and ToolRuntime

Earlier we learned how to use @tool to define tools and how to register them with an Agent.

Ordinary tools mainly receive data provided by the model through function parameters. For example, a weather query tool requires the model to pass in a city name.

But in real development, tools often need to access information that cannot be provided directly by the model:

LangChain provides a runtime dependency injection mechanism that allows tools to access this information without exposing all internal data to the language model.

Earlier tutorials often used InjectedState and InjectedStore. In LangChain 1.x, the official recommendation is to use ToolRuntime to uniformly access runtime information.

This chapter introduces these three mechanisms and their relationships, and explains how to use them correctly through complete Agent examples.


I. The Differences between State, Context, and Store

Before writing tools, you need to understand the three kinds of data at Agent runtime.

Data Type Main purpose Typical use
State Manage mutable state within a session Conversation history, current task progress, temporary selections
Context Pass the runtime context of the current call User ID, request source, tenant information
Store Share data across different sessions or calls User preferences, learning progress, long-term memory

This can be understood through the following diagram:

用户发起请求

      |

      v

  LangChain Agent

      |

      +-- State

      |     当前消息、任务状态

      |

      +-- Context

      |     用户身份、请求配置

      |

      +-- Store

            用户偏好、学习记录

      |

      v

  ToolRuntime

      |

      v

  Python 工具函数

Among these, State, Context, and Store have different lifecycles.

**State:** Used by default for the current Agent execution process. If a Checkpointer is configured, it can be saved per conversation thread and restored in later calls.

**Context:** Usually passed in by the application when calling the Agent, providing the context information needed for this run.

**Store:** Can save data across sessions. How long it can actually be saved depends on the specific Store implementation.


II. ToolRuntime — The Officially Recommended Tool Runtime Interface

In LangChain 1.x, it is recommended to use ToolRuntime Access the tool execution context.

You only need to add the following to the tool function:

runtime: ToolRuntime

When the Agent executes the tool, LangChain automatically injects the runtime object.

There is no need to add Annotated, nor do you need to have the model pass in this parameter.

Common ToolRuntime attributes

property Description
runtime.state Current Agent state
runtime.context Context of the current run
runtime.store Shared data storage object
runtime.tool_call_id Current tool call ID
runtime.config RunnableConfig runtime configuration
runtime.stream_writer Used to send custom streaming updates

Example: Reading the current Agent message count

Example

from

langchain.

tools

import

tool

,

ToolRuntime

@

tool

def

conversation_stats

(

    runtime: ToolRuntime

)

str

:

   

"""Count the current Agent's messages."""

    messages

=

runtime.

state

.

get

(

       

"messages"

,

[

]

   

)

    human_count

=

sum

(

        message.

type

==

"human"

       

for

message

in

messages

   

)

    ai_count

=

sum

(

        message.

type

==

"ai"

       

for

message

in

messages

   

)

    tool_count

=

sum

(

        message.

type

==

"tool"

       

for

message

in

messages

   

)

   

return

(

        f

"There are {len(messages)} messages in total;"

        f

"{human_count} human messages;"

        f

"{ai_count} AI messages;"

        f

"{tool_count} tool results"

   

)

In this tool,runtime.state provides the current Agent state, which usually contains messages。

Note thatruntime does not appear in the tool parameter list provided to the model.

The model only needs to know that the tool can perform conversation statistics; it does not need to understand how the Agent stores messages internally.

Call it in the Agent

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

conversation_stats

]

,

    system_prompt

=

(

       

"You are a conversation statistics assistant."

       

"When the user asks to count messages,"

       

"use the conversation_stats tool."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"Please count the messages in the current conversation."

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

If the model calls conversation_stats, and the tool can access the message state at execution time and return the statistics.

The actual number of messages depends on how many messages the Agent has produced when the tool is executed, so you cannot assume the total is always fixed.

**Note:** You cannot simply execute directly:

# 不适合作为运行时注入的测试方式

conversation_stats.invoke({})

because an ordinary tool call does not automatically provide the complete Agent runtime context.

If you need to test such a tool, you should use create_agent() or a properly configured LangGraph ToolNode executed.


III. InjectedState — The Legacy State Injection Method

InjectedState Used to mark parameters that need to be automatically injected from the Agent state.

It can still be used with LangGraph ToolNodes that support this injection mechanism, but in newer LangChain tutorials, the recommendation is to prefer ToolRuntime。

Basic syntax of InjectedState

from typing import Annotated

from langgraph.prebuilt import InjectedState



state: Annotated[dict, InjectedState()]

When a tool runs through an execution node that supports state injection, LangGraph obtains the corresponding data from the current graph state.

Example: Reading the full State

Example

from

typing

import

Annotated

,

Any

from

langchain.

tools

import

tool

from

langgraph.

prebuilt

import

InjectedState

@

tool

def

get_message_count

(

    state: Annotated

[

       

dict

[

str

,

Any

]

,

        InjectedState

(

)

   

]

)

str

:

   

"""Read the current conversation message count."""

    messages

=

state.

get

(

       

"messages"

,

[

]

   

)

   

return

(

        f

"There are {len(messages)} messages in total"

   

)

Here, state is not an ordinary tool parameter filled in by the model.

The execution framework injects the current State into the corresponding parameter before the tool actually runs.

Injecting only a specific State field

InjectedState It also supports reading only a single field from the state.

For example:

InjectedState("messages")

means injecting only messages fields are read.

Example

from

typing

import

Annotated

from

langchain.

tools

import

tool

from

langgraph.

prebuilt

import

InjectedState

@

tool

def

count_messages

(

    messages: Annotated

[

       

list

,

        InjectedState

(

"messages"

)

   

]

)

str

:

   

"""Count the current conversation message count."""

   

return

f

"{len(messages)} messages in total"

Compared with injecting the entire State, this approach only reads the fields the tool needs.

But in new projects, you can usually just use:

runtime.state["messages"]

Avoid using multiple different injection parameters.


IV. Reading State Does Not Equal Modifying State

In the original text, remember_preference() only reads the state and returns text; it does not actually save user preferences into the Agent state.

If you want a tool to modify state, the official LangChain recommendation is to return Command。

Command You can declare which state fields need to be written and associate the tool call result back to the message history.

Example: Saving the current session's preferences

Example

from

langchain.

agents

import

AgentState

from

langchain.

messages

import

ToolMessage

from

langchain.

tools

import

tool

,

ToolRuntime

from

langgraph.

types

import

Command

Custom Agent state

class

CustomState

(

AgentState

)

:

    theme:

str

@

tool

def

set_theme

(

    theme:

str

,

    runtime: ToolRuntime

)

Command:

   

"""Save the interface theme of the current session."""

   

return

Command

(

        update

=

{

           

"theme"

: theme

,

           

"messages"

:

[

                ToolMessage

(

                    content

=

f

"Theme set to: {theme}"

,

                    tool_call_id

=

runtime.

tool_call_id

               

)

           

]

       

}

   

)

@

tool

def

get_theme

(

    runtime: ToolRuntime

)

str

:

   

"""Query the theme setting of the current session."""

   

return

runtime.

state

.

get

(

       

"theme"

,

"Not set"

   

)

An additional state field is defined here:

theme: str

When set_theme Return Command , you can use update to update this field.

Among these, ToolMessage must correspond to the current tool call ID.

If there are only read operations, there is no need to return a Command.

Creating an Agent that supports custom State

agent = create_agent(

    model=model,

    tools=[set_theme, get_theme],

    state_schema=CustomState,

    system_prompt="You are a user settings assistant."

)

This allows the Agent to manage custom session fields.

**Note:** State is a workflow state; it is not recommended to directly modify the runtime.state internal dictionary and assume the modification will definitely persist. Changes should be submitted through supported state update methods.

If multiple tools may update the same field simultaneously, you also need to consider parallel write conflicts and reducer configuration.


V. Checkpointer — Letting State Persist Across Calls

State does not only exist within a single invoke() call.

LangGraph provides a Checkpointer for saving conversation state.

For example, when the same user sends multiple questions in a row, you can use the same thread_id to restore previous messages and state.

Example: Saving conversation history

Example

from

langgraph.

checkpoint

.

memory

import

InMemorySaver

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

]

,

    checkpointer

=

InMemorySaver

(

)

)

Use the same thread_id for the same conversation

config

=

{

   

"configurable"

:

{

       

"thread_id"

:

"demo_session_001"

   

}

}

First Round

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"I'm learning Python."

           

}

       

]

   

}

,

    config

=

config

)

Second Round

result

=

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"What did I say I was learning earlier?"

           

}

       

]

   

}

,

    config

=

config

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Here, the following is used InMemorySaver Save conversation checkpoints.

The two calls use the same thread_id, so the second call can access the previously saved conversation history.

but InMemorySaver Data is only saved in the memory of the current Python process.

When the program exits or restarts, these records are usually lost.

If persistent storage is needed, you can use a database-backed Checkpointer.


VI. InjectedStore — The Legacy Storage Injection Method

InjectedStore Used to inject LangGraph's Store object into a tool.

Tools can use the Store to save and read long-term information such as user preferences and learning progress.

Its basic syntax is:

from typing import Annotated

from langgraph.prebuilt import InjectedStore

from langgraph.store.base import BaseStore



store: Annotated[

    BaseStore,

    InjectedStore()

]

Similar to InjectedState, InjectedStore parameters are not exposed to the model as ordinary tool parameters.

Example: Reading data from the Store

Example

from

typing

import

Annotated

from

langchain.

tools

import

tool

from

langgraph.

prebuilt

import

InjectedStore

from

langgraph.

store

.

base

import

BaseStore

@

tool

def

get_preference

(

    key:

str

,

    store: Annotated

[

        BaseStore

,

        InjectedStore

(

)

   

]

)

str

:

   

"""Read the preferences saved by the demo user."""

    item

=

store.

get

(

       

(

"demo"

,

"preferences"

)

,

        key

   

)

   

if

item

is

None

:

       

return

"Preference not found"

   

return

str

(

item.

value

)

This tool needs to be executed through an Agent or ToolNode configured with a Store.

Calling it directly:

get_preference.invoke({"key": "theme"})

does not magically obtain a Store instance.

Therefore, this approach is only suitable for demonstrating the structure of the legacy injection parameters. Below we use the officially recommended ToolRuntime to implement a complete example.


VII. ToolRuntime.store — Accessing Shared Storage

In LangChain 1.x, it is recommended to use:

runtime.store

to obtain the Store object used by the current Agent.

A Store organizes data through **namespaces (Namespace) and keys (Key)**.

For example:

store.put(

    ("users", "user_001"),

    "profile",

    {"name": "小明"}

)

Where:

When reading, use:

item = store.get(

    ("users", "user_001"),

    "profile"

)



print(item.value)

The lifecycle of InMemoryStore

InMemoryStore is an in-memory Store suitable for teaching and testing.

It allows multiple Agent calls to share data in the same Store instance, but it does not mean the data has been written to disk.

Operation InMemoryStore
Multiple calls within the same process can share data
Different sessions using the same Store instance can share data
Program restart in-memory data is usually lost
Sharing across multiple servers cannot be achieved automatically

In production, you should usually choose a persistent Store, such as a database implementation like PostgreSQL.


VIII. Complete Example: Saving User Learning Progress

Below we create an Agent that can save and read learning progress.

This example uses:

It should be noted in particular that the user ID cannot be arbitrarily specified by the model, otherwise it may cause data confusion between users.

In this example, the application provides the current user's identity context.

Complete code

Example

from

dataclasses

import

dataclass

from

dotenv

import

load_dotenv

from

langchain.

tools

import

tool

,

ToolRuntime

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

from

langgraph.

store

.

memory

import

InMemoryStore

load_dotenv

(

)

-------------------------

Defining the runtime user context

-------------------------

@

dataclass

class

UserContext:

    user_id:

str

-------------------------

Creating the Store

-------------------------

store

=

InMemoryStore

(

)

Initializing mock user data

store.

put

(

   

(

"users"

,

"user_001"

)

,

   

"profile"

,

   

{

       

"name"

:

"Xiao Ming"

,

       

"level"

:

"Beginner"

,

       

"completed_courses"

:

[

           

"HTML Basics Tutorial"

       

]

   

}

)

-------------------------

Tool 1: Reading the learning profile

-------------------------

@

tool

def

get_user_profile

(

    runtime: ToolRuntime

[

UserContext

]

)

str

:

   

"""Read the current user's mock learning profile."""

    user_id

=

runtime.

context

.

user_id

    item

=

runtime.

store

.

get

(

       

(

"users"

,

user_id

)

,

       

"profile"

   

)

   

if

item

is

None

:

       

return

"Learning profile not found"

   

profile

=

item.

value

   

return

(

        f

"Name: {profile['name']};"

        f

"Level: {profile['level']};"

        f

"Completed courses:"

        +

"、"

.

join

(

           

profile

[

"completed_courses"

]

       

)

   

)

-------------------------

Tool 2: Saving learning progress

-------------------------

@

tool

def

save_course_progress

(

    course_name:

str

,

    runtime: ToolRuntime

[

UserContext

]

)

str

:

   

"""Add a course to the current user's mock completed list."""

    user_id

=

runtime.

context

.

user_id

    namespace

=

(

"users"

,

user_id

)

    item

=

runtime.

store

.

get

(

        namespace

,

       

"profile"

   

)

   

if

item

is

None

:

       

return

"User profile does not exist, cannot save"

   

profile

=

dict

(

item.

value

)

    completed

=

list

(

       

profile

.

get

(

"completed_courses"

,

[

]

)

   

)

   

if

course_name

in

completed:

       

return

"This course is already marked as completed"

    completed.

append

(

course_name

)

   

profile

[

"completed_courses"

]

=

completed

    runtime.

store

.

put

(

        namespace

,

       

"profile"

,

       

profile

   

)

   

return

(

        f

"Mock learning progress saved: {course_name}."

        f

"{len(completed)} courses completed so far."

   

)

-------------------------

Creating the Agent

-------------------------

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

        get_user_profile

,

        save_course_progress

   

]

,

    store

=

store

,

    context_schema

=

UserContext

,

    system_prompt

=

(

       

"You are a programming learning assistant."

       

"Use the tool when the user asks about learning progress."

       

"When the user explicitly asks to mark a course as completed,"

       

"use the save tool."

       

"All data is mock data for teaching purposes."

       

"Do not claim it has been saved when no tool has confirmed success."

   

)

)

-------------------------

Calling the Agent

-------------------------

context

=

UserContext

(

    user_id

=

"user_001"

)

def

ask

(

question:

str

)

:

    result

=

agent.

invoke

(

       

{

           

"messages"

:

[

               

{

                   

"role"

:

"user"

,

                   

"content"

: question

               

}

           

]

       

}

,

        context

=

context

   

)

   

print

(

"\nUser:"

,

question

)

   

print

(

       

"AI:"

,

        result

[

"messages"

]

[

1

]

.

content

   

)

if

name

==

"main"

:

   

Querying completed courses

    ask

(

"Query my mock learning profile."

)

   

Saving progress

    ask

(

       

"Please mark the Python3 Basic Tutorial"

       

"as completed."

   

)

   

Querying again

    ask

(

"Query my completed courses again."

)

Explanation of the results

If the model calls the relevant tools correctly, the initial learning profile includes:

姓名:小明

水平:入门

已完成课程:HTML 基础教程

After marking the Python3 Basic Tutorial as completed, reading the Store again gives:

姓名:小明

水平:入门

Completed courses:

HTML 基础教程、Python3 基础教程

It should be noted that the above are expected business data changes, not fixed AI output text.

Since the Agent's tool selection is determined by the model, whether the save operation is actually performed should be judged by the data in the Store.

**Security tip:** The UserContext(user_id="user_001") in the example is a mock identity proactively provided by the application. In production, the user ID should be obtained from a server-verified login session or authentication information; you cannot directly trust arbitrary IDs submitted by users.


IX. Querying Course Data with Store in an Agent

Besides user preferences, the Store can also save shared information such as course catalogs.

Below we use the Store to save a set of mock course materials, and then query them through a tool.

Example

Example

from

langchain.

tools

import

tool

,

ToolRuntime

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

from

langgraph.

store

.

memory

import

InMemoryStore

Mock course catalog

store

=

InMemoryStore

(

)

store.

put

(

   

(

"runoob_demo"

,

"courses"

)

,

   

"catalog"

,

   

{

       

"Python3 Basic Tutorial"

:

{

           

"price"

:

"Free"

,

           

"duration"

:

"20 hours"

       

}

,

       

"Python Data Analysis"

:

{

           

"price"

:

"Mock membership course"

,

           

"duration"

:

"30 hours"

       

}

,

       

"HTML Basics Tutorial"

:

{

           

"price"

:

"Free"

,

           

"duration"

:

"15 hours"

       

}

   

}

)

@

tool

def

query_course_info

(

    course_name:

str

,

    runtime: ToolRuntime

)

str

:

   

"""Query the mock price and study duration of a specified course."""

    item

=

runtime.

store

.

get

(

       

(

"runoob_demo"

,

"courses"

)

,

       

"catalog"

   

)

   

if

item

is

None

:

       

return

"Mock course catalog does not exist"

    catalog

=

item.

value

    info

=

catalog.

get

(

course_name

)

   

if

info

is

None

:

       

return

f

"Course not found: {course_name}"

   

return

(

        f

"Course: {course_name};"

        f

"Price: {info['price']};"

        f

"Duration: {info['duration']}"

   

)

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

query_course_info

]

,

    store

=

store

,

    system_prompt

=

(

       

"You are a course advisor."

       

"Use tools when querying course information."

       

"All course materials are mock data for teaching purposes."

       

"Do not treat mock prices as real selling prices."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

(

               

"Please query the Python3 basic tutorial"

               

"and the mock course information for Python data analysis."

           

)

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

In this example, the course catalog is saved by the Store, and the tool runtime.store introduced in the previous section to read data.

If the model calls it twice separately query_course_info, it can obtain the mock information of the two courses.

**Note:** These prices, study durations, and membership attributes are demonstration data and do not represent the courses or pricing policies currently actually offered by the Runoob Tutorial website.


10. ToolRuntime.context - Getting trusted user context

In practical applications, tools often need to know which user the current request belongs to.

For example, different users' learning records should be saved in different namespaces:

("users", "user_001")

("users", "user_002")

However, the user ID should not be left for the model to fill in freely.

It is recommended to use the runtime Context, with verified identity information provided by the application.

Example

Example

from

dataclasses

import

dataclass

from

langchain.

tools

import

tool

,

ToolRuntime

@

dataclass

class

UserContext:

    user_id:

str

@

tool

def

who_am_i

(

    runtime: ToolRuntime

[

UserContext

]

)

str

:

   

"""Query the user identifier of the current request."""

   

return

(

        f

"Current user:"

        f

"{runtime.context.user_id}"

   

)

Specify when creating the agent:

agent = create_agent(

    model=model,

    tools=[who_am_i],

    context_schema=UserContext

)

Provide the Context when calling:

result = agent.invoke(

    {

        "messages": [

            {

                "role": "user",

                "content": "查询我的用户标识"

            }

        ]

    },

    context=UserContext(

        user_id="user_001"

    )

)

In this way, the model does not need to obtain the user ID as a tool parameter, and the tool can read it through the trusted runtime.

**Note:** The Context itself is not responsible for login authentication. The application must first confirm the user's identity before creating the corresponding Context.


11. InjectedToolArg - General injection parameter marker

InjectedToolArg Used to mark tool parameters that should not be generated by the language model.

It is mainly used to declare that a parameter should be provided by the program or execution framework, rather than being a normal Tool Calling parameter.

For example:

Example

from

typing

import

Annotated

from

langchain.

tools

import

(

    tool

,

    InjectedToolArg

)

@

tool

def

my_tool

(

    normal_param:

str

,

    injected_param: Annotated

[

       

str

,

        InjectedToolArg

   

]

)

str

:

   

"""Demonstrate the difference between normal parameters and injected parameters."""

   

return

(

        f

"Normal parameter: {normal_param};"

        f

"Injected parameter: {injected_param}"

   

)

print

(

    my_tool.

tool_call_schema

.

model_json_schema

(

)

)

Here, normal_param is a normal parameter provided to the model.

injected_param Pass InjectedToolArg is marked as an injected parameter, so it is not exposed as a normal model tool parameter.

But note:InjectedToolArg is only an injection marker and does not automatically create an injected value.

If there is no corresponding runtime injection logic, tool execution may still fail due to missing parameters.

Compared with implementing general parameter injection yourself, real projects usually recommend using ToolRuntime。


12. Comparison of State, Checkpointer, and Store

These three concepts are often confused, but they serve different purposes.

Comparison Dimensions State Checkpointer Store
Main purpose Save workflow state Save and restore State Store cross-session data
Typical data Messages, temporary variables Session checkpoints User preferences, learning progress
Data scope Current workflow or thread Associated with identifiers such as threads Organized by namespace and key
Across calls Depends on state management Supports session restoration Supports shared data
Persistence Depends on execution configuration Depends on the implementation Depends on the implementation

For example, an AI learning assistant might be designed like this:

State:

  当前正在讨论 Python 装饰器



Checkpointer:

  保存这段对话的历史和状态



Context:

  当前登录用户是 user_001



Store:

  user_001 已完成 Python 基础课程

Therefore:


13. Production environment considerations

When tools need to access real user data or long-term storage, security and consistency must also be considered.

1. Do not trust the user ID provided by the model

User identity should come from the server authentication system, not from tool parameters generated by the language model.

It is recommended that the application server create the runtime Context, and then runtime.context obtain the user identity.

2. InMemoryStore is not suitable for long-term storage of important data

An in-memory Store is suitable for learning and testing.

Production environments usually need a persistent implementation such as PostgreSQL to ensure data remains available after a program restart.

3. Avoid concurrent write overwrites

When multiple tools or multiple Agents modify the same learning progress record at the same time, simple read-modify-write operations may produce race conditions.

Real systems should combine database transactions, version control, or other concurrency control schemes.

4. Permission checks cannot rely only on prompts

Even if the system prompt requires querying only one's own data, it cannot replace backend permission verification.

For example, before accessing learning records, it is necessary to confirm that the current user has permission to read data under the corresponding namespace.

5. Limit the scope of data exposed to the model

State and Store may contain users' personal information, access tokens, or other sensitive data.

Tools should try to return only the fields necessary to complete the current task, avoiding handing the entire user profile or internal configuration directly to the model.


14. Frequently Asked Questions

1. Can InjectedState and InjectedStore still be used?

They can be used in LangGraph ToolNode scenarios that support the legacy injection mechanism.

But LangChain currently officially recommends using ToolRuntime, to uniformly access state, context, and storage.

2. Why can't calling tool.invoke() directly automatically obtain State?

Because automatic injection requires the corresponding Agent or ToolNode execution context.

Calling a tool directly does not automatically construct a complete Agent state.

3. Why did the tool read State but not save user preferences?

Because reading State is not the same as updating State.

To modify custom state fields, you should use a supported state update mechanism, such as returning Command。

4. Does State disappear after the Agent finishes running?

Not necessarily.

If you use a Checkpointer and continue calling the Agent with the same thread identifier, you can restore the previous state.

5. Is InMemoryStore permanent storage?

No.

Data is saved in the current Python process memory and is usually lost after the process ends.

6. Can Store and Checkpointer replace each other?

They should not simply replace each other.

Checkpointer is mainly used to save and restore session state, while Store is mainly used to read and write shared data by namespace and key.

7. What information can ToolRuntime access?

Common attributes include:

runtime.state

runtime.context

runtime.store

runtime.tool_call_id

runtime.config

runtime.stream_writer

Some newer versions also provide extended attributes such as execution information; refer to the current API Reference for details.

8. How to isolate learning progress among multiple users?

It is recommended to obtain the user ID through a trusted Context and then use a user-specific Store namespace.

For example:

namespace = (

    "users",

    runtime.context.user_id

)

At the same time, the user identity must be verified on the backend to prevent access to other users' data.

9. Does InjectedToolArg automatically create an injected value?

No.

It mainly marks that a tool parameter should not be exposed to the model. Actual injection requires the execution framework to provide the corresponding logic.

10. Do both State and Store require a persistent database?

Not necessarily.

Development and testing can use in-memory implementations, but production projects that need to retain data after a service restart should usually use database-backed Checkpointer and Store.


Summary

LangChain's tool injection mechanism allows Agent tools to access runtime data beyond model parameters.

This chapter introduces the following:

For new LangChain projects, it is recommended to prefer the following tool definition approach:

from langchain.tools import tool, ToolRuntime



@tool

def my_tool(

    keyword: str,

    runtime: ToolRuntime

) -> str:

    """演示访问工具运行时。"""



    messages = runtime.state.get(

        "messages", []

    )



    return (

        f"关键词:{keyword};"

        f"消息数:{len(messages)}"

    )

This approach is more unified and easier to extend than declaring multiple InjectedState and InjectedStore parameters separately.

**Core principle:** Let the model only be responsible for providing the business parameters needed to complete the task, while handing state, user identity, persistent storage, and permission control to the trusted program runtime.