Velamuvi AIAcademy

Lesson 14 of 39 · Sessions, Memory and Context

Compaction: Keeping Context Small

Keep long Agent Framework chats in the context window with sliding windows, truncation, tool-result collapsing, summaries, token budgets and CompactionProvider.

  • 18 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why long chats need compaction and how messages are grouped
  • Turn on compaction for an agent with compaction_strategy
  • Choose between the built-in strategies, including summaries and token budgets
  • Count tokens with CharacterEstimatorTokenizer or your own tokenizer
  • Compact the stored history between turns with CompactionProvider

Why long chats need compaction

Every time an agent calls the model, it sends the conversation so far: every question, every answer, and every tool call with its result. A short chat costs little. A support chat that runs all afternoon, or one task with twenty tool calls, sends thousands of tokens on every call. Cost and waiting time grow with each turn, and in the end the request is bigger than the model's context window (the most text a model can read at once) and fails.

Agent Framework compacts with strategies: objects that look at the conversation and decide what to hide. Nothing is deleted. Hidden messages stay in the session, they just aren't sent. The Memory in AI Agents course explains short-term memory in general; this lesson shows how Agent Framework does it.

Messages come in groups

Before compacting, the framework sorts the conversation into groups, and a strategy always keeps or hides a whole group:

Group kindWhat it holds
systemA system message
userOne user message
assistant_textOne assistant reply
tool_callThe assistant's tool call and the tool results that answer it

The tool_call group matters most. Model APIs reject a tool result whose call is missing, so a call and its result must stay together. Here's the idea in plain Python, with a sliding window that keeps the system message and the last three groups:

Try it yourselfPython
# A conversation as (role, text) pairs. A "result" belongs to the "call" just before it.
conversation = [
    ("system", "You are the assistant of a bike shop."),
    ("user", "Do you have the Trek FX 2?"),
    ("call", "check_stock('Trek FX 2')"),
    ("result", "3 in stock"),
    ("assistant", "Yes, 3 in stock."),
    ("user", "What does it cost?"),
    ("call", "get_price('Trek FX 2')"),
    ("result", "649 EUR"),
    ("assistant", "It costs 649 EUR."),
    ("user", "Can I book a test ride?"),
]

def groups(messages):
    out = []
    for role, text in messages:
        if role == "result":
            out[-1].append((role, text))       # join the call it answers
        else:
            out.append([(role, text)])         # start a new group
    return out

def sliding_window(messages, keep_last_groups):
    all_groups = groups(messages)
    system = [g for g in all_groups if g[0][0] == "system"]
    others = [g for g in all_groups if g[0][0] != "system"]
    kept = system + others[-keep_last_groups:]
    return [message for group in kept for message in group]

print(len(conversation), "messages in", len(groups(conversation)), "groups")
for role, text in sliding_window(conversation, keep_last_groups=3):
    print(f"{role:9} {text}")

Ten messages became eight groups, because each tool call and its result count as one. The window kept the system message and the last three groups, so the older stock check disappeared but the price check stayed complete.

Turn compaction on for an agent

Pass a strategy as compaction_strategy when you create the agent:

import asyncio
from agent_framework import Agent, SlidingWindowStrategy
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(
        client=OpenAIChatClient(),                     # reads OPENAI_API_KEY and OPENAI_MODEL
        instructions="You are the assistant of a bike shop.",
        default_options={"store": False},              # keep the history in your app, where it can be compacted
        compaction_strategy=SlidingWindowStrategy(keep_last_groups=3),
    )
    session = agent.create_session()
    for question in ["Do you sell city bikes?", "Which sizes?", "Any in blue?", "Can I test ride one?"]:
        response = await agent.run(question, session=session)
    print("Stored in the session:", len(session.state["in_memory"]["messages"]), "messages")

asyncio.run(main())
Output
Stored in the session: 8 messages

What each part does:

  • compaction_strategy=SlidingWindowStrategy(keep_last_groups=3): before every model call, including the extra calls an agent makes inside a tool loop, the framework sends only the last 3 groups. The instructions are always sent. In this chat the four model calls received 1, 3, 3 and 3 messages.
  • default_options={"store": False}: needed with OpenAIChatClient. It uses OpenAI's Responses API, which by default keeps the conversation on OpenAI's servers. Your app then sends only the new message, so there's nothing local to compact, and the server's copy keeps growing. With store=False the history stays in the session and is sent, compacted, each time. OpenAIChatCompletionClient never stores conversations, so it doesn't need this.
  • The session still holds all 8 messages. Compaction changes what the model receives, not what you keep.

You can set a strategy in two more places. A strategy passed to one run wins over the agent's: await agent.run(question, session=session, compaction_strategy=SlidingWindowStrategy(keep_last_groups=10)). A strategy on the client, OpenAIChatClient(compaction_strategy=...), is used when the agent has none.

The built-in strategies

StrategyWhat it doesMain settings
SlidingWindowStrategyKeeps the system message and the last N groupskeep_last_groups, preserve_system
TruncationStrategyOnce the chat passes a limit, hides the oldest groups until it's under a target. Counts messages, or tokens if you give it a tokenizermax_n, compact_to, tokenizer, preserve_system, preserve_first_user_group
SelectiveToolCallCompactionStrategyHides old tool-call groups completely, leaving questions and answers alonekeep_last_tool_call_groups
ToolResultCompactionStrategyReplaces each old tool-call group with one short line listing its resultskeep_last_tool_call_groups
SummarizationStrategyAsks a model to summarize older groups and puts the summary in their placeclient, target_count, threshold, prompt, max_summary_input_tokens
TokenBudgetComposedStrategyRuns several strategies in order until the chat fits a token budgettoken_budget, tokenizer, strategies, early_stop
ContextWindowCompactionStrategyWorks out a budget from the model's context window, then collapses old tool results and, if still needed, truncatesmax_context_window_tokens, max_output_tokens, tool_eviction_threshold, truncation_threshold, keep_last_tool_call_groups
AgentTriggeredCompactionStrategyRuns another strategy only when the model calls a compact_context tool (experimental)strategy, tool_name, approval_mode, exclude_trigger
UnloadSkillsCompactionStrategyUnloads agent skills the model no longer needs (covered in the Agent Skills lesson)

See exactly what the model would receive

apply_compaction(messages, strategy=...) runs a strategy on a list of messages and returns the ones that would be sent. It needs no model and no API key, so it's the easiest way to compare strategies. Here each one gets the same bike-shop chat:

import asyncio
from agent_framework import (
    CharacterEstimatorTokenizer, Content, ContextWindowCompactionStrategy, Message,
    SelectiveToolCallCompactionStrategy, SlidingWindowStrategy, TokenBudgetComposedStrategy,
    ToolResultCompactionStrategy, TruncationStrategy, apply_compaction,
)

def conversation():          # a fresh list each time: strategies mark the messages they hide
    return [
        Message("system", ["You are the assistant of a bike shop."]),
        Message("user", ["Do you have the Trek FX 2 in stock?"]),
        Message("assistant", [Content.from_function_call("c1", "check_stock", arguments={"model": "Trek FX 2"})]),
        Message("tool", [Content.from_function_result("c1", result="3 in stock")]),
        Message("assistant", ["Yes, we have 3 in stock."]),
        Message("user", ["What does it cost?"]),
        Message("assistant", [Content.from_function_call("c2", "get_price", arguments={"model": "Trek FX 2"})]),
        Message("tool", [Content.from_function_result("c2", result="649 EUR")]),
        Message("assistant", ["It costs 649 EUR."]),
        Message("user", ["Can I book a test ride on Saturday?"]),
    ]

def short(message):
    content = message.contents[0]
    if content.type == "function_call":
        return f"call {content.name}"
    if content.type == "function_result":
        return f"result {content.result}"
    return f"{message.role}: {message.text[:22]}"

tokenizer = CharacterEstimatorTokenizer()
strategies = {
    "sliding window": SlidingWindowStrategy(keep_last_groups=3),
    "truncation": TruncationStrategy(max_n=6, compact_to=4),
    "drop old tool calls": SelectiveToolCallCompactionStrategy(keep_last_tool_call_groups=1),
    "collapse old tool results": ToolResultCompactionStrategy(keep_last_tool_call_groups=1),
    "token budget": TokenBudgetComposedStrategy(
        token_budget=250, tokenizer=tokenizer,
        strategies=[ToolResultCompactionStrategy(keep_last_tool_call_groups=0), SlidingWindowStrategy(keep_last_groups=4)],
    ),
    "context window": ContextWindowCompactionStrategy(
        max_context_window_tokens=500, max_output_tokens=200, tokenizer=tokenizer,
    ),
}

async def main():
    for name, strategy in strategies.items():
        sent = await apply_compaction(conversation(), strategy=strategy)
        print(f"{name} ({len(sent)}): " + " | ".join(short(m) for m in sent))

asyncio.run(main())
Output
sliding window (5): system: You are the assistant  | call get_price | result 649 EUR | assistant: It costs 649 EUR. | user: Can I book a test ride
truncation (3): system: You are the assistant  | assistant: It costs 649 EUR. | user: Can I book a test ride
drop old tool calls (8): system: You are the assistant  | user: Do you have the Trek F | assistant: Yes, we have 3 in stoc | user: What does it cost? | call get_price | result 649 EUR | assistant: It costs 649 EUR. | user: Can I book a test ride
collapse old tool results (9): system: You are the assistant  | user: Do you have the Trek F | assistant: [Tool results: check_s | assistant: Yes, we have 3 in stoc | user: What does it cost? | call get_price | result 649 EUR | assistant: It costs 649 EUR. | user: Can I book a test ride
token budget (5): system: You are the assistant  | user: What does it cost? | assistant: [Tool results: get_pri | assistant: It costs 649 EUR. | user: Can I book a test ride
context window (3): system: You are the assistant  | assistant: It costs 649 EUR. | user: Can I book a test ride

Reading the results:

  • Sliding window kept the system message and the last three groups, exactly like the plain-Python version.
  • Truncation saw 10 messages, more than max_n=6, and hid the oldest groups until no more than compact_to=4 were left. Whole groups go at once, so it ended at 3.
  • Drop old tool calls removed the stock check (call and result) and kept the newest tool group.
  • Collapse old tool results replaced the stock check with one message, [Tool results: check_stock: 3 in stock]. The fact stays and the overhead goes.
  • Token budget ran its strategies in order: first it collapsed every tool group, then the sliding window kept four groups. That fit under 250 tokens, so it stopped.
  • Context window subtracted the 200 tokens kept free for the answer from the 500-token window, leaving a 300-token input budget. Above half of that (tool_eviction_threshold=0.5) it collapses old tool results; above 80% (truncation_threshold=0.8) it removes the oldest groups.

Two details: strategies mark the messages they hide, so the example builds a fresh list each time; and these token counts come from CharacterEstimatorTokenizer, which measures each whole message, including its structure, so they're higher than the words alone.

Summaries

SummarizationStrategy keeps the meaning of old messages instead of dropping them. It asks a model to summarize them:

import asyncio
from agent_framework import Agent, SummarizationStrategy
from agent_framework.openai import OpenAIChatClient

async def main():
    summarizer = OpenAIChatClient()                    # use a model you trust: its summary becomes history
    agent = Agent(
        client=OpenAIChatClient(),
        instructions="You are the assistant of a bike shop.",
        default_options={"store": False},
        compaction_strategy=SummarizationStrategy(
            client=summarizer,
            target_count=4,          # keep about this many recent messages word for word
            threshold=2,             # summarize once there are more than target_count + threshold
        ),
    )
    session = agent.create_session()
    for turn in range(1, 6):
        await agent.run(f"Question {turn}", session=session)

asyncio.run(main())

Once more than target_count + threshold messages are included (here more than 6), it sends the oldest groups to the summarizer and puts the summary, as an assistant message, in their place. About target_count recent messages stay word for word. In this chat, the fourth call received the summary plus the last four messages. Use prompt= for your own summarizing instructions, and max_summary_input_tokens (default 8,000) to cap how much text goes to the summarizer.

Used as the agent's compaction_strategy, the summary isn't saved: the session still holds every message, so on later turns the whole history is summarized again. To summarize once and keep the result, use it with CompactionProvider, below.

Count tokens

Limits in messages are simple, but models are limited by tokens. Token-aware strategies take a tokenizer: any object with a count_tokens(text) method.

from agent_framework import CharacterEstimatorTokenizer, TokenizerProtocol, TruncationStrategy

class WordTokenizer:
    """Counts words. Any class with a count_tokens(text) -> int method is a tokenizer."""
    def count_tokens(self, text: str) -> int:
        return len(text.split())

text = "Do you have the Trek FX 2 in stock?"
print(CharacterEstimatorTokenizer().count_tokens(text))    # about 4 characters per token
print(WordTokenizer().count_tokens(text))
print(isinstance(WordTokenizer(), TokenizerProtocol))

strategy = TruncationStrategy(max_n=3000, compact_to=2000, tokenizer=WordTokenizer())   # limits now count tokens
Output
8
9
True

CharacterEstimatorTokenizer guesses about 4 characters per token. It's fast and needs no downloads. Any class with a count_tokens(text) -> int method matches TokenizerProtocol, so for exact counts you can wrap your model's own tokenizer library the same way (for OpenAI models, the tiktoken package). A tokenizer can go on a strategy, on the agent (Agent(tokenizer=...)), on one run, or on CompactionProvider.

Compact the stored history with CompactionProvider

An agent's compaction_strategy leaves the stored history growing, and every turn loads all of it. CompactionProvider is a context provider (the next lesson covers them) that compacts at two moments:

  • before_strategy runs at the start of each run, on the history loaded by earlier providers (not the new message). It controls what the model sees this turn.
  • after_strategy runs at the end of each run, on the history stored in the session, and marks old messages as excluded. With skip_excluded=True, the history provider doesn't load them again.
import asyncio
from agent_framework import (
    EXCLUDED_KEY, Agent, CompactionProvider, InMemoryHistoryProvider,
    SlidingWindowStrategy, TruncationStrategy,
)
from agent_framework.openai import OpenAIChatClient

async def main():
    history = InMemoryHistoryProvider(skip_excluded=True)         # don't load messages marked as excluded
    compaction = CompactionProvider(
        before_strategy=SlidingWindowStrategy(keep_last_groups=6),  # trims what the model sees this turn
        after_strategy=TruncationStrategy(max_n=6, compact_to=4),   # marks old stored messages as excluded
        history_source_id=history.source_id,
    )
    agent = Agent(
        client=OpenAIChatClient(),
        instructions="You are the assistant of a bike shop.",
        default_options={"store": False},
        context_providers=[history, compaction],    # history first: it loads what compaction works on
    )
    session = agent.create_session()
    for turn in range(1, 7):
        await agent.run(f"Question {turn}", session=session)
        stored = session.state[history.source_id]["messages"]
        hidden = sum(1 for message in stored if message.additional_properties.get(EXCLUDED_KEY))
        print(f"After turn {turn}: {len(stored)} stored, {hidden} excluded")

asyncio.run(main())
Output
After turn 1: 2 stored, 0 excluded
After turn 2: 4 stored, 0 excluded
After turn 3: 6 stored, 0 excluded
After turn 4: 8 stored, 0 excluded
After turn 5: 10 stored, 4 excluded
After turn 6: 12 stored, 4 excluded

From turn 6 on, the four oldest messages are never loaded again. Things to know:

  • Order matters. Providers' before_run steps run in list order, so put the history provider first: it loads the messages that compaction then works on. Pass history_source_id=history.source_id so the provider finds them.
  • The after step works one turn behind. after_run steps run in reverse order, so compaction runs before the history provider saves this turn's messages. At the end of turn 5 it saw 8 stored messages, more than max_n=6, and excluded the oldest 4. Then the 2 new messages were saved.
  • Excluded messages stay stored, marked, which is useful for audits. How much you keep, and where, is up to the history provider (see the History Providers and Storage lesson).
  • Summaries are saved. With after_strategy=SummarizationStrategy(...), the summary is written into the stored history. Later summaries include the previous one, giving a rolling summary of the whole chat.

Let the model decide

AgentTriggeredCompactionStrategy wraps any strategy and only runs it when the model asks, by calling a tool:

import asyncio
from agent_framework import Agent, AgentTriggeredCompactionStrategy, SlidingWindowStrategy
from agent_framework.openai import OpenAIChatClient

async def main():
    compaction = AgentTriggeredCompactionStrategy(SlidingWindowStrategy(keep_last_groups=4))
    agent = Agent(
        client=OpenAIChatClient(),
        instructions="You help bike shop customers. When the chat gets long, call compact_context.",
        default_options={"store": False},     # required: the history must live in your app
        tools=[compaction.tool],              # the tool the model calls to ask for compaction
        compaction_strategy=compaction,
    )
    print("Trigger tool:", compaction.tool.name)
    session = agent.create_session()
    for turn in range(1, 6):
        response = await agent.run(f"Question {turn}", session=session)

asyncio.run(main())
Output
Trigger tool: compact_context

Register compaction.tool with the agent and tell the model when to use it. When the model calls compact_context, the wrapped strategy runs before its next call. In a test, the model called the tool once the chat reached 7 messages, and its next call received the four newest groups plus the trigger call and its result. Set exclude_trigger=True to hide those too, and approval_mode="always_require" to make a person approve each compaction. The strategy is experimental (you'll see an ExperimentalWarning), and it needs the history in your app: with store=True the client refuses to run.

Write your own strategy

A strategy is any object with an async __call__(messages) method that marks messages and returns True if it changed anything. That's what CompactionStrategy describes. Before calling it, the framework writes each message's group into its additional_properties:

import asyncio
from agent_framework import (
    EXCLUDED_KEY, GROUP_ANNOTATION_KEY, GROUP_ID_KEY, GROUP_KIND_KEY,
    CompactionStrategy, Message, apply_compaction,
)

class HideOldAnswers:
    """Hide every assistant text reply except the newest `keep`. Questions and tool calls stay."""

    def __init__(self, keep: int = 1):
        self.keep = keep

    async def __call__(self, messages: list[Message]) -> bool:
        groups = [m.additional_properties[GROUP_ANNOTATION_KEY] for m in messages]   # added before the call
        answers = [g[GROUP_ID_KEY] for g in groups if g[GROUP_KIND_KEY] == "assistant_text"]
        to_hide = set(answers[:-self.keep])
        changed = False
        for message, group in zip(messages, groups):
            if group[GROUP_ID_KEY] in to_hide and not message.additional_properties.get(EXCLUDED_KEY):
                message.additional_properties[EXCLUDED_KEY] = True       # excluded, not deleted
                changed = True
        return changed                                                  # tell the framework something changed

async def main():
    chat = [Message("user", ["Hi"]), Message("assistant", ["Hello!"]),
            Message("user", ["Price?"]), Message("assistant", ["649 EUR."]), Message("user", ["Thanks"])]
    print(isinstance(HideOldAnswers(), CompactionStrategy))
    sent = await apply_compaction(chat, strategy=HideOldAnswers(keep=1))
    print([m.text for m in sent])

asyncio.run(main())
Output
True
['Hi', 'Price?', '649 EUR.', 'Thanks']

The keys you can read and write:

ConstantFound onMeaning
GROUP_ANNOTATION_KEYevery messageits group, with GROUP_ID_KEY, GROUP_KIND_KEY, GROUP_INDEX_KEY, GROUP_HAS_REASONING_KEY and GROUP_TOKEN_COUNT_KEY
EXCLUDED_KEY, EXCLUDE_REASON_KEYhidden messagesthe hidden flag, and why
SUMMARY_OF_MESSAGE_IDS_KEY, SUMMARY_OF_GROUP_IDS_KEYa summarythe messages and groups it replaced
SUMMARIZED_BY_SUMMARY_ID_KEYsummarized messagesthe summary that replaced them

Three helpers work on annotated lists: annotate_message_groups(messages) adds the group annotations, included_messages(messages) returns the messages that aren't hidden, and included_token_count(messages) adds up their token counts.

Common mistakes

Practice exercise

Write the oldest-first rule that TruncationStrategy uses with a tokenizer: remove whole groups, oldest first, until the conversation fits the budget, and never remove the system group.

Your solutionPython
# Each group as (kind, tokens), oldest first. The system group must always stay.
groups = [("system", 40), ("user", 30), ("tool_call", 220), ("assistant", 50),
          ("user", 25), ("tool_call", 180), ("assistant", 45), ("user", 20)]
budget = 300

# Drop the oldest non-system groups until the total is within the budget.
# Then print the kept kinds joined by " > ", then " | ", then the total, like:
# system > user | 60 tokens
Knowledge check

An agent uses OpenAIChatClient with default settings and SlidingWindowStrategy(keep_last_groups=4), but long chats get more and more expensive. What is the most likely cause?

Summary

  • Compaction keeps each model call small by hiding, collapsing or summarizing older messages; nothing is deleted.
  • Messages are handled in groups, so a tool call and its result always stay together.
  • compaction_strategy on an agent, a run or a client compacts before every model call. With OpenAIChatClient, set store=False.
  • Pick from the built-in strategies, or write your own, and test them offline with apply_compaction. Tokenizers make limits count tokens.
  • CompactionProvider compacts what is loaded (before_strategy) and what is stored (after_strategy), which also saves summaries.

Next: Context Providers and Long-Term Memory.

Finished reading? Tick it off to track your progress.