AI AgentsLangChain

How do you retrieve relevant memories at runtime?

Question 315 of 324 · Updated

On this page

Direct answer#

Retrieve memories through a scoped LangGraph Store query, rather than injecting every stored record into an agent's prompt. Use exact-key retrieval for known facts, such as a confirmed profile setting. For open-ended experiential questions, enable semantic indexing and call store.search with an authorized namespace, a task-specific query and supported metadata filters. Rerank eligible candidates, remove redundant evidence, and fit the selected records into a measured context budget before model exposure.

Relevance is not authority. A highly similar memory can be private, unsupported, inappropriate for the current task or simply a record of an unsuccessful previous attempt. Authorization and eligibility are hard constraints, not ranking weights. Retrieved text remains data rather than privileged instructions.

This lesson applies LangChain and LangGraph's memory read path. AI Agents #72 explains the general retrieval concept; #279 compares episodic and semantic memory; LangChain #32–34 (#312–314) cover persistence, isolation and memory ingestion. The RAG lessons #94, #96, #97 and #142 already explain general hybrid search, fusion, reranking and embeddings. Here the distinct objective is implementing and evaluating runtime selection of authorized agent memories, not repeating general document retrieval or the memory-writing architecture. Detailed correction, stale-memory and conflict resolution are reserved for LangChain #36.

1. Route the request to the correct memory read#

Consider a fictional technical-support agent with a confirmed preference for concise responses and several historical troubleshooting episodes.

Current taskAppropriate retrievalWhy
What answer style does this user prefer?Exact profile keyKnown identity and field; similarity is unnecessary
What happened in case E-17?Exact authorized episode IDPreserve identity rather than approximate a match
Have similar connectivity problems occurred?Semantic search over eligible episodesNatural-language descriptions can differ
Which previously approved troubleshooting procedure applies?Approved versioned procedure registryA similar old episode is not an executable policy
What is the current status of an external ticket?Authoritative live domain serviceA historical memory is not current status
General question unrelated to prior interactionsNo memory retrieval where unnecessaryAvoid irrelevant context and disclosure

A profile, collection and procedure registry can coexist. In the last lesson we chose those representations at ingestion; here we choose which representation a particular invocation should read. Do not force every user request through a vector search. The retrieval method should match the information need.

Loading diagram…

The diagram is an application pattern rather than a built-in LangGraph routing workflow. The host must implement and test the policy.

2. Configure semantic indexing in LangGraph Store#

A LangGraph Store organizes records by namespace and key. Modern implementations can support semantic indexing when configured with an embedding function or model and its actual output dimensions. The embedding maps approved searchable text to numerical vectors; a compatible search implementation compares the query representation with indexed records.

The following is an illustrative integration for a compatible modern Python release. It assumes the deployment has an already configured, approved embedding object and its verified dimension. Do not infer the dimension from an arbitrary model name or enable an unapproved external embedding service for private memory.

PYTHON
from langgraph.store.memory import InMemoryStore def create_memory_store(approved_embeddings, embedding_dimensions): return InMemoryStore(index={ "embed": approved_embeddings, "dims": embedding_dimensions, "fields": ["text"], }) # The host has authenticated the subject and validated the record. ns = ("tenant", "demo-tenant", "subject", "demo-user", "episodes") # store = create_memory_store(approved_embeddings, verified_dimensions) # store.put(ns, "e17", { # "kind": "episode", # "approved": True, # "text": "A fictional Wi-Fi reconnect resolved case E-17.", # "source_ref": "verified-case-e17", # "schema_version": 1, # }) # matches = store.search( # ns, # query="Previous Wi-Fi connection failures", # filter={"kind": "episode", "approved": True}, # limit=8, # )

Verification status: Local Python 3.13.5 is available, but langchain, langchain_core and langgraph are not installed. The SDK snippets are illustrative and unexecuted. The standalone ranking code in section 7 was genuinely executed and passed 16 checks. Confirm the exact index configuration, embedding interface, supported filter operators, search result fields and persistent backend behavior against the pinned version. No real embedding API or provider call was made.

Index a specifically approved text field instead of automatically embedding the entire record. Embedding data can expose private information to a processing service even if it is not subsequently displayed. Do not index secrets, private metadata or entire conversation payloads unnecessarily. Restrict the embedding provider, retention and processing scope according to policy.

An index's embedding model and preprocessing revision matter. Query vectors must be compatible with the index's vectors. If a model revision changes dimensions or vector semantics, rebuild or maintain a compatible versioned index rather than mixing incompatible vectors. Verify the actual similarity convention and score range; not all stores expose cosine similarity, and higher is not universally better across raw distance APIs.

InMemoryStore is process-local and useful for development. A persistent database-backed store may provide suitable indexing, but its setup, migrations, supported vector search, filter execution, synchronization and failure behavior depend on the installed implementation. Do not assume indexing in one implementation implies identical behavior in another.

3. Use namespaces and metadata as eligibility constraints#

For each request, derive the allowed namespace from trusted runtime context. A user should not be able to select another subject's namespace by putting an identifier into the natural-language search query or a tool argument.

A namespace prefix can include descendants. Searching a broad prefix such as ("tenant", "A") could include private records belonging to several subjects. Use the narrow approved prefix for the particular collection, and verify that every result lies inside the allowed scope. A namespace is an organizational convention, not a substitute for application or storage-level access control.

For the fictional episode search, the trusted namespace might be ("tenant", "A", "subject", "alice", "episodes"). Approved shared project records require a separate authorized path. Never silently widen a search to an entire tenant when a personal search returns no useful results.

ConstraintRole
Tenant and authenticated subjectMandatory scope
Collection and memory kindSelect the relevant type
Purpose and disclosure policyMandatory permitted use
Record eligibility and expiryExclude ineligible records
Source and schema validityReject malformed or unsupported evidence
Similarity and recencyRank only the eligible candidates

Backend metadata filters can help narrow results efficiently, provided their exact semantics and enforcement are verified. Do not treat a filter expression supplied by a model as an authorization policy. A user-facing tool can accept a validated query string, but the host must construct its own namespace and hard filters.

Verify that the underlying search runs within the permitted scope before sensitive records reach an external reranker, logging service or model. If the backend cannot enforce the required filter during search, use an appropriately restricted index or another reviewed retrieval design. Filtering only after exposing a global candidate list is insufficient. Filtering after an approximate search can also reduce recall if inaccessible records occupy the candidate budget.

The prior isolation lesson covers ownership and revocation. Here the read-path invariant is that unauthorized records cannot be rescued by relevance, recency or a rerank score.

4. Construct a task-specific query#

The most recent user message may be too ambiguous for search. "Did that happen before?" depends on the current task's entity and event. Use an approved subset of current state to resolve the query.

For example:

  • Original question: "Did that happen before?"
  • Authorized task state: fictional Wi-Fi reconnect failed after a configuration change.
  • Search intent: "Prior verified Wi-Fi reconnect failures after configuration changes."
  • Scope: current subject's eligible troubleshooting episodes.

Query construction should retain the entity and task constraint while excluding unrelated private details. Exact identifiers such as case E-17 should remain exact rather than be approximated by embeddings. When a required entity cannot be resolved, use a controlled clarification or an appropriate no-memory path instead of searching every stored record.

A model can propose a rewritten query, but validate its size and permitted use. The model must not determine the authorized namespace, arbitrary database filter, backend route or disclosure policy. Avoid blindly embedding the full message history, raw credentials, unrestricted attachments or hidden runtime metadata.

For several distinct subquestions, perform a bounded number of independently scoped retrievals. Combine candidates using stable memory IDs and provenance. Deduplicate repeated hits before reranking or context assembly. Protect the total query and latency budget; multiple searches may add cost without improving the task.

5. Relevance, recency and reranking#

A semantic score is a signal about similarity, not the probability that the memory is true or sufficient. An episode about Wi-Fi can be relevant even if the attempted resolution failed. An old verified lesson can be more useful than a recent unrelated event.

For cosine similarity, the dot product of the query vector and memory vector is divided by the product of their Euclidean norms. Zero vectors and incompatible dimensions are invalid. The cosine score lies between -1 and 1 for valid real vectors in exact arithmetic; implementations can differ in normalization and returned score conventions.

For one hypothetical policy, admit only eligible episodes with cosine similarity at least 0.6. For admitted candidates, calculate:

Score = 0.85 × cosine_similarity + 0.15 × recency

LaTeX

This is an illustrative policy with a 30-day decay scale, not a universal LangGraph algorithm or empirically tuned ranking formula. The similarity gate prevents a recent but unrelated record from being selected solely because it is new. Do not apply this weighted formula to incompatible backend scores without calibration.

MemorySimilarityAgeRecencyCombined score
A: matching episode1.000 days1.001.000
C: older matching episode1.0060 days0.3330.900
B: related episode0.8030 days0.500.755
N: unrelated new episode0.000 days1.00Excluded by gate

A stable preference retrieved by an exact key may not need recency-based ranking at all. Age is not the same as freshness or eligibility; a verified old episode can remain accurate as a historical record. The next lesson handles stale and conflicting factual claims.

Two-stage ranking#

Use an inexpensive candidate generator followed by a narrower reranker when the task warrants it. A reranker can incorporate the actual task, relevant metadata, evidence type and query-record relationship. General cross-encoder and fusion algorithms are already covered in the RAG curriculum.

Loading diagram…

The initial candidate count is not the final top-k. Retrieve enough eligible candidates to accommodate filtering and deduplication, subject to the latency and processing budget. Tune both values using evaluation. An arbitrarily large rerank pool can increase cost and privacy exposure. A too-small pool can lose relevant records before reranking.

If the application uses an external reranker, only pass records eligible for that processor. A reranker cannot grant access or convert unverified assertions into facts.

6. Deduplicate and budget the final projection#

Memory collections may contain an episode, its summary and a retried extraction of the same source. Including all three wastes tokens and can falsely make one observation appear independently corroborated. Use stable source or logical case identity to recognize duplicates. Do not merge distinct cases merely because their text is similar.

A source can legitimately support multiple different claims. A production deduplication key may need to include source, claim identity, entity and revision rather than only source ID. The teaching code below deliberately assumes one relevant episode per source.

Determine the memory allowance only after reserving room for current instructions, current task, required recent messages, tool definitions, output and a safety margin. Count the exact formatted projection including evidence labels and metadata. If a record's full representation cannot fit, skip it or use an explicitly approved shorter representation that preserves necessary meaning and source references. Do not arbitrarily truncate a negative observation into a success.

For example, a synthetic request might have an effective input allowance of 6,000 tokens after reserving output. The host assigns 4,200 to required non-memory input and 300 to additional overhead and safety margin, leaving 1,500 for optional memory. If a validated projection uses 1,280 tokens, 220 remain. These figures are hypothetical, and the final provider-bound request still needs its own measurement.

A greedy rank-ordered selector is a simple baseline. It may leave budget unused or fail to maximize total relevance. A diversity-aware selection method or constrained optimization can improve results for some workloads, but do not sacrifice eligibility or required evidence for numerical utility. If evidence is mandatory, do not silently drop it when the budget is insufficient.

7. Tested Python implementation: scoped ranking and selection#

The following self-contained program uses the Python standard library. It implements exact cosine scoring on synthetic two-dimensional vectors, scope and kind filtering before scoring, a recency-weighted rerank, source deduplication, deterministic tie-breaking and a greedy context allowance.

It is not a LangGraph Store implementation, embedding model, vector database, natural-language reranker or provider tokenizer. The scope, eligibility flag, age and costs are assumed to be validated by the trusted application. The exact program was actually executed on Python 3.13.5.

PYTHON
from dataclasses import dataclass, replace from math import sqrt, isfinite import sys, importlib.util @dataclass(frozen=True) class Memory: id: str scope: tuple[str, str] kind: str source: str vector: tuple[float, ...] age_days: int cost: int allowed: bool = True def cosine(a, b): if not a or len(a) != len(b) or not all(isfinite(x) for x in (*a, *b)): raise ValueError('invalid vectors') na, nb = sqrt(sum(x*x for x in a)), sqrt(sum(x*x for x in b)) if not na or not nb: raise ValueError('zero vector') return sum(x*y for x,y in zip(a,b))/(na*nb) def retrieve(records, scope, kind, query, *, budget, k=3, threshold=0.6): if type(budget) is not int or budget < 0 or type(k) is not int or k < 0: raise ValueError('invalid limits') cosine(query, query) ranked=[] for m in records: if m.scope != scope or m.kind != kind or not m.allowed: continue if type(m.cost) is not int or m.cost <= 0 or m.age_days < 0: raise ValueError('invalid metadata') sim=cosine(query,m.vector) if sim >= threshold: score=0.85*sim+0.15/(1+m.age_days/30) ranked.append((score,m)) ranked.sort(key=lambda p:(-p[0],p[1].id)) result=[]; used=0; seen=set() for _, m in ranked: if len(result)>=k: break if m.source in seen or used+m.cost>budget: continue result.append(m.id); seen.add(m.source); used+=m.cost return tuple(result),used s=('A','alice'); q=(1.,0.) a=Memory('a',s,'episode','e1',(1.,0.),0,4) b=Memory('b',s,'episode','e2',(0.8,0.6),30,3) c=replace(a,id='c',source='e3',age_days=60) d=replace(a,id='d',source='e1',age_days=1) foreign=replace(a,id='x',scope=('B','alice'),vector=(0.,0.)) other=replace(a,id='y',scope=('A','bob')) wrong=replace(a,id='p',kind='profile') blocked=replace(a,id='z',allowed=False) noise=replace(a,id='n',source='e4',vector=(0.,1.)) rows=(a,b,c,d,foreign,other,wrong,blocked,noise) def run(rs=rows, **kw): return retrieve(rs,s,'episode',q,**({'budget':11}|kw)) def reject(fn): try: fn() except ValueError: return raise AssertionError('expected rejection') assert abs(cosine(q,(0.8,0.6))-.8)<1e-12 assert run()==(('a','c','b'),11) assert run(tuple(reversed(rows)))==run() assert run(budget=7)==(('a','b'),7) assert run(budget=3)==(('b',),3) assert run(budget=0)==((),0) assert run(k=1)==(('a',),4) assert run(k=0)==((),0) assert run(threshold=.9)==(('a','c'),8) assert run((foreign,other,wrong,blocked,noise))==((),0) assert run((a,d))==(('a',),4) assert run((replace(a,id='b',source='e5'),a))==(('a','b'),8) reject(lambda:run((replace(a,vector=(0.,0.)),))) reject(lambda:run((replace(a,vector=(1.,)),))) reject(lambda:run((replace(a,cost=0),))) reject(lambda:run(budget=-1)) print('16 checks passed') print(sys.version.split()[0],{p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})

Actual local output:

16 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}
Executed checkObserved behavior
Known cosine result0.8 within numerical tolerance
Full fixtureA, C, B selected, total cost 11
Reverse input orderingSame selected IDs and cost
Budget 7A and B selected
Budget 3Only B fits
Zero budgetNo memory
k = 1Highest ranked A
k = 0No memory
Higher thresholdA and C
Foreign, wrong-type, disallowed and unrelated onlyNo memory
Two copies of source e1Only A selected
Equal scoresStable ID order
Eligible zero vectorRejected
Eligible incompatible dimensionsRejected
Invalid zero costRejected
Negative budgetRejected

Interpret the budget trace#

A costs four units, C costs four, and B costs three. The newer duplicate D has source e1, so it is redundant once A is retained. With an allowance of seven, A fits; D is skipped by source identity; C is too expensive for the remaining three units; B fits exactly. Unlike a strict conversational-history suffix, optional memory selection may skip an oversized independent record. Required evidence would need a separately protected admission rule.

The foreign record deliberately has a zero vector. It is filtered before the cosine function can reject it. This checks the local function's evaluation order, not an actual backend's authorization or index execution plan. No real tenant data was used.

Complexity and limitations#

For n input records, m eligible candidates and d vector dimensions, the baseline scans n records, computes roughly O(m*d) similarity work and sorts qualifying candidates in O(m log m) worst case. It materializes ranked candidates in memory. A production vector index may reduce search work, but its approximate recall, filters and cost must be measured.

The code uses small, bounded finite vectors and positive synthetic cost units. It does not implement robust numerical normalization for extreme floating-point magnitudes, general validation of thresholds or ages, duplicate record-ID validation, live authorization, actual expiry checks, semantic embeddings or token counting. It assumes immutable trusted records with a unique ID and stable logical source. Dataclass annotations alone do not enforce these assumptions. A real implementation must validate those fields, measure formatted context and use actual provider-compatible vectors.

The allowed flag is a trusted fixture verdict, not a user- or model-supplied permission. The function returns IDs, not model-facing text. A separate authorized fetch and projection must resolve the selected IDs without substituting another revision or leaking fields. The greedy selector is not an optimal knapsack solver and does not claim to maximize total relevance. It handles optional memories only.

8. Integrate retrieval into the agent runtime#

Choose where retrieval belongs based on the task.

A known preference may be fetched by trusted host code or middleware before the first model call. A task-specific memory search tool allows the model to request evidence only when needed. For a multi-step agent, refresh retrieval when the objective or relevant entity changes, rather than automatically requery on every tool loop.

The following illustrative tool demonstrates a search boundary. The approved service encapsulates store search, independent authorization, eligibility, reranking, formatting and budget enforcement. This avoids exposing a raw store search interface to the model.

PYTHON
from dataclasses import dataclass from typing import Protocol from langchain.tools import tool, ToolRuntime from langchain.agents import create_agent class MemoryReader(Protocol): def search_episodes(self, tenant: str, subject: str, query: str, *, budget: int) -> str: ... @dataclass(frozen=True) class RequestContext: tenant: str subject: str reader: MemoryReader @tool def recall_episodes(query: str, runtime: ToolRuntime[RequestContext]) -> str: """Return bounded eligible fictional troubleshooting evidence.""" if not isinstance(query, str) or not query.strip() or len(query) > 500: return "Unsupported memory query." ctx = runtime.context return ctx.reader.search_episodes(ctx.tenant, ctx.subject, query, budget=600) # agent = create_agent( # model="openai:gpt-4o-mini", # tools=[recall_episodes], # context_schema=RequestContext, # store=approved_store, # )

This snippet is unexecuted. The reader interface is an application dependency, not a LangChain API or a provided implementation. It must implement the actual store access, current authorization, bounded query execution, error handling and projection guarantees described above. Its budget argument is a host-selected illustrative token allowance; the service is responsible for enforcing actual formatted size. The live service handle belongs to invocation context, not persistent graph state. Confirm the installed context schema and ToolRuntime interfaces.

Alternatively, a tool can use runtime.store.search directly, as long as it performs the same checks and sends only a reviewed projection. Do not pass the entire search-result object, arbitrary stored text or embedding vectors to the model. A memory result should be identified by source and kind, with any relevant caveat. Treat instructions contained in recalled text as untrusted information.

Loading diagram…

No eligible memory is a valid outcome. Distinguish that condition from backend failure, authorization denial and an insufficient evidence budget. A harmless optional preference can often fall back to a neutral default. A task requiring verified prior evidence may need a controlled limitation or an authoritative service lookup. Never broaden search permissions to compensate for a miss.

9. Evaluate the full retrieval funnel#

Create a labeled dataset of current task requests, authorized memory inventories, required relevant memory IDs or logical evidence units, and expected no-memory outcomes. Include near-duplicate records, failed outcomes, ambiguous follow-ups and foreign-scope distractors. Evaluate authorized candidate generation, reranking, budget selection and final model behavior independently.

MetricWhat it measures
Candidate Recall@kRelevant eligible memories found before final selection
Precision@kRelevant selected memories divided by selected memories, with a documented empty-result convention
Final evidence recallRequired evidence surviving deduplication and budget selection
MRRMean reciprocal rank of the first relevant eligible result, zero for a miss
nDCG@kRanked usefulness under graded relevance judgments
No-memory accuracyAppropriate abstention on queries without useful eligible records
Duplicate evidence rateRepeated logical sources or claims in final projection
Policy violation rateUnauthorized or ineligible records exposed at any protected boundary
Budget complianceActual model-facing request fits the effective limit
Downstream verified successTask correctness with memory compared with baseline

For example, if a query has four eligible relevant memories and the first five candidates include three of them, candidate Recall@5 is 3/4 = 75%. If the final projection has two relevant memories and one irrelevant memory, its precision is 2/3 and its recall is 2/4. A candidate-stage metric alone misses the final selection loss. These are constructed figures, not measured performance.

Report metrics for eligible records only; foreign records are never labeled relevant for an unauthorized request. Track unauthorized exposure separately as a critical failure. A high relevance score cannot compensate for an isolation violation.

Use baselines such as exact-key only, semantic only, semantic plus metadata/reranking, and no optional memory. Hold the task set, approved model profile, candidate limits and scoring policy consistent for meaningful comparison. Slice results by memory kind, query ambiguity, language, age, source diversity and available context budget. Tune threshold and recency weight on a development split, then evaluate on held-out tasks to avoid optimistic results.

10. Production verification and operational controls#

Integration fixtureRequired outcome
Exact known profile or episode IDCorrect authorized record, not a semantic substitute
Ambiguous follow-upQuery resolves using approved current task context
Unrelated queryAppropriate empty result
Cross-tenant high-similarity canaryNever reaches unauthorized reranker, model or response
Wrong collection or ineligible recordExcluded before protected use
Metadata filter with approximate indexActual filter semantics and eligible recall established
Repeated logical episodeOne evidence unit unless distinct claims are needed
Old but relevant episodeNot suppressed solely because it is old
Failed historical outcomePreserved as failed, not promoted to a success
Oversized optional memorySkipped or approved projection, no misleading truncation
Required memory does not fitControlled incomplete outcome
Embedding model or index revision changesCompatible query/index pair and re-evaluated quality
Backend outageBounded failure and truthful fallback
Revocation between search and fetchCurrent disclosure eligibility enforced
Tool loop repeats same queryBounded retrieval and policy-safe caching
Concurrent usersNo shared mutable scope or private result contamination

Test actual SDK search, embedding generation, backend filters, index update visibility, result representation and token accounting separately from the deterministic fixture. Use synthetic canaries in controlled integration environments. Measure p50 and p95 latency for candidate search, reranking, final projection and end-to-end task completion. Include embedding, index, reranking and model context costs when comparing designs.

Track candidate count, selected count, deduplication and budget-drop counts, no-memory outcomes, index/profile revision, normalized failure reason and policy violations. Avoid raw private queries or memory payloads in routine logs. Scope caches by the current eligible identity, query, policy and relevant record/index revisions. Recheck access when cached results are consumed.

When a source becomes ineligible or a record changes, verify that the index and cache cannot keep supplying obsolete data. The next lesson covers detailed freshness, correction and conflict handling. Runtime selection must not assume that a stored score or an earlier authorization verdict remains valid indefinitely.

Interview-ready answer#

I route the task to exact-key lookup or a scoped LangGraph Store semantic search depending on the information needed. I configure a compatible embedding index over approved fields and derive namespaces and metadata filters from trusted runtime context. I construct a bounded query from the current task, gate candidates by eligibility and relevance, optionally rerank by calibrated similarity and recency, deduplicate logical sources and fit the final projection into the model's actual context budget. I keep retrieved memories as labeled data, not instructions. I test candidate recall, final evidence retention, no-memory behavior, security and downstream verified task success, and never widen the authorized scope to recover a retrieval miss.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone Python program was executed locally and printed 16 checks passed on Python 3.13.5. Package inspection confirmed langchain, langchain_core and langgraph were absent. Actual SDK configuration and search, embedding generation, vector index and filtering semantics, external reranking, real token accounting, live authorization, production retrieval quality, current documentation and website rendering remain unverified. The test uses synthetic vectors, eligibility decisions, metadata and costs. All Mermaid diagrams use standard triple-backtick fences; rendering was not tested.

References

  1. 1.
    LangChain long-term memorydocs.langchain.com
  2. 2.
    LangChain short-term memorydocs.langchain.com
  3. 3.
    LangChain toolsdocs.langchain.com
  4. 4.
    LangChain runtimedocs.langchain.com
  5. 5.
    LangGraph persistencedocs.langchain.com
  6. 6.
    LangChain API referencereference.langchain.com
  7. 7.
    Python mathdocs.python.org
  8. 8.
    Python dataclassesdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.