Context Editing
Automatically manage context size with Anthropic's context editing.
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
1from kern.agent import Agent2from kern.models.anthropic import Claude3from kern.tools.hackernews import HackerNewsTools45agent = Agent(6 model=Claude(7 id="claude-sonnet-4-5",8 # Activate and configure the context management feature9 betas=["context-management-2025-06-27"],10 context_management={11 "edits": [12 {13 "type": "clear_tool_uses_20250919",14 "trigger": {"type": "tool_uses", "value": 2},15 "keep": {"type": "tool_uses", "value": 1},16 }17 ]18 },19 ),20 instructions="You are a helpful assistant with access to the web.",21 tools=[HackerNewsTools()],22 session_id="context-editing",23 add_history_to_context=True,24 markdown=True,25)2627agent.print_response(28 "Search for AI regulation in US. Make multiple searches to find the latest information."29)3031# Display context management metrics32print("\n" + "=" * 60)33print("CONTEXT MANAGEMENT SUMMARY")34print("=" * 60)35response = agent.get_last_run_output()36if response and response.metrics:37 print(f"\nInput tokens: {response.metrics.input_tokens:,}")3839# Print context management stats from the last message40if response and response.messages:41 for message in reversed(response.messages):42 if message.provider_data and "context_management" in message.provider_data:43 edits = message.provider_data["context_management"].get("applied_edits", [])44 if edits:45 print(46 f"\n✅ Saved: {edits[-1].get('cleared_input_tokens', 0):,} tokens"47 )48 print(f" Cleared: {edits[-1].get('cleared_tool_uses', 0)} tool uses")49 break5051print("\n" + "=" * 60)Usage
Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateSet your API key
1export ANTHROPIC_API_KEY=xxxInstall dependencies
1uv pip install -U anthropic kern-aiRun Agent
1python anthropic_context_management.py