LangChain Cross-Session Storage — Store

Checkpointer solves the problem of "memory within a single conversation." But if you need to share data across different conversations—such as user preferences or learning progress—you need to useStore。


Checkpointer vs Store

DimensionCheckpointerStore
ScopeSingle conversation thread (thread_id)Across all conversation threads
Data typeAgent state snapshot (automatically managed)Arbitrary key-value data (manually managed)
Typical use casesMulti-turn conversation memoryUser preferences, knowledge base, configuration
Data organizationthread_id → checkpoint(namespace, key) → value

Basic Store Operations

Store UsageNamespace + keyto organize data in a hierarchical structure:

Example

from langgraph.store.memory import InMemoryStore

store = InMemoryStore()

# Write data: put(namespace, key, value)
# namespace is a tuple, key is a string, value is a dictionary
store.put(
    ("users", "user_001"),           # Namespace
    "preferences",                    # Key
    {                                 # Value
        "theme": "dark",
        "language": "zh-CN",
        "level": "Beginner",
    }
)

store.put(
    ("users", "user_001"),
    "progress",
    {
        "completed_courses": ["HTML Basics", "Python Basics"],
        "total_hours": 35,
    }
)

# Read data: get(namespace, key)
prefs = store.get(("users", "user_001"), "preferences")
print(f"Preferences: {prefs.value}")

progress = store.get(("users", "user_001"), "progress")
print(f"Learning progress: {progress.value}")

# Search data: search(namespace)
all_user_data = store.search(("users", "user_001"))
print(f"\n"All user data ({len(all_user_data)} items):")
for item in all_user_data:
    print(f"  {item.key}: {item.value}")

# Delete data: delete(namespace, key)
store.delete(("users", "user_001"), "preferences")
deleted = store.get(("users", "user_001"), "preferences")
print(f"\n"After deletion: {deleted}")  # None

Output:

Preferences: {'theme': 'dark', 'language': 'zh-CN', 'level': '入门'}
Learning progress: {'completed_courses': ['HTML 基础', 'Python 基础'], 'total_hours': 35}

用户的所有数据 (2 项):
  preferences: {'theme': 'dark', 'language': 'zh-CN', 'level': '入门'}
  progress: {'completed_courses': ['HTML 基础', 'Python 基础'], 'total_hours': 35}

After deletion: None

Using Store in an Agent

Pass Store to create_agent(), and all tools in the Agent can access it via InjectedStore:

Example

from dotenv import load_dotenv
load_dotenv()

from typing import Annotated
from langgraph.store.base import BaseStore
from langgraph.store.memory import InMemoryStore
from langchain.tools import tool, InjectedStore
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage

# Create a Store and preset data
store = InMemoryStore()
store.put(("example", "courses"), "catalog", {
    "Python3 Basics Tutorial": {"price": "Free", "hours": 20, "level": "Beginner"},
    "Python Data Analysis": {"price": "Member", "hours": 30, "level": "Advanced"},
    "Java Object-Oriented": {"price": "Free", "hours": 25, "level": "Advanced"},
})

store.put(("example", "users"), "user_vip_001", {
    "name": "Xiao Ming",
    "membership": "VIP",
    "joined": "2024-01-15",
})


@tool
def query_course_info(
    course_name: str,
    store: Annotated[BaseStore, InjectedStore()],
) -> str:
    """Query detailed information about courses on the EXAMPLE tutorial site.

    Args:
course_name: Course name
    """

    item = store.get(("example", "courses"), "catalog")
    catalog = item.value if item else {}

    if course_name in catalog:
        info = catalog[course_name]
        return (
            f"《{course_name}》 - Price: {info['price']},"
            f"Duration: {info['hours']} hours, Difficulty: {info['level']}"
        )
    return f"Course 《{course_name}》 not found"


@tool
def get_user_membership(
    user_id: str,
    store: Annotated[BaseStore, InjectedStore()],
) -> str:
    """Query user membership information.

    Args:
user_id: User ID
    """

    item = store.get(("example", "users"), user_id)
    if item is None:
        return f"User {user_id} not found"

    user = item.value
    return (
        f"User {user['name']}, {user['membership']} member,"
        f"Registration date {user['joined']}"
    )


model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
    model=model,
    tools=[query_course_info, get_user_membership],
    store=store,
    system_prompt="You are the course consultant for EXAMPLE.",
)

# Query course information (data comes from Store)
result = agent.invoke({
    "messages": [HumanMessage(content="How much does the Python3 Basics Tutorial cost?")]
})
print(f"Query course: {result['messages'][-1].content}")

# Query user information (data comes from Store)
result = agent.invoke({
    "messages": [HumanMessage(content="Help me look up information for user user_vip_001")]
})
print(f"Query user: {result['messages'][-1].content}")

Output:

Course query: 《Python3 基础教程》是免费的,学习时长约20小时,难度为入门级别。
User query: 用户小明是 VIP 会员,注册日期为 2024年1月15日。

Store Persistence

InMemoryStore data is lost after a program restart. For production environments, you can use persistent solutions such as PostgresStore:

Example

# Development stage
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()

# Production environment (requires PostgreSQL)
# from langgraph.store.postgres import PostgresStore
# store = PostgresStore.from_conn_string("postgresql://...")

Store Usage Recommendations

Scenarionamespace examplekey exampleDescription
User preferences("users", user_id)preferencesTheme, language, notification settings
Learning progress("users", user_id)progressCompleted courses, study duration
Knowledge base("kb", collection)doc_idDocuments, FAQ, product information
Conversation summaries("sessions", thread_id)summarySummaries of long conversations, for use in scenarios beyond Checkpointer

Checkpointer is responsible for "where the conversation is," and Store is responsible for "who the user is, what they know, and what they like." Only by using both together can you build an intelligent Agent with persistent memory.

Other extensions