| name | langchain-long-term-memory |
| description | Add cross-session persistent memory to LangChain agents using LangGraph stores. Use when building agents that remember user preferences, past interactions, or any data that must persist across conversations. Covers store setup (InMemoryStore, PostgreSQL), namespace/key organization, reading and writing in tools, and vector search. |
Documentation Index
Fetch the complete documentation index at: https://docs.langchain.com/llms.txt
Use this file to discover all available pages before exploring further.
Long-Term Memory in LangChain Agents
Long-term memory persists across threads/conversations, unlike short-term memory (scoped to one thread). Built on LangGraph stores — JSON documents organized by namespace (folder) and key (file).
Store Setup
Pass a store to create_agent. Use InMemoryStore for dev/testing; use a DB-backed store in production.
from langchain.agents import create_agent
from langgraph.store.memory import InMemoryStore
store = InMemoryStore()
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[...],
store=store,
context_schema=Context,
)
PostgreSQL (production):
pip install langgraph-checkpoint-postgres
from langgraph.store.postgres import PostgresStore
DB_URI = "postgresql://user:pass@host:5442/db?sslmode=disable"
with PostgresStore.from_conn_string(DB_URI) as store:
store.setup()
agent = create_agent(..., store=store)
Storage Model
store.put(namespace, key, value)
store.get(namespace, key)
store.search(namespace, filter={}, query="...")
- namespace: tuple of strings, e.g.
("users",) or (user_id, "preferences")
- key: unique string within namespace
- value: any JSON-serializable dict
Namespaces often include user/org IDs to scope data: (user_id, "memories").
Reading in Tools
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime
@dataclass
class Context:
user_id: str
@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
"""Look up stored user info."""
item = runtime.store.get(("users",), runtime.context.user_id)
return str(item.value) if item else "No info found"
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_user_info],
store=store,
context_schema=Context,
)
agent.invoke(
{"messages": [{"role": "user", "content": "What do you know about me?"}]},
context=Context(user_id="user_123"),
)
Writing in Tools
from typing_extensions import TypedDict
class UserInfo(TypedDict):
name: str
language: str
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
"""Save user info for future sessions."""
runtime.store.put(("users",), runtime.context.user_id, dict(user_info))
return "Saved."
Merge pattern (update without overwriting other keys):
@tool
def update_preference(key: str, value: str, runtime: ToolRuntime[Context]) -> str:
"""Update a single user preference."""
existing = runtime.store.get(("prefs",), runtime.context.user_id)
prefs = existing.value if existing else {}
prefs[key] = value
runtime.store.put(("prefs",), runtime.context.user_id, prefs)
return f"Updated {key}."
Vector Search (Semantic Recall)
from collections.abc import Sequence
from langgraph.store.base import IndexConfig
def embed(texts: Sequence[str]) -> list[list[float]]:
...
store = InMemoryStore(index=IndexConfig(embed=embed, dims=1536))
store.put(("memories", user_id), "mem-1", {"content": "User prefers dark mode"})
store.put(("memories", user_id), "mem-2", {"content": "User works in fintech"})
results = store.search(("memories", user_id), query="what are user's preferences?")
Key Rules
store must be passed to create_agent — tools only get runtime.store if the agent was created with one
context_schema required for user-scoped namespaces — use a dataclass with user_id; pass context=Context(user_id=...) at invoke time
InMemoryStore is ephemeral — data is lost on restart; use PostgresStore or another DB-backed store for production
store.get() returns StoreValue | None — always check for None; use .value to access the dict
store.setup() required for DB stores — call once to create tables
- Namespace design matters — include user/org IDs in namespace tuples to avoid data leakage across users
Related Resources
- Short-term memory (within a thread):
/oss/python/langchain/short-term-memory
- Memory conceptual guide (semantic/episodic/procedural):
/oss/python/concepts/memory
- LangGraph persistence & store API:
/oss/python/langgraph/persistence#memory-store
- Context engineering (using store in middleware):
/oss/python/langchain/context-engineering