本页还没有译文
本页 23 段还没译成日本語,下面显示的是英文原文。Long-term memory with MongoDB Atlas
还没翻译译自英文(docs.langchain.com)本页 23 段都还没译
Long-term memory lets your agent store and recall information across different conversations and sessions. This guide shows how to use MongoDB Atlas as the persistent store backend.
MongoDB stores memories as documents in a collection. With an Atlas Vector Search index, the same store can run semantic search over stored memories.
Tip
For a deeper dive into memory types and strategies for writing memories, see the Memory conceptual guide.
Setup
Installation
Install the store package (langgraph-store-mongodb):
pipuv
pip install -U langgraph-store-mongodb pymongouv add langgraph-store-mongodb pymongoCredentials
Set your Atlas connection string:
import getpass
import os
if not os.environ.get("MONGODB_ATLAS_URI"):
os.environ["MONGODB_ATLAS_URI"] = getpass.getpass("Enter your MongoDB Atlas URI: ")If you want automated tracing of your model calls, set your LangSmith API key:
if not os.environ.get("LANGSMITH_API_KEY"):
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"Usage
Create a MongoDBStore and pass it to create_agent. The from_conn_string context manager creates the required indexes when it opens. You do not call a separate setup() method.
import os
from langchain.agents import create_agent
from langgraph.store.mongodb import MongoDBStore
MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]
with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
agent = create_agent(
"anthropic:claude-sonnet-4-6",
tools=[],
store=store,
)Memory storage
LangGraph stores memories as JSON documents organized by namespace and key. Namespaces typically include a user or org ID to keep memories scoped.
The following example configures vector indexing so store.search can run semantic queries. Use create_vector_index_config and pass it as index_config:
import os
from collections.abc import Sequence
from langgraph.store.mongodb import MongoDBStore, create_vector_index_config
def embed(texts: Sequence[str]) -> list[list[float]]:
# Replace with an embeddings model or LangChain Embeddings instance
return [[1.0, 2.0] for _ in texts]
MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]
with MongoDBStore.from_conn_string(
MONGODB_ATLAS_URI,
index_config=create_vector_index_config(embed=embed, dims=2),
) as store:
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context)
store.put(
namespace,
"a-memory",
{
"rules": [
"User likes short, direct language",
"User only speaks English and Python",
],
"my-key": "my-value",
},
)
item = store.get(namespace, "a-memory")
items = store.search(
namespace, filter={"my-key": "my-value"}, query="language preferences"
)For more information about store operations, see the Stores guide.
Read long-term memory in tools
Tools can read from the store using the runtime parameter, which LangGraph injects automatically:
import os
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langgraph.store.mongodb import MongoDBStore
@dataclass
class Context:
user_id: str
MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]
with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
store.put(("users",), "user_123", {"name": "John Smith", "language": "English"})
@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
"""Look up user info."""
assert runtime.store is not None
user_info = runtime.store.get(("users",), runtime.context.user_id)
return str(user_info.value) if user_info else "Unknown user"
agent = create_agent(
"anthropic:claude-sonnet-4-6",
tools=[get_user_info],
store=store,
context_schema=Context,
)
agent.invoke(
{"messages": [{"role": "user", "content": "look up user information"}]},
context=Context(user_id="user_123"),
)Write long-term memory from tools
Tools can also write to the store using runtime.store.put, persisting data that survives across threads:
import os
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langgraph.store.mongodb import MongoDBStore
from typing_extensions import TypedDict
@dataclass
class Context:
user_id: str
class UserInfo(TypedDict):
name: str
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
"""Save user info."""
assert runtime.store is not None
runtime.store.put(("users",), runtime.context.user_id, dict(user_info))
return "Successfully saved user info."
MONGODB_ATLAS_URI = os.environ["MONGODB_ATLAS_URI"]
with MongoDBStore.from_conn_string(MONGODB_ATLAS_URI) as store:
agent = create_agent(
"anthropic:claude-sonnet-4-6",
tools=[save_user_info],
store=store,
context_schema=Context,
)
agent.invoke(
{"messages": [{"role": "user", "content": "My name is John Smith"}]},
context=Context(user_id="user_123"),
)