Guilds AI / AI Blog

,

LangChain Memory: Short-Term and Long-Term Python Setup

AI robot beside conversation bubbles, layered memory cards and a connected database.

LangChain memory lets an application retain information from earlier interactions and use it when a user returns or continues a conversation. In current LangChain agents, use a LangGraph checkpointer for conversation-specific state and a store for selected information that must remain accessible across different threads.

The two mechanisms have different purposes. A checkpointer can preserve the messages and state of a particular thread. A long-term store can hold a confirmed preference or application fact outside that thread. Neither changes the model’s trained weights. This guide uses the LangChain documentation reviewed November 29, 2026. The Python examples illustrate documented interfaces; live model and database calls have not been executed here.

What is LangChain memory?

A language model generally needs the relevant conversational context to be supplied with a request. LangChain memory organizes that context outside the model so an application can decide what to retain and what to retrieve. For persistent improvements based on verified feedback rather than conversation history alone, see our agentic learning guide.

ComponentScopeTypical use
CheckpointerIndividual threadConversation history and resumable agent state
StoreApplication-defined namespace and keyConfirmed preferences and reusable facts
Context selectionCurrent model requestChoose messages and memories relevant to the question

LangChain’s high-level agent interface uses LangGraph for execution and persistence. Our LangGraph framework guide explains how state passes through graph nodes and how the workflow can pause or resume.

Do not confuse short-term with temporary storage. Thread history can survive a process restart when a durable checkpointer is configured. Conversely, an in-memory long-term store can span several conversations in one process while losing its contents when that process stops. Scope and physical durability are separate design decisions.

Add short-term memory with a checkpointer

Prepare a Python environment

Install the framework and a compatible model integration in a virtual environment. Follow our LangChain installation guide for platform-specific setup and dependency checks. The following example assumes a supported OpenAI model identifier and credentials configured through the environment.

python -m pip install -U langchain langgraph langchain-openai

Create the agent and reuse a thread ID

Use InMemorySaver for a local demonstration. It retains checkpoints in the running process. Pass the same authorized thread identifier to subsequent invocations that belong to the same conversation.

import os
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="openai:" + os.environ["MODEL_ID"],
    tools=[],
    checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": "demo-42"}}

agent.invoke({
    "messages": [{"role": "user",
                  "content": "My project is called Northstar."}]
}, config)

result = agent.invoke({
    "messages": [{"role": "user",
                  "content": "What is my project called?"}]
}, config)
print(result["messages"][-1].content)

Set MODEL_ID to a model supported by your provider account and configure OPENAI_API_KEY through an approved secret-management mechanism. The second invocation should have access to the earlier message and may answer Northstar. The response itself is generated by the model, so it is not a deterministic assertion of storage correctness.

Inspect the saved state separately when testing. For example, in this local demonstration the agent’s get_state method can retrieve the state associated with the configuration:

snapshot = agent.get_state(config)
for message in snapshot.values["messages"]:
    print(message.type, message.content)

Use only fictional data for this kind of debugging. Printing full histories in production may expose confidential information. Create a new authorized thread identifier when starting an independent conversation. Do not accept an arbitrary thread identifier from an unauthenticated client as sufficient proof of access.

Add long-term memory with a store

A user may want an application to remember a preferred output format even when starting a different conversation. That information belongs in an approved cross-session memory record rather than being tied exclusively to an old chat.

LangGraph stores use namespace and key identifiers. The following model-free example demonstrates the underlying storage interface using a fictional user. It does not need a language model call once the relevant packages have been installed.

from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
namespace = ("demo-user-42", "preferences")

store.put(namespace, "output_format", {
    "format": "bullet points",
    "source": "explicit user preference",
})

item = store.get(namespace, "output_format")
print(item.value["format"])  # Expected: bullet points

The application can pass the store to create_agent using the store parameter. However, creating an agent with a store does not automatically make every memory available to the model. Implement a controlled retrieval step or tool that reads the appropriate namespace, selects relevant records and adds them to the current context. Provide an explicit and validated mechanism for storing new preferences.

For semantic retrieval, a store can be configured with an embedding index when supported by the selected backend. Similarity search is useful for selecting relevant prior information but should not be treated as authorization or proof that a memory is still true. Use exact key retrieval for stable, known settings.

When should a memory be written?

A simple approach is to save only preferences explicitly confirmed by the user through the application’s approved process. A more advanced system may propose facts to extract from conversations. Validate the proposal, identify its source and handle corrections or expiration. Do not allow arbitrary external documents or model-generated guesses to become trusted permanent instructions.

Manage conversation context

Saving an entire conversation is different from sending the entire conversation to a model. Longer histories consume more input tokens and may contain stale or irrelevant information. Keep the information required to interpret the current request and maintain a deliberate retention policy.

TechniqueWhen usefulImportant limitation
Trim selected messagesRecent context is sufficientEarlier constraints may be lost from model input
Summarize older turnsConversations are longSummaries may omit qualifications or introduce errors
Retrieve relevant memoriesSpecific facts matter across sessionsRetrieval may miss relevant information
Remove obsolete recordsA user corrects a stored factHistorical checkpoints and other copies may need separate treatment

Preserve valid message structure when reducing history, particularly tool-call messages and their associated tool responses. Use documented message filtering or summarization middleware rather than deleting arbitrary entries. Keep critical operational policies outside ordinary conversation memory.

A memory store can complement retrieval-augmented generation. Our guide to building RAG agents with LLMs explains how a separate knowledge base supplies authoritative information. A remembered user preference does not override a current policy retrieved from the approved source.

Choose a production persistence backend

For development, InMemorySaver and InMemoryStore provide convenient local mechanisms. For persistent applications, choose supported database-backed implementations and configure them for your deployment. LangChain documents PostgreSQL checkpointer and store integrations, and other supported backends may be suitable for different operational requirements.

RequirementDesign implication
Resume a conversation after restartUse a durable checkpointer and authorized thread IDs
Recall preferences across conversationsUse a durable store with tenant and user namespaces
Recover interrupted workflowsPreserve checkpoints and reconcile external side effects
Delete or correct remembered informationImplement retrieval restrictions, retention and deletion procedures
Operate multiple workersUse shared persistence and evaluate concurrency behavior

For PostgreSQL, the documented integration package is langgraph-checkpoint-postgres. The checkpointer and store may use separate components and setup procedures. Configure the database connection securely, run the documented setup or migrations and test backup and restoration before production use. Avoid hard-coded passwords and publicly accessible development database configurations.

Resuming a workflow is not a guarantee of exactly-once external actions. If a tool created a record before the agent was interrupted, a repeated execution may create another one unless the operation uses a stable identifier or a reconciliation check.

Memory is also distinct from caching. A cache reuses a previous computation or response; memory preserves selected context or state. Our AI agent caching best practices guide covers freshness and authorization rules for reused results.

Test memory isolation and reliability

Use a representative test matrix rather than relying on one convincing chatbot answer. Test the storage layer, the retrieval layer and the resulting model behavior separately.

TestExpected result
Same threadEarlier authorized messages available
New thread, same userOld thread messages absent unless deliberately retrieved
Different userOther user’s messages and memories inaccessible
Process restartDurable backends retain expected records
Preference correctionCurrent retrieval returns the corrected value
Unauthorized IDRequest rejected before accessing saved state
Long conversationContext stays within configured limits

A namespace and thread ID organize records; neither is an access-control system by itself. Resolve the authenticated identity on the server, verify thread ownership and derive the namespace from approved application data. Apply the same checks to memory writes, reads and deletion operations.

Treat recalled information as potentially outdated and untrusted. If an old preference conflicts with the user’s current instruction, resolve the conflict according to the application’s rules rather than blindly repeating the stored value. Test prompt injection attempts that try to make an agent remember unauthorized instructions.

If a user requests deletion, examine the actual storage implementation. Removing a current message or record does not automatically remove every historical checkpoint, trace, cache or backup. Implement and document the retention and deletion behavior appropriate to the application.

Frequently asked questions

What is LangChain memory?

It is application-managed context that can retain conversation state or selected information from past interactions. Current LangChain agents use checkpointers for thread state and stores for cross-thread memory.

Does InMemorySaver survive a restart?

No. It stores checkpoints in the running process. Use a supported durable checkpointer when state must survive a restart.

What is the difference between a checkpointer and a store?

A checkpointer preserves graph state for a specific thread. A store holds application-defined records under namespaces and keys that can be accessed across threads.

Should I still use ConversationBufferMemory?

It appears in older LangChain tutorials and legacy APIs. For a new current LangChain agent, follow the checkpointer and store interfaces documented for your installed version.

Does memory train the language model?

No. Application-level memory stores information outside the model and supplies relevant context to later requests. It does not update the model’s trained weights.