Context Editing

Clear older tool results from Claude's server-side context with Anthropic context editing.

from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.anthropic import Claude
from agno.tools.websearch import WebSearchTools

agent = Agent(
    model=Claude(
        id="claude-sonnet-4-5-20250929",
        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},
                }
            ]
        },
    ),
    db=SqliteDb(db_file="tmp/context_management.db"),
    instructions="Use web search to answer with current, sourced information.",
    tools=[WebSearchTools()],
    session_id="context-editing",
    add_history_to_context=True,
    markdown=True,
)

if __name__ == "__main__":
    agent.print_response(
        "Search for AI regulation in the US. Make at least three searches, then summarize the latest developments."
    )

    run = agent.get_last_run_output()
    if run and run.metrics:
        print(f"Input tokens: {run.metrics.input_tokens:,}")

    if run and run.messages:
        for message in reversed(run.messages):
            context_data = (message.provider_data or {}).get("context_management")
            if context_data:
                edits = context_data.get("applied_edits", [])
                if edits:
                    latest_edit = edits[-1]
                    print(
                        f"Cleared tool uses: {latest_edit.get('cleared_tool_uses', 0)}"
                    )
                    print(
                        f"Cleared input tokens: {latest_edit.get('cleared_input_tokens', 0):,}"
                    )
                    break

The clear_tool_uses_20250919 edit activates once the prompt contains more than two tool use/result pairs. It keeps the newest pair and clears older tool results. By default, Anthropic keeps the original tool-call inputs. Set clear_tool_inputs=True in the edit only when those inputs can also be removed.

Context editing runs on Anthropic's server before the request reaches Claude. The SQLite database stores Agno's session and run history independently of those server-side edits. Clearing content can invalidate the affected prompt-cache prefix.

Thinking blocks require a separate clear_thinking_20251015 edit. When both strategies are used, list the thinking edit first. Context-edit metrics are finalized at the end of a response, including a streamed response.

See Anthropic's context-editing documentation for strategy defaults and additional fields.

Run the Example

Set up your virtual environment

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

Install dependencies

uv pip install -U "agno[anthropic,ddg,sqlite]"

Set your API key

export ANTHROPIC_API_KEY="your_anthropic_api_key"

Save and run

Save the example as context_management.py, then run:

python context_management.py