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 Agent
2from kern.models.anthropic import Claude
3from kern.tools.hackernews import HackerNewsTools
4
5agent = Agent(
6 model=Claude(
7 id="claude-sonnet-4-5",
8 # Activate and configure the context management feature
9 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)
26
27agent.print_response(
28 "Search for AI regulation in US. Make multiple searches to find the latest information."
29)
30
31# Display context management metrics
32print("\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:,}")
38
39# Print context management stats from the last message
40if 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 break
50
51print("\n" + "=" * 60)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set your API key

1export ANTHROPIC_API_KEY=xxx

Install dependencies

1uv pip install -U anthropic kern-ai

Run Agent

1python anthropic_context_management.py