◢ build log

Keeping AI Agent Conversations on Track with Summarization

Learn how to manage long conversations in AI agents by summarizing prior turns to fit within the LLM's context window, maintaining coherence and

AI agents need memory. They need to recall past interactions to maintain a coherent conversation. The challenge is the limited context window of Large Language Models (LLMs). You cannot simply pass the entire conversation history indefinitely.

The Context Window Problem

LLMs have a fixed input size, known as the context window. This window dictates how much text – your prompt, system instructions, and conversation history – the model can process at once. As a conversation progresses, the number of turns increases. Eventually, the total length of messages exceeds the LLM's context window limit.

When this happens, you have a few problems. First, you might hit an API error, stopping the conversation cold. Second, even if you don't hit a hard limit, very long contexts increase token usage, leading to higher costs and slower response times. Most importantly, the LLM might start to forget earlier parts of the conversation, leading to incoherent or irrelevant responses.

Why Summarize?

Summarization is a practical solution to the context window problem. Instead of passing every single message from the past, you condense previous interactions into a shorter, more manageable summary. This summary captures the essential information, decisions made, and key facts discussed, without needing to include every word.

The goal is to preserve the meaning and relevant state of the conversation. This allows your agent to understand the current turn in the context of what has already happened, even if the explicit messages are no longer present.

How to Implement Summarization

There are a few ways to approach this.

Rolling Summaries

The most common method is a rolling summary. After a certain number of turns, or when the conversation history approaches the context window limit, you take the oldest part of the conversation and ask an LLM to summarize it. This summary then replaces those older turns in your agent's memory, effectively compressing the history.

Here's a conceptual example:

class ConversationAgent:
    def __init__(self, llm_client, max_history_tokens=4000):
        self.llm = llm_client
        self.history = [] # Stores message objects
        self.max_tokens = max_history_tokens

    def add_message(self, role, content):
        self.history.append({"role": role, "content": content})
        self.manage_context_window()

    def get_current_context(self):
        # Return history for LLM call
        return self.history

    def manage_context_window(self):
        current_token_count = self._calculate_tokens(self.history)

        if current_token_count > self.max_tokens:
            # Determine how much to summarize
            # This is a simplified example; real-world needs more nuance
            num_messages_to_summarize = len(self.history) // 2 # Summarize half the history
            messages_to_condense = self.history[:num_messages_to_summarize]
            remaining_messages = self.history[num_messages_to_condense:]

            summary_prompt = "Summarize the following conversation, capturing key decisions, facts, and unresolved questions: "
            summary_content = self.llm.generate(prompt=summary_prompt, messages=messages_to_condense)

            # Replace condensed messages with summary
            self.history = [{
                "role": "system", 
                "content": f"Previous conversation summary: {summary_content}"
            }] + remaining_messages

    def _calculate_tokens(self, messages):
        # Placeholder: In a real app, use a proper token counter for your LLM
        return sum(len(m["content"].split()) for m in messages) # Rough word count as proxy

    def chat(self, user_input):
        self.add_message("user", user_input)
        # ... call LLM with self.get_current_context() ...
        # ... add LLM response ...
        return "LLM Response"

Condensing Specific Information

Beyond a general summary, you can be more targeted. If your agent is performing a specific task, you might only need to extract certain entities, facts, or commitments. For example, an agent booking appointments might only need to remember the date, time, and service, not the entire negotiation leading to it. This requires more specific prompt engineering for the summarization step.

Challenges and Considerations

Summarization is not a silver bullet. It introduces its own set of challenges:

  • Loss of Detail: Summaries are inherently lossy. Fine-grained details that might become important later could be omitted. You need to balance conciseness with retaining critical information.
  • Summarization Quality: The quality of the summary depends on the LLM's ability to summarize and the prompt you give it. A poor summary can confuse the agent as much as a truncated history.
  • Cost of Summarization: Each summarization step is an additional LLM call. This adds latency and cost. You need to decide when the benefit of a condensed context outweighs the cost of generating the summary.
  • Prompt Engineering for Summaries: Crafting effective summarization prompts is crucial. Instruct the LLM on what to summarize (e.g., "key decisions," "unresolved questions," "user preferences") and how (e.g., "concisely," "bullet points").

Beyond Simple Summaries

For very complex or long-running agents, summarization can be combined with other techniques. Storing summaries or key facts in a structured way, perhaps in a vector database, allows for more sophisticated retrieval. This means the agent can intelligently fetch relevant past information, rather than relying solely on a linear summary. However, for many practical applications, rolling summaries are a robust starting point for AI agent development.

Where to go from here

Experiment with different summarization strategies for your agent. Pay attention to the balance between detail, cost, and context window limits. If you need help architecting robust memory for your AI agents, consider AI consulting services.

  • ai agent memory
  • llm context window
  • conversation summarization
  • ai agent development
  • context management
  • long conversations ai
  • prompt engineering summarization
  • ai agent architecture
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_