Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

Summarizing Conversations for Context Window Management

Recommended resources

Introduction

In our previous lesson, we established a robust foundation for managing an agent's working memory. We distinguished between simple pruning techniques like the sliding window and the more sophisticated active maintenance of structured session_notes. We concluded that while pruning is necessary, simply deleting old messages can lead to a form of digital amnesia, where the agent loses critical context from earlier in the conversation.

This lesson tackles that problem head-on. You will implement conversation summarization, a powerful technique for compressing message history as it approaches the model's context window limit. Instead of discarding the past, we will use an LLM to distill it into a concise summary. This acts as a form of lossy compression, preserving the semantic essence of the conversation while freeing up valuable tokens. Your goal is to build the components of a summarization engine, understand the trade-offs involved, and integrate it into our agent's state management lifecycle.


The Core Mechanism: Compressing History

At its heart, conversation summarization is a straightforward process. When the conversation history grows too long, we take a chunk of the older messages, pass them to an LLM with a specific prompt asking for a summary, and then replace that original chunk with a single, concise summary message.

This diagram illustrates the fundamental summarization loop. A subset of the chat history (2) is passed to a dedicated "Summarizer LLM" (5). The resulting summary is then used to construct a new, shorter chat history (4) for the main LLM to continue the conversation.

This diagram illustrates the fundamental summarization loop. A subset of the chat history (2) is passed to a dedicated "Summarizer LLM" (5). The resulting summary is then used to construct a new, shorter chat history (4) for the main LLM to continue the conversation.

This approach seems simple, but the engineering details are what make it robust. We need to answer three key questions:

  1. When should we trigger summarization?
  2. What part of the history should we summarize?
  3. How should we perform the summarization to maximize information retention?

Let's build a system that answers these questions methodically.


Designing a Summarization Engine

A production-grade system doesn't just summarize randomly; it uses a deliberate strategy. We can encapsulate this logic within a dedicated class, a SummarizationEngine. This engine will be responsible for deciding when and how to compress the conversation history.

The following article provides an excellent, detailed implementation of such an engine, along with different strategies or "patterns" for summarization.

The Complete Guide to Managing Conversation History in ...

This article offers a deep dive into advanced history management, with a section dedicated to building a summarization engine from first principles.

Focus your attention on Section 4: Progressive Summarization Strategies. Read the entire section carefully. Pay close attention to: The should_summarize method, which outlines various trigger conditions (token threshold, turn count, etc.). The create_layered_summary method. Analyze how it uses different prompts to create summaries of varying detail (from ultra_compact to detailed). This is a key technique for controlling the compression ratio. The create_rolling_summary method. This is a more efficient approach that updates an existing summary with new information, rather than re-summarizing from scratch. The Summarization Patterns at the end of the section, which show how to apply these methods (e.g., Token-Budget Summarization).


Implementing Summarization Strategies

Drawing from the principles in that article, let's outline the core components of our SummarizationEngine.

1. Trigger Conditions

Summarization is an extra LLM call, which adds latency and cost. We should only do it when necessary. Common triggers include:

  • Token Threshold: The most direct trigger. When the total token count of the message history exceeds a certain percentage (e.g., 75%) of the model's context window.
  • Message Count: A simpler proxy for token count. Summarize after every N messages.
  • Time Interval: For long-running but potentially idle agents, summarizing every X minutes can help consolidate state.

Your background in event-driven architectures is relevant here; you can think of these as events that trigger a "compaction" job on the agent's state.

2. Summarization Techniques

Once triggered, we have choices in how we summarize.

Rolling Summary: This is an efficient and elegant pattern. Instead of re-reading a long list of old messages, we maintain a running summary.

  • Turn 1-10: Raw messages.
  • Turn 11: History is too long. We create a summary of turns 1-10. The history becomes [summary_of_1_10, message_11].
  • Turn 12: We provide the LLM with the previous summary and message_11, asking it to create an updated summary that incorporates the new information. The history becomes [updated_summary_of_1_11, message_12].

Layered Summary: This technique, also from the article, involves creating summaries at different levels of granularity. You might have a 20-token "title" for the conversation, a 100-token paragraph summary, and a 500-token detailed summary. This allows the system to choose the appropriate level of detail to inject into the context based on the current task's needs.

The following diagram provides a high-level view of how progressive, layered summarization fits into a larger history management architecture.

This architectural diagram shows "Progressive Summarization" as a key component. Notice the flow from a "Full Conversation" down to an "Ultra Compact" summary, with various triggers controlling the process. This aligns with the layered approach we're discussing.

This architectural diagram shows "Progressive Summarization" as a key component. Notice the flow from a "Full Conversation" down to an "Ultra Compact" summary, with various triggers controlling the process. This aligns with the layered approach we're discussing.

3. Putting it into Code

Let's draft a Python class for our SummarizationEngine. This implementation will focus on the token-budget trigger and the rolling summary pattern.

from typing import List, Dict, Any

# Assume AgentMessage and an LLM client exist
# from our_agent_framework import AgentMessage, llm_client

class SummarizationEngine:
    def __init__(self, model: str, context_window_size: int, summarization_threshold: float = 0.75):
        self.model = model
        self.context_window_size = context_window_size
        self.summarization_trigger_tokens = int(context_window_size * summarization_threshold)
        # In a real system, you would use a proper tokenizer like tiktoken
        self._tokenizer = lambda text: len(text.split()) 

    def _get_token_count(self, messages: List[Dict[str, Any]]) -> int:
        """A placeholder for accurate token counting."""
        total_tokens = 0
        for msg in messages:
            total_tokens += self._tokenizer(msg.get("content", ""))
        return total_tokens

    def _create_summary(self, text_to_summarize: str, existing_summary: str = None) -> str:
        """Calls the LLM to generate or update a summary."""
        if existing_summary:
            prompt = f"""
            Below is an existing summary of a conversation and the most recent messages.
            Your task is to create a new, updated summary that incorporates the new messages into the existing summary.
            Do not lose key details from the existing summary.

            EXISTING SUMMARY:
            {existing_summary}

            NEW MESSAGES:
            {text_to_summarize}

            UPDATED SUMMARY:
            """
        else:
            prompt = f"""
            Summarize the following conversation. Be concise, but do not lose critical information,
            such as IDs, user preferences, or key decisions.

            CONVERSATION:
            {text_to_summarize}

            SUMMARY:
            """
        
        # In a real implementation, you'd call your LLM client here
        # response = llm_client.complete(prompt=prompt, model=self.model, max_tokens=300)
        # return response.text
        
        print(f"[SummarizationEngine] Summarizing {self._tokenizer(text_to_summarize)} words...")
        return f"This is a new summary of the conversation that happened. The last message was: {text_to_summarize.split()[-5:]}"


    def compact_history(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        Checks if the history needs compaction and performs it if necessary.
        Returns the compacted message history.
        """
        token_count = self._get_token_count(messages)

        if token_count < self.summarization_trigger_tokens:
            return messages

        print(f"[SummarizationEngine] History has {token_count} tokens, exceeding threshold of {self.summarization_trigger_tokens}. Compacting...")

        # Find where the existing summary is, if any
        summary_index = -1
        for i, msg in enumerate(messages):
            if msg.get("role") == "system" and "summary of the conversation" in msg.get("content", "").lower():
                summary_index = i
                break
        
        if summary_index != -1:
            # Rolling summary: Summarize messages that came *after* the last summary
            existing_summary = messages[summary_index]['content']
            messages_to_summarize = messages[summary_index + 1:]
            
            text_to_summarize = "\n".join([f"{m['role']}: {m['content']}" for m in messages_to_summarize])
            new_summary_content = self._create_summary(text_to_summarize, existing_summary=existing_summary)
            
            # The new history is just the updated summary
            # We will append new messages to this in the main loop
            compacted_messages = [{"role": "system", "content": new_summary_content}]

        else:
            # First-time summary: Keep the first message (often the user's initial prompt) and the last few messages for immediate context.
            # Summarize the middle part.
            if len(messages) < 5: # Not enough to summarize
                return messages

            first_message = messages[0]
            recent_messages = messages[-3:]
            messages_to_summarize = messages[1:-3]

            text_to_summarize = "\n".join([f"{m['role']}: {m['content']}" for m in messages_to_summarize])
            summary_content = self._create_summary(text_to_summarize)
            
            summary_message = {"role": "system", "content": summary_content}
            
            compacted_messages = [first_message, summary_message] + recent_messages

        print(f"[SummarizationEngine] Compaction complete. New token count: {self._get_token_count(compacted_messages)}")
        return compacted_messages

This class provides a concrete compact_history method that you can call from your main agent loop before making the next LLM call. It implements a hybrid strategy: it preserves the crucial first message and the most recent turns, while compressing the vast "middle" of the conversation.


Integrating and Observing Summarization in Action

To see how this works in practice, the following video provides a clear code demonstration using the Semantic Kernel framework. While we are building from scratch, the concepts of setting a reduction threshold and observing the resulting token savings are universal.

Context engineering for AI agents

This Microsoft Developer video demonstrates chat history summarization and its effect on token count.

Watch the code walkthrough from the start of the demo. Focus on how they define reducer_target_count and reducer_threshold. Observe the console output where it announces "History reduced" and shows the generated summary. The graph at the end, which plots token count over time, visually confirms the effectiveness of the technique.

As the video demonstrates, the result is a saw-tooth pattern in your context token count: it grows steadily with each turn, then drops sharply when summarization is triggered, preventing it from ever hitting the hard limit of the context window.

Finally, it's crucial to be aware of the engineering pitfalls. Summarization is a powerful tool, but if misused, it can degrade agent performance.

How to Create Context Window Management

This article provides practical advice and highlights common mistakes when managing context.

Please read the sections on Common Pitfalls and Key Takeaways. The advice here is invaluable for building a production system. Pay special attention to the warnings about "over-aggressive compression" and "not accounting for response tokens."


Conclusion

In this lesson, we have moved beyond simple history truncation and implemented a sophisticated compression strategy. By using an LLM to summarize older parts of a conversation, we can build agents that have a seemingly infinite memory, allowing for long, coherent interactions that would otherwise be impossible.

Your key takeaways are:

  • Summarization is Lossy Compression: It's a trade-off between preserving perfect historical detail and managing the finite context window. The goal is to retain semantic meaning, not every word.
  • Triggers are Essential: Summarization should be a deliberate, triggered process based on metrics like token count or message history length to balance performance and cost.
  • Summarization Strategies Vary: You can implement simple one-off summaries, more efficient rolling/incremental summaries, or complex layered summaries depending on your application's needs.
  • It's a System Component: The SummarizationEngine should be a well-defined part of your agent's architecture, working in concert with the state management and agent loop.

So far, we've focused on managing the agent's state in memory. But what happens if the process hosting our agent crashes during a multi-hour task? The entire state, including our carefully constructed summaries, would be lost. In our next lesson, we will address this by designing and implementing state checkpointing, allowing us to persist the agent's progress to durable storage and resume tasks after failures.