# Context Compression (/compression/overview)



<Badge icon="code-branch" color="orange">
  <Tooltip tip="Introduced in v2.2.14" cta="View release notes" href="https://github.com/agno-agi/agno/releases/tag/v2.2.14">
    v2.2.14
  </Tooltip>
</Badge>

## Setup [#setup]

In an activated [virtual environment](/sdk/setup):

```bash
uv pip install -U agno openai
export OPENAI_API_KEY="your_openai_api_key"
```

Context compression summarizes eligible tool-result messages for subsequent model requests. It can reduce context size, but does not guarantee a smaller summary, complete preservation of facts, lower total cost, or fitting the model's context window.

## The Problem: Verbose Tool Results [#the-problem-verbose-tool-results]

Large tool results can consume the context window. The following token counts illustrate a possible workload; they are not measured guarantees:

| Component     | Cumulative Token Count | Notes             |
| ------------- | ---------------------- | ----------------- |
| System Prompt | 1,200 tokens           |                   |
| User Message  | 1,300 tokens           |                   |
| LLM Response  | 1,500 tokens           |                   |
| Tool Call 1   | 2,500 tokens           |                   |
| Tool Call 2   | 5,700 tokens           | 2,500 + 3,200 new |
| Tool Call 3   | 8,500 tokens           | 5,700 + 2,800 new |
| Tool Call 4   | 12,000 tokens          | 8,500 + 3,500 new |

This quickly becomes expensive and hits context limits during complex workflows.

## The Solution: Automatic Compression [#the-solution-automatic-compression]

Context compression summarizes tool results after a threshold:

```
Tool Call 1: 2,500 tokens
Tool Call 2: 5,700 tokens
Tool Call 3: 8,500 tokens
[Compression triggered]
Tool Call 4: 1,300 tokens (800 compressed + 500 new)
```

Compression adds summarization-model calls and latency. Measure savings and information loss on your workload. System and user messages are not shortened by tool-result compression.

## How It Works [#how-it-works]

Context compression follows a simple pattern:

<Steps>
  <Step title="Enable Compression">
    Set `compress_tool_results=True` on your agent or team, or provide a `CompressionManager`. The system monitors tool call results as they come in.
  </Step>

  <Step title="Threshold Reached">
    After the threshold is reached, compression is triggered. Each uncompressed tool call result is individually summarized.
  </Step>

  <Step title="Intelligent Summarization">
    The compression prompt asks the model to retain key facts while removing boilerplate. Summaries can lose information or exceed the original length.
  </Step>

  <Step title="The LLM loop continues">
    The compressed tool results are used in the next LLM executions, using each message's `compressed_content`. The original `content` is retained, so this is not a storage-reduction guarantee.
  </Step>
</Steps>

<Note>
  When using `arun` on `Agent` or `Team`, compression is handled asynchronously and the uncompressed tool call results are summarized concurrently.
</Note>

## Compression and result offloading [#compression-and-result-offloading]

Compression and tool-result offloading are alternative mechanisms for the same results. Agent and Team initialization reject enabling both. If a member inherits a Team's result store, set `offload_tool_results=False` on that member before enabling its compression. See [tool result offloading](/examples/agents/result-offloading/offload-tool-results).

## Enable Compression [#enable-compression]

Turn on `compress_tool_results=True` to automatically compress tool results. This comes with a default threshold of 3 uncompressed tool-result messages.

For example:

<CodeBlockTabs defaultValue="Agent">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="Agent">
      Agent
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="Team">
      Team
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="Agent">
    ```python
    from agno.agent import Agent
    from agno.models.openai import OpenAIResponses
    from agno.tools.hackernews import HackerNewsTools

    agent = Agent(
        model=OpenAIResponses(id="gpt-5.2"),
        tools=[HackerNewsTools()],
        compress_tool_results=True,
    )

    agent.print_response("Get the top stories on HackerNews about AI, ML, startups, and tech trends")
    ```
  </CodeBlockTab>

  <CodeBlockTab value="Team">
    ```python
    from agno.agent import Agent
    from agno.models.openai import OpenAIResponses
    from agno.team import Team
    from agno.tools.hackernews import HackerNewsTools

    web_agent = Agent(
        name="HackerNews Researcher",
        tools=[HackerNewsTools()],
    )

    team = Team(
        model=OpenAIResponses(id="gpt-5.2"),
        members=[web_agent],
        compress_tool_results=True,
    )

    team.print_response("Get the top stories on HackerNews about AI, ML, startups, and tech trends")
    ```
  </CodeBlockTab>
</CodeBlockTabs>

<Info>
  You can also enable `compress_tool_results=True` on individual team members to compress their tool results independently.
</Info>

## Custom Compression [#custom-compression]

Provide a [`CompressionManager`](/reference/compression/compression-manager) to customize the compression behavior:

<CodeBlockTabs defaultValue="Agent">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="Agent">
      Agent
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="Team">
      Team
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="Agent">
    ```python
    from agno.agent import Agent
    from agno.compression.manager import CompressionManager
    from agno.models.openai import OpenAIResponses
    from agno.tools.hackernews import HackerNewsTools

    compression_manager = CompressionManager(
        model=OpenAIResponses(id="gpt-5-mini"),  # Use a faster model for compression
        compress_tool_results_limit=2,  # Compress at 2 uncompressed tool-result messages (default: 3)
        compress_tool_call_instructions="Your custom compression prompt here...",
    )

    agent = Agent(
        model=OpenAIResponses(id="gpt-5.2"),
        tools=[HackerNewsTools()],
        compression_manager=compression_manager,
    )

    agent.print_response("Find stories about AI startup funding on HackerNews")
    ```
  </CodeBlockTab>

  <CodeBlockTab value="Team">
    ```python
    from agno.agent import Agent
    from agno.compression.manager import CompressionManager
    from agno.models.openai import OpenAIResponses
    from agno.team import Team
    from agno.tools.hackernews import HackerNewsTools

    compression_manager = CompressionManager(
        model=OpenAIResponses(id="gpt-5-mini"),  # Use a faster model for compression
        compress_tool_results_limit=2,  # Compress at 2 uncompressed tool-result messages (default: 3)
        compress_tool_call_instructions="Your custom compression prompt here...",
    )

    web_agent = Agent(
        name="HackerNews Researcher",
        tools=[HackerNewsTools()],
    )

    team = Team(
        model=OpenAIResponses(id="gpt-5.2"),
        members=[web_agent],
        compression_manager=compression_manager,
    )

    team.print_response("Find stories about AI startup funding on HackerNews")
    ```
  </CodeBlockTab>
</CodeBlockTabs>

<Tip>
  Use a faster, cheaper model like `gpt-5-mini` for compression to reduce latency and cost while using a more capable model as your Agent's main model.
</Tip>

## Compression Triggers [#compression-triggers]

The `CompressionManager` supports two types of thresholds for triggering compression:

| Mode            | Parameter                     | Use Case                                                                                      |
| --------------- | ----------------------------- | --------------------------------------------------------------------------------------------- |
| **Count-Based** | `compress_tool_results_limit` | Predictable tool call patterns. Triggers after N uncompressed tool results.                   |
| **Token-Based** | `compress_token_limit`        | Variable result sizes. Triggers when the estimated context token count reaches the threshold. |

<Note>
  When both thresholds are set, reaching either triggers compression (OR). If neither threshold is set, `compress_tool_results_limit` defaults to `3`.
</Note>

### Tool-Based Compression [#tool-based-compression]

Set `compress_tool_results_limit` when you have predictable tool call patterns and want compression to trigger after a fixed number of tool call results.

### Token-Based Compression [#token-based-compression]

Use `compress_token_limit` to trigger summarization based on estimated context size, especially when tool results vary significantly in size:

<CodeBlockTabs defaultValue="Agent">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="Agent">
      Agent
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="Team">
      Team
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="Agent">
    ```python
    from agno.agent import Agent
    from agno.compression.manager import CompressionManager
    from agno.models.openai import OpenAIResponses
    from agno.tools.hackernews import HackerNewsTools

    compression_manager = CompressionManager(
        model=OpenAIResponses(id="gpt-5.2"),
        compress_tool_results=True,
        compress_token_limit=5000,  # or compress_tool_results_limit
    )

    agent = Agent(
        model=OpenAIResponses(id="gpt-5.2"),
        tools=[HackerNewsTools()],
        compression_manager=compression_manager,
    )

    agent.print_response("Find HackerNews discussions about OpenAI, Anthropic, Google DeepMind, and Meta AI")
    ```
  </CodeBlockTab>

  <CodeBlockTab value="Team">
    ```python
    from agno.agent import Agent
    from agno.compression.manager import CompressionManager
    from agno.models.openai import OpenAIResponses
    from agno.team import Team
    from agno.tools.hackernews import HackerNewsTools

    compression_manager = CompressionManager(
        model=OpenAIResponses(id="gpt-5.2"),
        compress_tool_results=True,
        compress_token_limit=5000,  # or compress_tool_results_limit
    )

    web_agent = Agent(
        name="HackerNews Researcher",
        tools=[HackerNewsTools()],
    )

    team = Team(
        model=OpenAIResponses(id="gpt-5.2"),
        members=[web_agent],
        compression_manager=compression_manager,
    )

    team.print_response("Find HackerNews discussions about OpenAI, Anthropic, Google DeepMind, and Meta AI")
    ```
  </CodeBlockTab>
</CodeBlockTabs>

<Info>
  Token counting includes messages, tool definitions, and output schemas. See [Token Counting](/compression/token-counting) for details.
</Info>

## When to Use Context Compression [#when-to-use-context-compression]

**Best for:**

* Agents with tools that return verbose results (web search, APIs)
* Multi-step workflows with many tool calls
* Long-running sessions where context accumulates
* Production systems where cost matters

## Developer Resources [#developer-resources]

* [CompressionManager Reference](/reference/compression/compression-manager) - Full CompressionManager documentation
* [Agent Reference](/reference/agents/agent) - Agent parameter documentation
* [Team Reference](/reference/teams/team) - Team parameter documentation
