AI AgentsLangChain
How do you add long-term memory to an agent architecture?
Question 314 of 324 · Updated
On this page
- Direct answer
- 1. Start with a concrete memory contract
- 2. Architecture: separate the write path from the read path
- 3. Profiles versus collections
- Structured profiles
- Collections
- 4. Integrate LangGraph Store with a LangChain agent
- 5. Extract candidate memories, not automatic truths
- 6. Choose when memories are written
- Hot-path writes
- Background writes
- Worked capacity example
- 7. Consolidate experiences without inventing rules
- 8. Tested Python: source-grounded extraction and consolidation
- What the tests establish
- 9. Retention, provenance and privacy
- 10. Production evaluation: evaluate learning, not just retrieval
- Integration and failure testing checklist
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Add long-term memory as a separate, policy-controlled subsystem around a LangChain agent: extract candidate memories from authorized interactions, validate their type and provenance, store eligible records through a LangGraph Store or another durable repository, and supply a bounded relevant projection on future requests. Keep thread-local execution state in a checkpointer. Treat memory extraction, persistence, consolidation and retrieval as distinct operations.
Long-term memory is not the same as saving every conversation or increasing the model's context window. A good memory architecture learns useful facts and outcomes while preventing unsupported claims, unnecessary sensitive-data retention and accidental changes to executable procedures.
Earlier AI Agents #64, #66–68, #73, #79 and #279 explain memory types, consolidation and persistence concepts. LangChain #15 (#295), #31–33 (#311–313) cover store access, thread memory, cross-thread record promotion and isolation. This lesson builds a typed memory ingestion and maintenance architecture, including extraction, profile versus collection design, hot-path versus background writes and provenance-preserving consolidation. Detailed retrieval ranking and stale/conflicting memory resolution remain in #35 and #36.
1. Start with a concrete memory contract#
Suppose a fictional technical-support agent helps a customer troubleshoot a simulated application. The user explicitly confirms a preference for concise troubleshooting steps. During several completed tasks, a particular checklist helps resolve a problem. One later attempt using the same checklist fails.
A useful system can retain the user's confirmed preference, the individual verified troubleshooting outcomes and a carefully qualified observation that the checklist helped in multiple recorded cases. It must not turn those observations into a claim that the checklist always works or automatically make it mandatory for every future task.
| Memory category | Example | Suggested representation | Acceptance boundary |
|---|---|---|---|
| Semantic | Confirmed preference for concise steps | Typed profile field or fact record | Verified source and permitted purpose |
| Episodic | Checklist helped during case E-1 | Individual dated outcome record | Verified task outcome |
| Procedural | Approved troubleshooting checklist version 3 | Versioned procedure or policy artifact | Review and deployment approval |
| Short-term state | Current case identifier and pending tool call | Thread checkpoint | Valid runtime transition |
These categories describe the meaning of information, not mandatory database products. A semantic fact may live in a document record, a relational row or a structured profile. An episodic record may contain metadata and a source reference rather than a full conversation. A procedural artifact may be stored separately from user memories, particularly when it controls privileged behavior.
The same interaction can produce different memory candidates. A successful case can yield an episode, and several independently verified episodes may support a qualified semantic observation. The original outcome does not, by itself, authorize a change to a procedure.
2. Architecture: separate the write path from the read path#
The diagram is an application design, not an automatically installed LangChain feature. Configure the store, extraction workflow, admission policy, validation and projection explicitly. The read path must still verify authorization and relevance on every invocation; the next lesson covers its ranking and selection mechanics.
A useful separation of responsibilities is:
- The interaction runtime records messages and execution evidence in the appropriate thread.
- An extraction component proposes durable records from a bounded authorized source.
- An acceptance service checks the candidate against evidence and retention policy.
- A memory repository stores accepted records with provenance.
- A maintenance process consolidates eligible records and invalidates derived records when required.
- A procedure registry accepts only separately reviewed changes to executable behavior.
Keep a user-facing memory inventory where appropriate so the user can understand and correct what is retained. The user's ability to request a change is not a reason to blindly accept arbitrary generated facts or instructions.
3. Profiles versus collections#
A profile stores a compact, structured representation of known fields. A collection stores separate memory records, often with independently managed identities, timestamps and source references.
Structured profiles#
For predictable preferences or account-specific settings, a profile may contain a bounded set of fields:
JSON{ "schema_version": 1, "record_revision": 12, "preferences": { "answer_style": { "value": "concise", "source_ref": "confirmation-42" } } }
This is an illustrative application schema. It is not a required LangGraph Store format. Validate each field and its source before changing the profile. Rewriting the entire profile with a model can unintentionally remove unrelated fields. Prefer validated, field-specific patches and a version-aware commit rather than treating an LLM-generated full replacement as authoritative.
A profile is appropriate when the field vocabulary is reasonably stable and the consumer usually needs a small set of known values. It becomes harder to maintain when many independent facts, conflicting observations or source-specific histories must be represented.
Collections#
A collection of episodic records can retain separately identifiable outcomes, such as E-1 and E-2. Each record can carry its own retention deadline, source revision and verified status. Collections also support adding records without rewriting a large shared document.
| Design dimension | Profile | Collection |
|---|---|---|
| Granularity | One bounded object with known fields | Independently identified records |
| Typical workload | Stable settings and preferences | Growing observations, facts and experiences |
| Update model | Validated field patch | Insert, replace or retire a specific record |
| Provenance | Per field when important | Per record or claim |
| Growth | Must enforce a bounded schema and size | Must manage quotas and consolidation |
| Retrieval | Usually exact key | Exact key, metadata or approved semantic retrieval |
| Failure mode | Whole-profile rewrite loses facts | Duplicate or low-quality records accumulate |
A hybrid is often appropriate: a small profile for confirmed preferences, an episodic collection for verified experiences and a separate approved procedure registry. Do not put every memory in the profile merely to avoid implementing retrieval. Nor should you turn one explicit preference into dozens of duplicate vector records.
4. Integrate LangGraph Store with a LangChain agent#
Modern LangChain supports supplying a LangGraph Store to create_agent. For local experimentation, InMemoryStore provides an in-process implementation. The following illustrates separate logical collections and an exact-key memory read. It uses a trusted application context, not user-supplied namespace arguments.
PYTHONfrom dataclasses import dataclass from langchain.agents import create_agent from langchain.tools import tool, ToolRuntime from langgraph.checkpoint.memory import InMemorySaver from langgraph.store.memory import InMemoryStore @dataclass(frozen=True) class Identity: tenant: str subject: str def namespace(identity: Identity, kind: str): if kind not in ("profiles", "episodes", "semantic"): raise ValueError("Unsupported collection") return ("tenant", identity.tenant, "subject", identity.subject, kind) store = InMemoryStore() @tool def read_confirmed_style(runtime: ToolRuntime[Identity]) -> str: """Read the approved answer-style preference for this caller.""" if runtime.store is None: return "Preference unavailable." item = runtime.store.get(namespace(runtime.context, "profiles"), "style") if item is None: return "No confirmed preference." value = item.value.get("value") return value if value in ("concise", "detailed") else "Preference unavailable." agent = create_agent( model="openai:gpt-4o-mini", tools=[read_confirmed_style], checkpointer=InMemorySaver(), store=store, context_schema=Identity, system_prompt="Provide fictional troubleshooting assistance.", ) # Only the trusted admission service writes accepted records. # Synthetic demonstration record; no actual extraction or user data. identity = Identity("demo-tenant", "demo-user") store.put(namespace(identity, "profiles"), "style", { "value": "concise", "source_ref": "demo-confirmation", "schema_version": 1, })
SDK verification limitation: Python 3.13.5 was available locally; langchain, langchain_core and langgraph were absent. This integration was not executed and the model identifier is illustrative. Confirm the exact signatures, provider behavior, context propagation, record APIs and backend capabilities against a pinned release. The example assumes an authorized caller and a simplified unexpired fixture. A real read must validate schema, provenance, current eligibility, expiry and disclosure policy.
The store does not automatically inspect conversations, extract useful memories or select which records to inject into the model. Those functions belong to your application or explicitly configured memory components. An InMemoryStore instance is process-local; for durable deployments choose a supported persistent store integration such as a compatible database-backed LangGraph store, following its actual setup and migration requirements. Verify backup/restore, concurrency and retention independently.
The previous cross-conversation persistence lesson explains record revisions and atomic promotion receipts. Do not treat the simple put operation above as compare-and-set or as atomic with graph checkpoint updates. For strong consistency, use a transactional repository or verified backend mechanism.
5. Extract candidate memories, not automatic truths#
A model can extract candidate structured memories from a completed turn or verified outcome. Provide it with a defined schema and a bounded authorized source, then validate the proposal independently. A useful candidate contains:
| Field | Purpose |
|---|---|
| kind | Semantic, episodic or proposed procedural artifact |
| content | Typed fact or concise outcome |
| source_refs | References to original authorized source events |
| purpose | Why future retention and use are allowed |
| proposed_retention | Requested retention category, not an authority to set it |
| extraction_revision | Identifies the extractor and schema used |
For a structured extraction task, give the model the source text and metadata that it is allowed to inspect. Ask it to identify evidence-backed facts and clearly distinguish asserted preferences from observations. The extractor should return no candidates when nothing is eligible. Avoid prompting it to always create a memory from every interaction.
The acceptance service must not trust an extractor-generated verified flag or confirmation ID. Obtain those properties from the authoritative interaction record or service. Resolve the references and check the candidate's meaning against the sources. For strongly typed fields, a deterministic rule may be sufficient; for free-form claims, use appropriately evaluated claim-level validation or human review. A model-based verifier is not automatically ground truth.
Example decisions:
| Source event | Candidate | Decision |
|---|---|---|
| User confirms future concise answers | answer_style = concise | Accept if product policy permits |
| Model predicts checklist will succeed | Verified successful episode | Reject: prediction is not an outcome |
| Trusted service records completed case | Episode with case outcome | Accept if retention permitted |
| Tool output contains an API credential | Reusable semantic memory | Reject |
| User supplies a possible new troubleshooting procedure | Mandatory executable instruction | Review separately, no automatic approval |
| One success and one failure | Checklist always works | Reject: unsupported generalization |
For critical data, separate the exact source record from the generated narrative. A summary can be useful for human inspection, but the underlying typed outcome and provenance should remain available according to retention policy.
6. Choose when memories are written#
There are two common application patterns: write memories on the hot path while the agent is responding, or enqueue an authorized extraction job for background processing.
Hot-path writes#
Use a synchronous commit when the user explicitly expects a preference to be saved before the response is returned, or when a later step needs the newly written record immediately. The cost is extra latency and another dependency on the response path. Return a truthful result: if the write failed, do not claim the memory was saved.
A tool can call a scoped memory admission service, but do not allow the model to supply arbitrary subjects, retention deadlines or confirmation flags. Require a host-validated operation identity and current permission.
Background writes#
Background extraction is useful when the system can analyze completed tasks after responding, or consolidate a collection without delaying the interaction. The next invocation might arrive before the job commits, so define eventual visibility and do not promise immediate continuity for an uncommitted memory.
A production job can contain a stable event ID, authorized source revision, policy revision and extractor version. Prefer a reference to the original authorized source over unnecessarily copying sensitive conversation text into every job payload. At processing time, recheck that the source and retention authorization still exist. A queued job must not recreate data that the user has revoked or requested to delete.
Use a durable queue or outbox where needed, idempotent processing identities, bounded retries and protected dead-letter handling. In-process asynchronous work is not durable simply because a function is async. If a worker commits and loses its acknowledgement, reconcile the actual operation before reprocessing.
Worked capacity example#
Suppose a fictional product handles 10,000 completed interactions daily. Only 20% are eligible for extraction under its policy. An average approved extraction request uses 800 input tokens and 150 output tokens. The background extraction workload is approximately 2,000 requests and 1.9 million model tokens daily before retry, verification and consolidation costs. Running extraction on every interaction instead would use approximately 9.5 million tokens under the same assumptions. These numbers are illustrative planning arithmetic, not a provider benchmark or billing quote.
Measure candidate quality and operational cost together. A low write count can mean strong selection or poor recall; a high write count can mean useful coverage or indiscriminate retention.
7. Consolidate experiences without inventing rules#
A collection may accumulate repeated outcomes and duplicate candidates. Consolidation can normalize equivalent records, retain source references and produce carefully scoped semantic observations.
Suppose two independently recorded cases report that a checklist helped, and another reports that it failed. A defensible derived memory is "the checklist helped in multiple recorded cases." It is not "the checklist always works." The failure must remain available to later evaluation. A broader claim about effectiveness would require an appropriate denominator, comparable cases and more evidence.
Use stable source identities to avoid counting retried extraction as independent evidence. Different source IDs are necessary but not sufficient for statistical independence: two IDs may describe the same incident. Establish the actual case identity and provenance at ingestion.
A derived memory should not automatically outlive the permitted use of its underlying sources. A conservative policy takes the earliest source expiry for the derived record and recomputes from remaining eligible evidence. Other legitimate retention designs may preserve independently authorized facts under a separate basis; document the exact policy rather than assume it.
Procedural memory requires a different lifecycle. An agent can propose a revised workflow based on experiences, but a proposed procedure must go through review, tests, versioning and deployment approval. No number of successful episodes should automatically grant the model a new permission or allow an arbitrary stored instruction to become system policy.
8. Tested Python: source-grounded extraction and consolidation#
The following standard-library example implements a narrow deterministic memory admission policy. It accepts verified, retention-authorized outcomes from one subject, emits episodic records, and derives a qualified semantic observation only from at least two eligible successful cases. It retains unsuccessful episodes and never generates executable procedures.
This is a policy demonstration, not a LangGraph Store implementation, an LLM extractor or a semantic retrieval engine. The exact program was executed locally.
PYTHONfrom dataclasses import dataclass, replace import sys, importlib.util @dataclass(frozen=True) class Event: id: str subject: tuple[str, str] kind: str value: str verified: bool retain: bool expires: int @dataclass(frozen=True) class Memory: kind: str value: str sources: tuple[str, ...] expires: int class Rejected(Exception): pass def build_memory(events, subject, now): seen = set() episodes = [] for e in events: if e.subject != subject: continue if e.id in seen: raise Rejected('duplicate source identity') seen.add(e.id) if not e.verified or not e.retain or e.expires <= now: continue if e.kind == 'verified_outcome' and e.value in ('checklist_helped', 'checklist_failed'): episodes.append(Memory('episodic', e.value, (e.id,), e.expires)) successes = [m for m in episodes if m.value == 'checklist_helped'] derived = () if len(successes) >= 2: derived = (Memory('semantic', 'checklist_helped_in_multiple_recorded_cases', tuple(sorted(m.sources[0] for m in successes)), min(m.expires for m in successes)),) return tuple(sorted(episodes, key=lambda m: m.sources)) + derived s = ('tenant-a', 'user-1') e1 = Event('e1', s, 'verified_outcome', 'checklist_helped', True, True, 100) e2 = replace(e1, id='e2', expires=80) e3 = replace(e1, id='e3', value='checklist_failed') foreign = replace(e1, id='e4', subject=('tenant-b', 'user-1')) assert build_memory([], s, 0) == () assert build_memory([e1], s, 0) == (Memory('episodic','checklist_helped',('e1',),100),) assert build_memory([e1,e2], s, 0)[-1] == Memory('semantic','checklist_helped_in_multiple_recorded_cases',('e1','e2'),80) assert build_memory([e1,e2,e3], s, 0)[2].value == 'checklist_failed' assert build_memory([e1,foreign], s, 0) == build_memory([e1], s, 0) assert build_memory([replace(e1, verified=False)], s, 0) == () assert build_memory([replace(e1, retain=False)], s, 0) == () assert build_memory([replace(e1, kind='credential')], s, 0) == () assert build_memory([replace(e1, kind='procedure')], s, 0) == () assert build_memory([replace(e1, value='arbitrary text')], s, 0) == () assert build_memory([e1,e2], s, 80) == build_memory([e1], s, 80) assert build_memory([e1,e2], s, 100) == () assert build_memory([e2,e1], s, 0) == build_memory([e1,e2], s, 0) assert all(m.kind != 'procedural' for m in build_memory([e1,e2,e3], s, 0)) try: build_memory([e1,e1], s, 0) except Rejected: pass else: raise AssertionError('duplicate source accepted') print('15 checks passed') print(sys.version.split()[0], {p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})
Actual output:
15 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}| Check | Verified behavior |
|---|---|
| Empty events | No memory emitted |
| One successful episode | Preserves exact source and expiry |
| Two successful episodes | Qualified semantic memory with both source IDs and earliest expiry |
| Failed case | Retained independently |
| Foreign subject | Excluded |
| Unverified event | Excluded |
| Retention denied | Excluded |
| Credential event type | Excluded |
| Procedure event type | Excluded |
| Arbitrary outcome text | Excluded by narrow vocabulary |
| First source expires | Derived memory disappears upon reconstruction |
| All sources expire | No memory remains eligible |
| Reordered sources | Deterministic result |
| Procedure generation | No procedural record emitted |
| Duplicate source identity | Controlled rejection |
What the tests establish#
The fixtures represent trusted, independently verified events. The verified and retain flags, subject, source identity and expiry are assumed to originate from a validated host record, not a candidate emitted by a model or client. The test does not perform authentication, actual consent verification or evidence lookup. The credential check rejects a specific event category; it is not a general secret detector. The two success IDs represent distinct synthetic cases under the fixture assumptions, not statistically proven independent observations.
The function returns a new in-memory projection from eligible events. It does not physically erase any previously persisted derived record; a real maintenance job must atomically retire or rebuild dependent records, and the read path must enforce eligibility even if maintenance is delayed. The code is intentionally strict about duplicate source IDs and does not implement durable job deduplication. Real job replays should be reconciled using a stable operation identity and commit receipts as explained in #312.
Dataclass annotations do not enforce types or provenance at runtime. Validate the event schema, clock, IDs and policy verdicts before calling the function. The fixture tests exact constrained values, not natural-language extraction recall, factual entailment, store durability or actual LLM behavior.
9. Retention, provenance and privacy#
The memory repository should be purpose-bound. Record the minimum information needed for continuity, together with the provenance necessary to justify it. Avoid retaining full raw interactions as memory merely because storage is cheap. Source archives, extracted memories, embeddings, cache entries and procedure proposals each need a defined lifecycle.
A typical accepted memory record has a stable ID, scope, kind, schema version, content, source references, extraction revision, acceptance policy revision, created or observed time, and an expiry or retention class. The host assigns authoritative metadata and restricts which components may write it.
Derived records form dependencies. If an episode is deleted, a semantic observation based on that episode may need to be invalidated and regenerated. Index entries, embeddings and cached projections may also be affected. Expiry is not equivalent to physical deletion; use a verified deletion workflow with an appropriate policy for backups, audit obligations and retries.
When a user requests a correction, avoid blindly overwriting unrelated memories. Identify the affected claim, authorized source and dependent records. The next conflict-resolution lesson covers detailed precedence and freshness rules.
Privacy is particularly important for background processing. The extraction worker should not receive more information than the main task authorized, nor use a provider or region that is not approved for that data category. Record a useful extraction outcome without logging raw sensitive source text. A high-confidence inferred personal attribute is not automatically appropriate to retain. Apply product policy, purpose limitation and user controls before storing information.
10. Production evaluation: evaluate learning, not just retrieval#
Measure the memory-writing pipeline independently of the model that later consumes memory. Create ground-truth source fixtures with eligible and ineligible events, verified and unverified outcomes, repeated experiences, negative examples, deletion and expiry conditions, and proposed procedure changes.
| Metric | Interpretation |
|---|---|
| Extraction precision | Supported eligible accepted candidates divided by accepted candidates |
| Eligible-fact recall | Required eligible source facts represented divided by required eligible facts |
| Provenance accuracy | Verified source support for checked memory records |
| Duplicate rate | Repeated logical memory records under the defined identity policy |
| Prohibited-retention rate | Ineligible records incorrectly retained |
| Derived invalidation success | Dependent records correctly retired or rebuilt after source changes |
| Procedure promotion safety | No unreviewed changes become executable policy |
| Write latency | Time to acknowledged durable commit on the relevant path |
| Event-to-visibility lag | Time from eligible source event to usable committed memory |
| Downstream task success | Verified quality with memory versus a no-memory baseline |
Suppose a synthetic evaluation includes 100 eligible facts. The system stores 90 candidates, 81 of which are correctly supported and eligible. Under a one-to-one fact scoring policy, precision is 90% and eligible-fact recall is 81%. These are illustrative counts, not measured performance. If one of the nine incorrect candidates is a prohibited secret, that is a critical policy failure, not merely a small precision loss.
Compare a profile-only design, a collection-only design and a hybrid under the same task fixtures. Measure whether repeated work decreases without contaminating new tasks with previous outcomes. Evaluate write frequency, memory size, storage and extraction costs, and the downstream value of retained records. The next lesson covers retrieval relevance evaluation specifically.
Integration and failure testing checklist#
| Scenario | Expected result |
|---|---|
| Explicit confirmed preference | Eligible profile field saved and acknowledged |
| Unsupported inferred attribute | Not stored as a verified fact |
| Completed and unsuccessful tasks | Both outcomes represented faithfully when eligible |
| Retried extraction job | No duplicate independent experience |
| Whole-profile patch | Unrelated fields preserved |
| Worker crashes after commit | Actual commit reconciled without duplicate write |
| Source access revoked while queued | Pending extraction denied or canceled |
| Derived record loses necessary source | No stale derived record used |
| Expired record in index | Ineligible before model exposure |
| Proposed procedural improvement | Reviewed separately, never silently deployed |
| Persistent backend restart | Accepted records and required metadata restored |
| User deletion | Dependent projections and queued processing handled |
| SDK or extractor upgrade | Record contract and evaluation suite reverified |
Use the actual installed framework, database, worker queue and provider for deployment testing. Run both normal and adversarial fixtures; the deterministic Python test cannot establish the quality of generated memories or the guarantees of distributed storage. Record safe source aliases, accepted record types, policy revisions, rejection reasons and operational timings. Avoid unrestricted prompt and memory logs.
Interview-ready answer#
I add long-term memory to a LangChain agent by separating thread checkpoints from a typed durable memory subsystem. I use a bounded profile for stable confirmed preferences, collections for episodic outcomes and semantic facts, and a separately reviewed registry for procedures. I configure a LangGraph Store, but implement extraction, validation and lifecycle policies explicitly. I choose synchronous writes for immediate confirmed changes and durable background jobs for nonurgent extraction and consolidation. I preserve source provenance, retain negative outcomes, prevent duplicate evidence and invalidate derived records when their sources become ineligible. I never automatically promote retrieved instructions into privileged procedures. I evaluate extraction quality, retention compliance, durability and downstream task success against a no-memory baseline.
Official documentation research leads and verification status#
- LangChain long-term memory
- LangChain memory overview
- LangChain short-term memory
- LangChain agents
- LangChain runtime
- LangGraph persistence
- LangChain API reference
- Python dataclasses
Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone program was executed locally on Python 3.13.5 and passed all 15 checks. Local package inspection confirmed langchain, langchain_core and langgraph were absent. SDK integration, actual LLM extraction, durable store and background-worker behavior, semantic retrieval, provider performance, live documentation and website rendering remain unverified. The fixture uses a deterministic trusted event inventory and synthetic times, not a real customer conversation. Mermaid diagrams use standard triple-backtick fences; rendering was not tested.
References
- 1.LangChain long-term memorydocs.langchain.com
- 2.LangChain memory overviewdocs.langchain.com
- 3.LangChain short-term memorydocs.langchain.com
- 4.LangChain agentsdocs.langchain.com
- 5.LangChain runtimedocs.langchain.com
- 6.LangGraph persistencedocs.langchain.com
- 7.LangChain API referencereference.langchain.com
- 8.Python dataclassesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps