Skip to main content
With Anthropic’s context editing capabilities, you can automatically manage your context size. When your context grows larger, previous tool results and thinking blocks will be removed. This is useful to reduce costs, improve performance, and reduce the chances of hitting context limits.

Working example

anthropic_context_management.py
from agno.agent import Agent
from agno.models.anthropic import Claude
from agno.tools.hackernews import HackerNewsTools

agent = Agent(
    model=Claude(
        id="claude-sonnet-4-5",
        # Activate and configure the context management feature
        betas=["context-management-2025-06-27"],
        context_management={
            "edits": [
                {
                    "type": "clear_tool_uses_20250919",
                    "trigger": {"type": "tool_uses", "value": 2},
                    "keep": {"type": "tool_uses", "value": 1},
                }
            ]
        },
    ),
    instructions="You are a helpful assistant with access to the web.",
    tools=[HackerNewsTools()],
    session_id="context-editing",
    add_history_to_context=True,
    markdown=True,
)

agent.print_response(
    "Search for AI regulation in US. Make multiple searches to find the latest information."
)

# Display context management metrics
print("\n" + "=" * 60)
print("CONTEXT MANAGEMENT SUMMARY")
print("=" * 60)
response = agent.get_last_run_output()
if response and response.metrics:
    print(f"\nInput tokens: {response.metrics.input_tokens:,}")

# Print context management stats from the last message
if response and response.messages:
    for message in reversed(response.messages):
        if message.provider_data and "context_management" in message.provider_data:
            edits = message.provider_data["context_management"].get("applied_edits", [])
            if edits:
                print(
                    f"\n✅ Saved: {edits[-1].get('cleared_input_tokens', 0):,} tokens"
                )
                print(f"   Cleared: {edits[-1].get('cleared_tool_uses', 0)} tool uses")
                break

print("\n" + "=" * 60)

Usage

1

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate
2

Set your API key

export ANTHROPIC_API_KEY=xxx
3

Install dependencies

uv pip install -U anthropic agno
4

Run Agent

python anthropic_context_management.py