AI Agents, Evergreen

Agent Memory Retrieval: How Short-Term and Long-Term Retrieval Differ

Cartoon robot with a magnifying glass deciding what to remember, between a live chat window and a filing cabinet archive of memories, under the headline What should it remember?

Agent memory retrieval is the work an AI agent does to bring the right information back at the right moment. A language model on its own remembers nothing between calls: everything it can use must either already be in its context window or be fetched back from storage and placed there. Short-term retrieval works with what is already in the live context, while long-term retrieval searches durable storage for episodes, facts and procedures recorded earlier. The two jobs look similar, but they use different mechanisms, fail in different ways, and need to be combined deliberately.

Short-term and long-term memory in AI agents

The starting point is the statelessness of the model. In the CoALA framework from Princeton researchers, an agent’s storage is divided into working memory and long-term memories: episodic memory for past experiences, semantic memory for facts, and procedural memory for skills and behaviour held in the model’s weights and in the agent’s code. Working memory holds the active information for the current decision cycle, including knowledge retrieved from long-term memory. In CoALA’s account, a retrieval procedure reads information from long-term memories into working memory. Nothing persists unless the application writes it somewhere and retrieves it again.

That division sets up the retrieval question. Short-term memory is the live context of the current run: the system prompt, the conversation so far, tool results, and working notes the application has added. Long-term memory is everything stored outside that run: past conversations, distilled facts, user preferences, and learned procedures. Short-term retrieval is selection and management inside a finite window. Long-term retrieval is search over stored data.

Short-term memory retrieval: working with the live context window

Short-term retrieval begins with a distinction worth keeping clear. The model uses supplied context through attention over the tokens in its window. The application decides which tokens those are. Selection, trimming and summarisation are application mechanisms that choose, drop or compress context before the model sees it. Recency and ordering are not a sequence in which the model retrieves items; they are effects on what the model can use, depending on what survived selection and what sits near the current turn.

The OpenAI Agents SDK cookbook describes this layer as session memory. A Session object stores conversation history and prepends it to each turn, so the developer repeatedly calls the runner with the same session and the SDK handles context length, history and continuity. The Responses API underneath provides basic memory support through message chaining with previous_response_id. The cookbook is explicit about its limit: what the API does not provide is automatic memory management. The session layer adds it, and the developer still chooses the policy.

The cookbook covers two policies. Trimming drops older turns and keeps the last N turns: cheap and deterministic, but it forgets abruptly, and anything older than the cutoff is absent from the active context however relevant it was, unless the application retained the original turns separately. Summarisation compresses older messages into a shorter summary injected into the history, preserving a compressed account at the cost of verbatim detail. Working notes belong in this layer too, with a qualification: an application can keep a scratchpad of working notes as ordinary text it manages itself, but it should not assume that a model-internal reasoning trace is available and reusable as context, since that depends on the model and interface.

Long-term memory retrieval: finding stored episodes and facts

Cartoon robot with a magnifying glass pulling a glowing card from a filing cabinet, with dots suggesting vector similarity search.

Long-term retrieval starts outside the window. One documented mechanism is embedding-based search. The query and the stored items are turned into embeddings, and candidates are ranked by similarity in vector space, commonly by cosine distance. A vector database holds those embeddings and returns the nearest items. This finds paraphrases and related material that exact keyword matching would miss, but similarity is not relevance: an item can be close in vector space and still be the wrong answer.

Keyword retrieval works differently. BM25 ranks stored text by exact term matches, weighted by how rare a term is and by document length. It is strong on exact identifiers and distinctive terms, and weak on paraphrase. Hybrid search runs both searches in parallel and fuses the ranked lists. The Weaviate documentation describes hybrid search as combining vector search and keyword search (BM25) to leverage the strengths of both approaches, taking into account semantic similarity and exact keyword relevance. Its alpha parameter weights the vector component: 0 is keyword only, 0.5 gives equal weight, 0.75 is the server default, and 1 is vector only. Weaviate offers relative score fusion, which normalizes each search’s scores, and ranked fusion, which scores objects by position in each list.

Another fusion method works only with ranks. Reciprocal Rank Fusion ignores the raw scores from each retriever, which are not directly comparable, and scores each document from its rank in each list. The following fragment shows the scoring rule only; it is not a complete retrieval implementation.

def rrf_score(ranks, k=60):
    return sum(1.0 / (k + rank) for rank in ranks)

In that rule, a document ranked first by one retriever contributes 1/(60 + 1), and one ranked tenth by another contributes 1/(60 + 10). The constant 60 comes from the original Cormack, Clarke and Buettcher paper at SIGIR 2009, where it was determined experimentally.

Metadata filtering and namespacing narrow the search alongside similarity ranking. LangGraph’s BaseStore holds long-term facts scoped by namespace, typically by user identity rather than by conversation thread, so a returning user in a new thread can still have stored preferences retrieved. LangMem builds on that store, organising what it stores into semantic memory (facts and preferences), episodic memory (past interactions kept as learning examples) and procedural memory (how the agent should behave, materialised by updating its system prompt). It provides tools to extract and store details into a namespace and to search that namespace for memories semantically similar to the current context. Its backends include an in-memory store whose contents are lost on restart, and a Postgres-backed store for production. Reranking is a second pass after retrieval: a cross-encoder reads the query together with each candidate and re-scores relevance, so a wide first retrieval is followed by a narrow rerank. That second pass adds latency and cost, so it is a trade-off to measure.

Short-term versus long-term agent memory retrieval compared

The comparison turns on where the information lives when it is needed. Short-term retrieval is immediate: the information is already in the window, so there is no search step. Its costs are the costs of the window itself. Every token kept in context is a token the model must process on every call, and a window filled with stale turns or irrelevant retrievals leaves less room for what matters now. Trimming and summarisation control that cost, but both remove information from the active context: a trimmed turn is absent from the history the model sees, and a summarised detail is present only in compressed form, unless the application retained the original records separately.

Long-term retrieval is deferred: the information must be found, ranked and fetched before it can be used. Its costs are the search, the embedding and storage infrastructure, and any reranking pass. Its failure modes are different. A search can return nothing relevant, return stale material as if it were current, or return items that are similar but wrong. Similarity ranking has no understanding of provenance or recency unless the design adds it through metadata, filters and scoring. A retrieved fact also carries a freshness question: it was true, or believed, when it was stored, and the world or the user may have moved on since.

Short-term retrieval therefore favours freshness and immediacy at the price of a finite window and removal of information from the active context. Long-term retrieval favours durability and coverage across sessions at the price of search quality, staleness and extra latency. Neither substitutes for the other. An agent that relies only on the window forgets everything when the run ends. An agent that performs a retrieval on every turn, as in the LangGraph/LangMem account in which memory search sits in the critical path of every turn, pays a search on each such turn and risks answering from material that no longer applies; durable storage on its own does not require a query on every turn, and the retrieval policy decides when to query it.

How information moves between short-term and long-term memory

Cartoon robot carrying a box of notes along an arrow path from a desk to an archive shelf.

Retrieval is only the read path. For long-term retrieval to work, something must write to storage in a form that can later be found. That write-back is a design decision, not an automatic side effect of a conversation. The application must decide what gets stored, in what form, and with what metadata: the raw exchange, a distilled fact, a session summary, or an example of a successful interaction. A verbatim log supports text and date search over what was actually said. A distilled fact supports semantic search over what the agent concluded, but loses the evidence behind it unless that evidence is stored alongside it.

Consolidation turns episodes into durable knowledge. The clearest published design is Generative Agents, the 2023 Stanford and Google study in which 25 simulated characters kept a memory stream of observations in natural language. Retrieval scored every memory on three factors, each normalized to a 0 to 1 range and summed: recency, decaying exponentially with a factor of 0.995 per in-game hour since the memory was last retrieved; importance, a 1 to 10 rating the model assigned when the memory was created; and relevance, the cosine similarity between the memory’s embedding and the current situation’s embedding. Only the top-scoring memories that fit into the context window were placed in the prompt. Reflection ran when the summed importance of recent memories passed 150: the agent examined the 100 most recent memories, asked high-level questions about them, retrieved relevant memories for each question, and wrote insights back into the same stream. That happened roughly two or three times per simulated day. Those numbers are design choices in one research system, not measured optima, and should be treated as starting points to tune.

MemGPT, developed into the Letta framework, gives the same movement an operating-system shape. Its virtual context management treats the context window as main memory and external storage as disk, paging information in and out through function calls. Core memory sits in context, in the system message, and the agent edits it with tools. Recall memory searches past conversation history by text or date, and archival memory is searched by embedding. Movement between layers is therefore an explicit, tool-mediated act: something must decide what to keep, what to summarise, and what to write to durable storage with enough metadata to be found again. Expiry and forgetting need the same explicit treatment, since research for this article did not verify default retention or time-to-live settings for the documented stores. Without a policy for what ages out and what is refreshed when contradicted, long-term retrieval can surface stale material with the confidence of a search result behind it.

Choosing and combining retrieval mechanisms for an agent

The choice starts with the shape of the work. A single-session task with a short conversation may need nothing beyond a session and a trimming or summarisation policy. A multi-session task, where the same user returns and expects the agent to remember decisions and preferences, needs durable storage and a search mechanism over it. A small set of facts can be kept as namespaced records retrieved by key or metadata filter. A large corpus of past interactions may be searched with embedding search, hybrid search or both, or with keyword or structured retrieval where that fits the workload, plus a way to check that the right items are recalled.

Freshness needs and tolerance for wrong recall decide how much machinery to add. Where a wrong recall is cheap, a simple vector search may be enough. Where it would mislead the user, the design may use metadata filters to scope the search, hybrid search so exact identifiers are not lost to paraphrase, and reranking as an attempt to improve relevance beyond similarity alone; which of these to use should be decided through evaluation on the builder’s own workload. Each pass adds latency, so the combination should be measured in the builder’s own environment. One guide on LangGraph and LangMem notes that LangChain publishes no retrieval-latency figures for LangMem and that memory search sits in the critical path of every turn, which is a reason to measure rather than assume.

A pattern for a multi-session support agent shows how the layers combine. The live session carries the current issue, with trimming keeping only the most recent turns verbatim and a running summary standing in for earlier turns. When the user returns, a search over the durable store, scoped to that user and filtered by recency, retrieves past issues and decisions, and a reranking pass orders them before the most relevant few are placed in context. After the session, the application writes back a distilled record of the outcome, with metadata recording the user, session and time, so the next retrieval can judge its freshness. The pattern is illustrative, not a claim about any particular product. Evaluation should be built in from the start: on the builder’s own queries and corpus, check whether the items that should be recalled are retrieved, and whether the items placed in context were the ones needed. Retrieval quality is a property of a particular corpus and workload, and should be treated as one.

Common mistakes and hard limits of agent memory retrieval

One possible failure mode is over-retrieval: flooding the window with everything a search returned, on the theory that more context must help. It does not. Irrelevant items consume the window, dilute attention over the tokens that matter, and give the model more material to draw a wrong conclusion from. The opposite mistake, under-retrieval, is quieter: the item that would have settled the question was never fetched, because the query, embedding or filter missed it, and the agent answers confidently from what it has. Both look like reasoning failures. Both are retrieval failures.

Stale memory is the next trap. A retrieved fact is presented as current simply because it was retrieved, with no sign of when it was stored or whether it has been superseded. Provenance and recency belong in the retrieved record and, where the user is affected, in the answer that relies on it. A design that stores facts without timestamps, sources or contradiction handling risks retrieving its own outdated conclusions as if they were evidence.

The hard limits are worth stating plainly. The context window is finite, and no window management policy removes the need to choose what to keep. Similarity search is approximate: it ranks by closeness in an embedding space, not by truth, and, in a nearest-neighbour query without a suitable rejection threshold or filter, can return the closest available item even when nothing in the store answers the question. A maximum vector distance threshold can reject candidates that are too dissimilar, while similarity alone cannot verify that a result answers the question. And no retrieval mechanism substitutes for task design. If the agent has no policy for what to store, no metadata to scope a search, and no check on what was recalled, adding a vector store adds a search step, not a memory. Agent memory retrieval works when each layer does the job it is built for: the window for what is live now, durable storage for what must survive, and explicit, measured movement between the two.