◢ build log

Robust RAG: Managing Context Windows for Multi-Query Interactions

Building a robust RAG system requires a thoughtful strategy for managing context windows across multiple queries to ensure accurate, cost-effective

Retrieval Augmented Generation (RAG) systems enhance LLM responses by providing relevant external information. This helps reduce hallucinations and grounds the model in specific data. However, LLMs have finite context windows. In multi-turn conversations or when users ask follow-up questions, managing this context becomes a critical challenge. Exceeding the context window leads to truncation, loss of vital information, and degraded user experience. It also increases API costs.

The Challenge of Context in Conversational RAG

Each user query, the LLM's system instructions, and the retrieved documents all consume tokens in the context window. In a single-turn RAG interaction, this is often manageable. The system fetches documents relevant to the current query, packages them with the prompt, and sends it to the LLM. The problem escalates with multi-turn interactions. If you simply append every past query and response to the context, you quickly hit the limit. The LLM loses track of earlier parts of the conversation, or crucial retrieved documents get pushed out.

This leads to several issues:

  • Loss of Coherence: The LLM forgets previous turns, leading to disjointed or irrelevant responses.
  • Increased Cost: Sending larger contexts means more tokens processed by the LLM, increasing API costs.
  • Higher Latency: Processing larger contexts takes more time, slowing down response times.
  • Reduced Accuracy: Relevant documents from earlier turns might be dropped, leading to less accurate answers for follow-up questions.

Strategies for Multi-Turn Context Management

Effective RAG systems for conversational use cases require specific strategies to keep the context window manageable while retaining conversational coherence.

Query Rewriting for Contextual Retrieval

Instead of passing the entire conversation history to the retriever, you can rewrite the current user query to incorporate relevant past turns. This creates a more comprehensive query for the retrieval step. The LLM itself can perform this rewriting.

For example, if a user asks "What are the benefits of cloud computing?" and then "How does that compare to on-premise solutions?", the second query needs the context of the first. The system can rewrite the second query to something like: "Compare the benefits of cloud computing to on-premise solutions."

This rewritten query is then used to retrieve documents, ensuring the retriever focuses on the full intent.

import openai

def rewrite_query_with_context(history, current_query):
    messages = [
        {"role": "system", "content": "You are a helpful assistant. Rewrite the user's latest query to include relevant context from the conversation history, making it a standalone query for document retrieval. Only output the rewritten query."},
        *history,
        {"role": "user", "content": current_query}
    ]
    # This is a hypothetical call. Replace with your actual LLM client.
    response = openai.chat.completions.create(
        model="some-llm-model",
        messages=messages,
        temperature=0.0
    )
    return response.choices[0].message.content

## Example usage:
## conversation_history = [
##     {"role": "user", "content": "What is serverless computing?"},
##     {"role": "assistant", "content": "Serverless computing allows you to run code..."}
## ]
## user_input = "What are its main advantages?"
## rewritten_query = rewrite_query_with_context(conversation_history, user_input)
## print(f"Rewritten query: {rewritten_query}")

Summarizing Conversation History

Another approach is to summarize past turns of the conversation. Instead of keeping every message, you condense the key points into a concise summary. This summary then occupies a smaller portion of the context window, leaving more room for new queries and retrieved documents.

You can summarize the entire history periodically, or summarize segments of the history as the conversation progresses. The summary itself can be generated by an LLM. This is particularly useful for long-running conversations where detailed recall of every turn is not necessary for current understanding.

import openai

def summarize_history(history, max_tokens=200):
    # Combine recent history into a single string for summarization
    conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in history])

    messages = [
        {"role": "system", "content": "Summarize the following conversation concisely, focusing on key topics and decisions. Keep the summary under 200 tokens."},
        {"role": "user", "content": conversation_text}
    ]
    # This is a hypothetical call. Replace with your actual LLM client.
    response = openai.chat.completions.create(
        model="some-llm-model",
        messages=messages,
        temperature=0.0
    )
    return {"role": "system", "content": f"Conversation Summary: {response.choices[0].message.content}"}

## Example usage:
## long_history = [
##     {"role": "user", "content": "Tell me about distributed databases."},
##     {"role": "assistant", "content": "They offer scalability and fault tolerance..."},
##     # ... many more turns ...
##     {"role": "user", "content": "What about consistency models?"}
## ]
## summary_message = summarize_history(long_history)
## print(summary_message)

Dynamic Reranking with Full Context

Even after retrieving documents, their relevance might depend on the entire conversation, not just the last query. A reranker can take the initial set of retrieved documents and re-score them based on the full chat history. This ensures that documents that were highly relevant earlier in the conversation, or become relevant due to the cumulative context, are prioritized.

This approach doesn't reduce the initial retrieval set size, but it makes the selection of documents passed to the final LLM more intelligent and context-aware. You still need to manage the overall context window for the final LLM call, potentially by truncating the reranked documents.

Sliding Window Approach

For systems that prioritize recent interactions, a sliding window strategy maintains a fixed number of recent turns in the context. As new turns are added, the oldest ones are discarded. This is simple to implement but risks losing crucial information from earlier in the conversation if it falls outside the window.

This method is best suited for conversations where older context quickly becomes irrelevant or is less critical than recent exchanges.

Metadata-Driven Filtering and Retrieval

If your RAG data is well-structured with metadata, you can leverage the conversational state to filter retrieval results more aggressively. For example, if the conversation is about "product features", you might filter documents to only those tagged with product and features.

As the conversation progresses and the topic shifts, the metadata filters can dynamically change. This reduces the number of documents retrieved initially, lowering the burden on subsequent reranking or summarization steps.

Practical Implementation Considerations

When implementing context management, consider these points:

  • Token Counting: Accurately track token usage for each part of your prompt (system instructions, chat history, retrieved documents). This is essential for preventing overflows and managing costs.
  • Hybrid Strategies: Often, a combination of these methods works best. For example, use a sliding window for recent turns, summarize older turns, and rewrite queries for retrieval.
  • Evaluation: Test different strategies with real user interactions. Measure the impact on response quality, latency, and cost. It is important to find the right balance for your specific application.
  • User Experience: Design your system to gracefully handle context limits. Inform the user if the conversation history is being summarized or if older context is no longer available.

Managing context windows in multi-query RAG is an ongoing optimization task. There is no one-size-fits-all solution. Choose strategies that align with your application's specific needs for recall, cost, and latency.

Where to go from here

Start by analyzing your typical conversation flows to identify where context loss occurs. Experiment with query rewriting or summarization to improve multi-turn coherence. For complex RAG architecture design, consider expert assistance. You can learn more about building robust RAG pipelines at /rag-pipeline-consultant.

  • RAG context management
  • LLM context window
  • multi-turn RAG
  • conversational RAG
  • query rewriting
  • context summarization
  • retrieval augmentation
  • LLM cost optimization
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_