Skip to main content

Welcome to a Grasp lesson

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

Lesson 21

Session Context Management

Recommended resources

Introduction

In our last lesson, we designed the data-centric heart of our agent: the immutable, versioned TaskState schema. This schema provides a structured representation of the agent's knowledge and progress, but it raises a critical engineering challenge. The message_history and other contextual elements within this state cannot grow indefinitely. Every token we send to an LLM incurs cost and, more importantly, consumes a piece of the model's finite context window.

This lesson directly confronts that challenge. You will implement the logic for managing an agent's short-term 'working memory,' focusing on how to prune and maintain relevant context within a single, ongoing session. This is not merely an optimization; it is a fundamental problem in resource management, analogous to managing memory or cache in a traditional distributed system. Your goal is to prevent context overflow and control costs while minimizing the loss of critical information, ensuring the agent remains coherent and effective over long-running tasks.

We will explore a spectrum of strategies, from simple truncation to more sophisticated, active maintenance techniques that treat memory not as a passive log, but as a curated set of facts.


The Context Window: A Finite Resource to Engineer

At its core, an LLM is a function that takes a sequence of tokens (the context) and predicts the next token. The maximum length of this sequence is the "context window."

Why LLMs Forget—and How RAG + Context Engineering Fix It (Free Labs).

This video provides an excellent primer on the context window and why managing it is a crucial engineering task.

Watch the initial segment from the beginning to understand the context window as a form of short-term memory and its limitations. Then, watch the section on context engineering. The key insight is that providing a smaller, more relevant context often yields better, faster, and cheaper results than simply flooding the model with raw history.

As the video highlights, our task is one of "context engineering." We must design a system that intelligently selects and formats the most relevant pieces of our TaskState to construct the optimal context for each turn of the agent's loop.


A Roadmap for Memory Management

The process of managing working memory for each agent turn can be visualized as a systematic pipeline. The flowchart below illustrates a production-grade approach, which will serve as our guide for this lesson.

This flowchart depicts a comprehensive memory management pipeline. It includes pre-run setup steps like context window guards and history limiting, which lead to a pruning process. If the context still overflows, a more intensive "compaction path" involving summarization is triggered.

This flowchart depicts a comprehensive memory management pipeline. It includes pre-run setup steps like context window guards and history limiting, which lead to a pruning process. If the context still overflows, a more intensive "compaction path" involving summarization is triggered.

Our focus today will be on the "Pre-run setup" and "Context pruning" stages. We will implement the logic that resides within the main agent turn, before the final reply is generated.


Foundational Pruning Strategies

Let's begin by implementing the most common strategies for managing the message_history list from our TaskState. The following article provides excellent, self-contained Python implementations that we can use as a starting point.

Short-Term Conversation Memory: Building Context-Aware AI Agents

This article builds from the ground up, starting with the problem of statelessness and progressively implementing more sophisticated memory management techniques.

First, review the sections on The Problem and The Solution to solidify the baseline. The ask_with_memory function, which simply appends to and passes the full history, is our starting point. You can also look at the ConversationalAgent class in the next section. Next, read the section on The Context Window Challenge. This frames the problem we need to solve. Study Solution 1: Sliding Window Memory. Read the explanation and analyze the ConversationalAgentWithWindow class implementation. Pay close attention to how it uses list slicing (self.conversation_history[-self.max_messages:]) to discard the oldest messages. Finally, study Solution 2: Conversation Summarization. Read the explanation and examine the ConversationalAgentWithSummary implementation. Note how it separates the history, generates a summary for the older part, and prepends it to the recent history. Also read the final comparison of the approaches.

Let's quickly formalize these two primary pruning strategies:

  1. Sliding Window (FIFO Pruning): This is the simplest strategy. It maintains a fixed-size buffer of the k most recent messages. When the buffer is full, the oldest message (First-In) is discarded to make room for the new one (First-Out).

    • Pros: Extremely simple to implement, computationally cheap, and provides a hard guarantee on context size.
    • Cons: "Forgets" older information completely, regardless of its importance. It's a blunt instrument.
  2. Summarization (Compaction): This strategy attempts to retain information from older parts of the conversation by compressing it. Instead of deleting old messages, it uses an LLM to create a summary, which replaces the original messages in the context.

    • Pros: Preserves the semantic essence of the entire conversation, mitigating the amnesia problem of the sliding window.
    • Cons: Incurs the cost and latency of an additional LLM call. The summarization process itself can be lossy, potentially discarding crucial details.

For many applications, a hybrid approach as shown in the SmartConversationalAgent from the article offers a good balance. It uses a sliding window for recent, high-fidelity history and a running summary for the distant past.


An Advanced Architecture: Live Distillation and Active Maintenance

The strategies above treat working memory as a monolithic, unstructured log of chat messages. A more robust, production-grade architecture makes a crucial distinction: it separates the raw, verbose conversation history from a structured, concise set of session notes or facts.

This diagram shows a layered memory architecture. Short-term memory (transient, scratchpad) is distinct from other memory types like Episodic and Semantic. This separation is key to advanced memory management.

This diagram shows a layered memory architecture. Short-term memory (transient, scratchpad) is distinct from other memory types like Episodic and Semantic. This separation is key to advanced memory management.

This separation allows us to apply different management policies to each. We can aggressively prune the noisy conversation history while carefully curating the high-signal session notes. This is where the concept of live distillation comes in.

Agent Memory Systems: A Complete Engineering Guide - Medium

This article presents a sophisticated, framework-agnostic architecture for agent memory. It introduces patterns that align perfectly with our goal of building a reliable, first-principles system.

Start by reading Layer 1: State Definition. This reinforces our direction by proposing a state object with separate lists for global_memory and session_memory. session_memory is our structured working memory, a staging area for facts relevant to the current task. Note the MemoryNote schema with its importance field—a critical piece of metadata for pruning. Next, study Layer 2: Live Distillation. The core idea is the "Distillation Tool Pattern": giving the agent a tool (save_memory) to actively extract "durable, actionable, explicit" information from the conversation into session_memory. The docstring for this tool is the mechanism that teaches the agent what is worth remembering. Finally, read Layer 3: Injection, focusing on the part about Context Window Management (Trimming). The TrimmingSession class and the inject_session_memories_next_turn flag demonstrate a brilliant technique. When the raw history is trimmed, this flag ensures the distilled session notes are re-injected, preventing information loss. Also read the Q&A section on preventing overflow, which summarizes this pattern.

This architecture elevates our design from passive pruning to active maintenance. The agent is no longer just a recipient of history; it becomes a curator of its own working memory.

This active role extends beyond just adding notes. A truly robust system must also handle changes and corrections.

How to build your own long-term Agentic Memory System for LLMs | Mem0 from scratch in DSPy

This video demonstrates building a memory system from scratch using the DSPy framework. While we are not using DSPy, the underlying principles of memory extraction and maintenance are directly applicable.

First, watch the segment from 12:04 to 20:22. This shows how to define a schema for a memory entry (e.g., with categories, sentiment) and use an LLM to extract structured information from an unstructured conversation. This is the practical implementation of "Live Distillation." Next, and most importantly, watch the section on updating memories from 32:59 to 38:52. This introduces the idea of using tools not just to add memories, but also to update existing ones, delete stale ones, or perform a no-op (no operation). This is the final piece of the active maintenance puzzle.


Synthesizing a Production-Grade Working Memory Manager

Let's integrate these concepts into a Python class that manages the working memory portion of our TaskState. This implementation will combine a sliding window for raw history with an actively maintained set of structured session notes.

import uuid
from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional

# A structured note, distilled from the conversation
@dataclass
class SessionNote:
    note_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    content: str
    importance: int = 3 # 1-5 scale
    
# Assume AgentMessage and other classes from previous lesson exist

class WorkingMemoryManager:
    def __init__(self, message_window_size: int = 20):
        self.message_window_size = message_window_size

    def _distill_and_update_notes(self, new_messages: List[AgentMessage], session_notes: List[SessionNote]) -> List[SessionNote]:
        """
        Uses an LLM tool-calling agent to add, update, or delete session notes
        based on the latest messages and existing notes.
        This is a placeholder for the logic shown in the DSPy video.
        """
        # 1. Format new_messages and session_notes for the LLM.
        # 2. Call an LLM with add_note, update_note, delete_note tools.
        # 3. The LLM decides if any new info is important enough to distill.
        #    - If user says "My project ID is X", it calls add_note("User's project ID is X", importance=4).
        #    - If user says "Actually, my project ID is Y", it finds the old note and calls
        #      update_note(note_id, "User's project ID is Y").
        # 4. Return the modified list of session_notes.
        print("[MemoryManager] Actively maintaining session notes...")
        # In a real implementation, this would return an updated list
        return session_notes

    def prune_context(self, message_history: List[AgentMessage], session_notes: List[SessionNote]) -> (List[AgentMessage], List[SessionNote]):
        """
        Prunes the message history and actively maintains session notes.
        """
        # Active Maintenance: Distill info from the latest messages
        # We might choose to only process messages since the last prune.
        updated_notes = self._distill_and_update_notes(message_history, session_notes)

        # Sliding Window Pruning: Keep only the most recent raw messages
        if len(message_history) > self.message_window_size:
            print(f"[MemoryManager] Pruning message history from {len(message_history)} to {self.message_window_size} messages.")
            pruned_history = message_history[-self.message_window_size:]
        else:
            pruned_history = message_history

        return pruned_history, updated_notes

    def build_prompt_context(self, pruned_history: List[AgentMessage], session_notes: List[SessionNote]) -> List[Dict[str, Any]]:
        """
        Constructs the final list of messages for the LLM prompt,
        injecting the structured notes.
        """
        context = []
        
        if session_notes:
            # Inject notes as a single system-like message at the start
            notes_str = "\n".join([f"- {note.content} (Importance: {note.importance})" for note in sorted(session_notes, key=lambda n: n.importance, reverse=True)])
            context.append({
                "role": "user", # Or a custom role if the API supports it
                "content": f"[CONTEXT FROM WORKING MEMORY]\nHere are some key facts for this session:\n{notes_str}\n---"
            })
        
        # Append the pruned raw conversation history
        # (Assuming AgentMessage can be serialized to the required dict format)
        context.extend([msg.to_dict() for msg in pruned_history])
        
        return context

# Example Usage (within your main agent loop)
# state: TaskState # from previous turn
# memory_manager = WorkingMemoryManager()

# 1. Prune the state from the previous turn
# pruned_history, updated_notes = memory_manager.prune_context(state.message_history, state.session_notes)

# 2. Build the context for the next LLM call
# prompt_messages = memory_manager.build_prompt_context(pruned_history, updated_notes)

# 3. Make the LLM call
# response = client.messages.create(..., messages=prompt_messages)

# 4. Create the new TaskState for this turn
# new_state = TaskState(
#     ...,
#     message_history=pruned_history + [new_user_message, assistant_response],
#     session_notes=updated_notes,
#     ...
# )

This WorkingMemoryManager encapsulates our logic. For each turn, it first uses an LLM to perform active maintenance on the structured session_notes, then applies a simple sliding window to the raw message_history. Finally, it constructs the prompt by injecting the high-signal notes before the more verbose, transient history. This ensures critical facts survive even when the raw messages they originated from are pruned away.


Conclusion

In this lesson, we have moved from a theoretical state schema to the practical engineering of short-term memory management. We've treated the context window as a finite resource and designed strategies to manage it effectively.

Your key takeaways are:

  • Memory management is a trade-off: You must constantly balance information fidelity against cost and the hard limits of the context window.
  • Simple strategies are the first line of defense: Sliding windows (FIFO) and summarization are effective, well-understood patterns for controlling context length.
  • Production systems require active maintenance: A sophisticated agent should not just passively accumulate history. It should actively distill important facts into a structured format (session_notes) and maintain this knowledge base by adding, updating, and deleting facts as the session progresses.
  • Separation of concerns is key: By separating verbose message_history from high-signal session_notes, we can apply different, more intelligent pruning policies to each, leading to a more robust and coherent agent.

We touched on the concept of summarization as a pruning strategy today. In our next lesson, we will perform a deep dive specifically into that technique. You will learn how to implement different summarization methods, when to trigger the compaction process, and how to handle the nuances of lossy compression to build an effective and cost-efficient long-term conversational memory.