RAG with memory: retrieval that understands the conversation

RAG with memory keeps recent turns and rewrites each follow-up into a standalone question before searching. Use it for chat assistants where people say 'and that one?' instead of repeating themselves.

RAG with memory in 60 seconds

  • What: keep recent turns, rewrite each follow-up into a standalone question (called condensing), then retrieve and answer as in simple RAG.
  • Optional extra: also retrieve from long-term memory, such as saved user preferences or earlier summaries.
  • Best for: chat assistants, support conversations, and any product where users refine their questions over several turns.
  • Costs: one extra model call per turn for the rewrite, plus the work of storing and expiring memory.
  • Risks: stale or wrong memory, a rewrite that changes the meaning, and the privacy of stored conversations.

Where this type fits

RAG with memory is a single-pass type, like naive and simple RAG. It still retrieves once and generates once per turn. What changes is the input to the search: instead of the raw message, the search receives a question that already contains the context of the conversation. The overview of RAG types places it alongside the other single-pass designs.

The problem it solves

Imagine a customer chatting with an assistant. They ask, 'What is the warranty on the Ridge 2 tent?' and get a good answer. Then they type, 'And the footprint?' A search step that receives only those three words has no tent in it. It might return a page about footprint tracking in a mobile app, or a footprint guide for a different product. The model then answers confidently about the wrong thing.

The cause is that retrieval is stateless. Each call to the search index stands alone, while human conversation depends on what came before. Pronouns ('it', 'that one'), ellipsis ('and the footprint?'), and corrections ('no, the larger size') all lean on earlier turns. A model can resolve them if it sees the history, but the search step cannot, because it only sees the query text.

A familiar analogy is a shop assistant who is replaced every minute. Each new assistant is skilled, but you have to start from scratch. Memory is the handover note. It keeps the thread, so the follow-up is searched as 'What is the footprint of the Ridge 2 tent?' and lands on the right page.

How it works

  • Store the turns: keep the last few user and assistant messages for the session. This is short-term memory.
  • Condense: if there is history, ask a model to rewrite the new message as a standalone question, replacing pronouns and filling in dropped details. If there is no history, skip this step.
  • Retrieve: search the index with the standalone question, exactly as in simple RAG. Optionally also search long-term memory, such as saved preferences, using the same question.
  • Generate: build the prompt from the retrieved documents, the recent turns, and the original message. The model may read the history for tone and detail, but facts should come from the retrieved sources.
  • Update memory: append the new turn. When the history grows past a budget, summarise the oldest turns into a short note and drop the raw text.
  • Expire: delete memory by rule (session end, a time limit, or a user request).
History feeds the rewrite before search, and each answer is saved for the next turn.

Two kinds of memory appear in the diagram, and it helps to keep them apart. Short-term memory is the running transcript of this conversation. It is cheap, exact, and disposable. Long-term memory is information that should survive across sessions, such as 'this user camps in winter' or a summary of a previous support case. It needs a store, a way to retrieve it, and rules for correcting and deleting it. The memory types page covers these in depth.

The condense step is the heart of the type. It does not answer anything. It only rewrites. A good rewrite keeps the user's meaning, adds the missing subject, and leaves everything else alone. A bad rewrite adds assumptions, such as picking a product the user never mentioned, and then the search faithfully retrieves the wrong thing.

A worked example

Acme Outdoors runs a chat assistant. A customer, signed in, holds a three-turn conversation.

  • Turn 1, user: 'What is the warranty on the Ridge 2 tent?' There is no history, so condensing is skipped. Retrieval finds the Ridge 2 warranty page. The answer says it covers manufacturing defects for 2 years.
  • Turn 2, user: 'And the footprint?' History now holds turn 1. The condense step outputs: 'What is the footprint size of the Ridge 2 tent?' Retrieval finds the Ridge 2 specification page. The answer gives the dimensions with a citation.
  • Turn 3, user: 'Is it cheaper than the Ridge 3?' The condense step outputs: 'Is the Ridge 2 tent cheaper than the Ridge 3 tent?' Retrieval pulls both product pages, since the standalone question names both. The answer compares the two prices.
  • Long-term memory: at the end of the session the system saves a short note, 'asked about Ridge 2 and Ridge 3 tents'. Next week, the assistant can offer to continue. The user can see and delete the note from their settings.
What the condense step sees and returns (illustrative) (python)
history = [
    {'role': 'user', 'text': 'What is the warranty on the Ridge 2 tent?'},
    {'role': 'assistant', 'text': 'It covers manufacturing defects for 2 years [1].'},
]
new_message = 'And the footprint?'

# Condense output (what retrieval receives instead of the raw message):
standalone = 'What is the footprint size of the Ridge 2 tent?'

Notice that the generation step still sees the real conversation. Only the search sees the rewritten question. That keeps the reply natural, while giving retrieval the precision it needs.

Building it

The code below keeps a small window of turns, condenses when there is history, retrieves, answers, and stores the turn. condense_llm, embed(), vector_store, and llm are placeholders. The rewrite is a separate, cheap model call with a strict instruction.

RAG with a sliding window and a condense step (illustrative) (python)
# Illustrative only. condense_llm, llm, embed() and vector_store are placeholders.

MAX_TURNS = 6          # sliding window: older turns are dropped or summarised
MIN_SCORE = 0.55
TIMEOUT_SECONDS = 20

CONDENSE_RULES = (
    'Rewrite the last user message as one standalone question. '
    'Use the conversation only to fill in missing subjects. '
    'Do not add facts, products or assumptions that the user did not mention. '
    'If the message is already standalone, return it unchanged.'
)


def condense(history, message):
    if not history:
        return message  # nothing to resolve, so save a model call
    transcript = '\n'.join(t['role'] + ': ' + t['text'] for t in history[-MAX_TURNS:])
    prompt = CONDENSE_RULES + '\n\n' + transcript + '\nuser: ' + message
    rewritten = condense_llm.generate(prompt, timeout=TIMEOUT_SECONDS)  # placeholder
    # Guard: a runaway rewrite is worse than the raw message.
    if not rewritten or len(rewritten) > 3 * len(message) + 200:
        return message
    return rewritten.strip()


def retrieve(question, user):
    hits = vector_store.search(vector=embed(question), top_k=5,
                               filter={'audience': user.allowed_audiences})
    return [h for h in hits if h.score >= MIN_SCORE]


def answer_turn(session, message, user):
    standalone = condense(session['history'], message)
    hits = retrieve(standalone, user)
    if not hits:
        reply = 'I could not find this in the documentation.'
    else:
        sources = '\n\n'.join('[' + str(i) + '] ' + h.text for i, h in enumerate(hits, 1))
        recent = '\n'.join(t['role'] + ': ' + t['text'] for t in session['history'][-MAX_TURNS:])
        prompt = ('Answer from the numbered sources only and cite them. '
                  'Use the conversation for context, not as a source of facts.\n\n'
                  'Sources:\n' + sources + '\n\nConversation:\n' + recent +
                  '\n\nUser: ' + message)
        reply = llm.generate(prompt, timeout=TIMEOUT_SECONDS)  # placeholder

    session['history'] += [{'role': 'user', 'text': message},
                           {'role': 'assistant', 'text': reply}]
    session['history'] = session['history'][-2 * MAX_TURNS:]  # bounded memory
    return {'answer': reply, 'standalone_question': standalone}

Two guards are worth copying. The rewrite length check falls back to the raw message if the rewrite looks runaway. And the answer prompt says the conversation is context, not a source of facts, which stops the model from treating its own earlier replies as evidence.

Design decisions

  • Window size: keep the last 4 to 6 turns verbatim and summarise older ones. A longer window costs tokens and increases the chance of drifting on an old topic.
  • Where memory lives: short-term memory in a session store with a time limit, and long-term memory in a separate store keyed by user. Keeping them apart makes deletion and audit simpler.
  • Rewrite model: use a small, fast model for condensing. Its output is short and the task is narrow, so latency and cost should stay low.
  • Privacy and retention: decide up front what is stored, for how long, and who can read it. Offer deletion on request, and exclude sensitive fields from long-term memory. See security.
  • Access control: memory must be scoped to the user. A shared store without scoping can leak one customer's details into another's conversation.
  • Failure handling: if the rewrite call fails or times out, fall back to the raw message and carry on. A slightly worse search beats an error page.
  • Staleness: attach timestamps to long-term entries, prefer recent ones, and let new facts override old ones, such as a changed delivery address.

Measuring it

  • Rewrite fidelity: on a set of multi-turn conversations, have reviewers label each rewrite as faithful, incomplete, or wrong. Report the share that are faithful.
  • Retrieval gain from condensing: run recall at k twice on follow-up questions, once with the raw message and once with the rewrite. The difference is what memory buys you.
  • Answer faithfulness per turn: check that claims are supported by retrieved sources and not by earlier assistant messages.
  • Long-context drift: in conversations of 10 or more turns, check whether answers start leaning on old topics. Compare accuracy by turn number.
  • Memory hygiene: count wrong or outdated long-term entries found in a sampled audit, and the share of user deletion requests honoured within the promised time.
Compare recall with and without condensing (illustrative) (python)
# cases: list of {'history': [...], 'message': str, 'source_id': str} (placeholder data)
# search_ids(text, k) returns ranked chunk ids (placeholder)

def recall_gain(cases, k=5):
    raw_hits = condensed_hits = 0
    for c in cases:
        if c['source_id'] in search_ids(c['message'], k):
            raw_hits += 1
        rewritten = condense(c['history'], c['message'])
        if c['source_id'] in search_ids(rewritten, k):
            condensed_hits += 1
    n = len(cases)
    return {'raw': raw_hits / n, 'condensed': condensed_hits / n}

When to use it, and when not to

SituationUse this type?Why
Chat assistant where users ask follow-upsYesPronouns and shortcuts make stateless retrieval fail.
Support conversations that span several turnsYesThe rewrite keeps the thread, so search stays on topic.
Returning users who expect continuityYes, with careLong-term memory helps, but needs deletion and correction tools.
One-shot search box or FAQ lookupNoThere is no history, so the rewrite adds cost without benefit.
Highly sensitive data and strict retention rulesMaybeShort-term memory only, with short expiry, and no long-term store.
Questions that need several sources or toolsNot aloneCombine with agentic RAG or advanced RAG.
Very long conversations over many topicsMaybeSummarise aggressively, or start new threads, to avoid topic drift.

Trade-offs

DimensionEffectWhat to do about it
QualityMuch better on follow-ups. Can worsen if the rewrite invents details or if old turns pull the search off topic.Constrain the rewrite, cap the window, and log both raw and rewritten questions.
LatencyAdds one small model call before retrieval on turns that have history.Use a small model, skip the call when the message is standalone, and stream the final answer.
CostExtra rewrite tokens each turn, plus history tokens in the answer prompt.Summarise old turns and bound the window.
ComplexityA session store, a memory policy, and deletion paths to build and support.Start with short-term memory only. Add long-term memory when a clear use case appears.
Failure modesStale or wrong memories, rewrite drift, leaks between users, and stored data that should have been deleted.Scope by user, add timestamps and expiry, and audit samples regularly.

Simple RAG is the stateless version. Every question stands alone, which is perfect for a search box and awkward for a chat. Advanced RAG also rewrites queries, but to improve retrieval in general (expansion, filters, synonyms), not to resolve conversational references. In practice, a chat product often combines both: condense first, then apply the advanced steps. Agentic RAG keeps state too, but over a task with several tool calls rather than a dialogue.

What this means for your role

Common mistakes

Further reading

  • Memory types, for short-term, long-term, and summary memory in AI systems.
  • Simple RAG, the stateless pipeline this type extends.

Memory lets retrieval follow the conversation. Keep it small, scoped to the user, and easy to delete, and it will earn its extra model call.

Search topics

↑↓ to move · Enter to open · Esc to close