Debian Codegraph @

examples/memory/basic.py

raw
1 import time
2 import threading
3 from typing import Optional
4
5 from pydantic import TypeAdapter
6
7 from anthropic import Anthropic
8 from anthropic.tools import BetaLocalFilesystemMemoryTool
9 from anthropic.types.beta import (
10 BetaMessageParam,
11 BetaContentBlockParam,
12 BetaMemoryTool20250818Command,
13 BetaMemoryTool20250818ViewCommand,
14 )
15 from anthropic.types.beta.beta_context_management_config_param import BetaContextManagementConfigParam
16
17 # Context management automatically clears old tool results to stay within token limits
18 # Triggers when input exceeds 30k tokens, keeps 3 tool uses after clearing
19 DEFAULT_CONTEXT_MANAGEMENT: BetaContextManagementConfigParam = {
20 "edits": [
21 {
22 "type": "clear_tool_uses_20250919",
23 # The below parameters are OPTIONAL:
24 # Trigger clearing when threshold is exceeded
25 "trigger": {"type": "input_tokens", "value": 30000},
26 # Number of tool uses to keep after clearing
27 "keep": {"type": "tool_uses", "value": 3},
28 # Optional: Clear at least this many tokens
29 "clear_at_least": {"type": "input_tokens", "value": 5000},
30 # Exclude these tools uses from being cleared
31 "exclude_tools": ["web_search"],
32 }
33 ]
34 }
35
36 DEFAULT_MEMORY_SYSTEM_PROMPT = """- ***DO NOT just store the conversation history**
37 - No need to mention your memory tool or what you are writing in it to the user, unless they ask
38 - Store facts about the user and their preferences
39 - Before responding, check memory to adjust technical depth and response style appropriately
40 - Keep memories up-to-date - remove outdated info, add new details as you learn them
41 - Use an xml format like <xml><name>John Doe</name></user></xml>"""
42
43
44 class Spinner:
45 def __init__(self, message: str = "Thinking"):
46 self.message = message
47 self.spinning = False
48 self.thread = None
49
50 def start(self):
51 self.spinning = True
52 self.thread = threading.Thread(target=self._spin)
53 self.thread.start()
54
55 def stop(self):
56 self.spinning = False
57 if self.thread:
58 self.thread.join()
59 print("\r" + " " * (len(self.message) + 10) + "\r", end="", flush=True)
60
61 def _spin(self):
62 chars = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
63 i = 0
64 while self.spinning:
65 print(f"\r{self.message} {chars[i % len(chars)]}", end="", flush=True)
66 i += 1
67 time.sleep(0.1)
68
69
70 def conversation_loop():
71 client = Anthropic()
72 memory = BetaLocalFilesystemMemoryTool()
73
74 messages: list[BetaMessageParam] = []
75
76 last_response_id: Optional[str] = None
77 last_usage = None
78
79 print("🧠 Claude with Memory & Web Search - Interactive Session")
80 print("Commands:")
81 print(" /quit or /exit - Exit the session")
82 print(" /clear - Start fresh conversation")
83 print(" /memory_view - See all memory files")
84 print(" /memory_clear - Delete all memory")
85 print(" /debug - View conversation history and token usage")
86
87 print(f"\n🧹 Context Management")
88 print("=" * 60)
89
90 while True:
91 try:
92 user_input = input("\nYou: ").strip()
93 except (EOFError, KeyboardInterrupt):
94 print("\nGoodbye!")
95 break
96
97 if user_input.lower() in ["/quit", "/exit"]:
98 print("Goodbye!")
99 break
100 elif user_input.lower() == "/clear":
101 messages = []
102 print("Conversation cleared!")
103 continue
104 elif user_input.lower() == "/memory_view":
105 result = memory.execute(BetaMemoryTool20250818ViewCommand(command="view", path="/memories"))
106 print("\n📁 Memory contents:")
107 print(result)
108 continue
109 elif user_input.lower() == "/memory_clear":
110 result = memory.clear_all_memory()
111 print(f"🗑️ {result}")
112 continue
113 elif user_input.lower() == "/debug":
114 print("\n🔍 Conversation history:")
115
116 if last_response_id:
117 print(f"📌 Last response ID: {last_response_id}")
118
119 if last_usage:
120 usage = last_usage
121 input_tokens = usage.get("input_tokens", 0)
122 cached_tokens = usage.get("cache_read_input_tokens", 0)
123 uncached_tokens = input_tokens - cached_tokens
124
125 print(f"📊 Last API call tokens:")
126 print(f" Total input: {input_tokens:,} tokens")
127 print(f" Cached: {cached_tokens:,} tokens")
128 print(f" Uncached: {uncached_tokens:,} tokens")
129
130 threshold = DEFAULT_CONTEXT_MANAGEMENT["edits"][0]["trigger"]["value"] # type: ignore
131 print(f" Context clearing threshold: {threshold:,} tokens")
132 if input_tokens >= threshold:
133 print(f" 🧹 Context clearing should trigger soon!")
134 elif input_tokens >= threshold * 0.8: # 80% of threshold #type: ignore
135 print(f" ⚠️ Approaching context clearing threshold!")
136
137 print("=" * 80)
138
139 for i, message in enumerate(messages):
140 role = message["role"].upper()
141 print(f"\n[{i + 1}] {role}:")
142 print("-" * 40)
143
144 content = message["content"]
145 if isinstance(content, str):
146 print(content[:500] + "..." if len(content) > 500 else content)
147 elif isinstance(content, list):
148 for block in content:
149 if isinstance(block, dict):
150 if block.get("type") in ["tool_use", "server_tool_use"]:
151 print(f"Tool: {block.get('name', 'unknown')}")
152 elif block.get("type") == "tool_result":
153 print(f"Tool Result: [content]")
154 elif block.get("type") == "text":
155 text = block.get("text", "")
156 print(f"Text: {text[:200]}..." if len(text) > 200 else f"Text: {text}")
157 print("=" * 80)
158 continue
159 elif not user_input:
160 continue
161
162 messages.append({"role": "user", "content": user_input})
163
164 print("\nClaude: ", end="", flush=True)
165
166 spinner = Spinner("Thinking")
167 spinner.start()
168
169 try:
170 runner = client.beta.messages.tool_runner(
171 betas=["context-management-2025-06-27"],
172 model="claude-sonnet-5-5",
173 max_tokens=2048,
174 system=DEFAULT_MEMORY_SYSTEM_PROMPT,
175 messages=messages,
176 tools=[memory],
177 context_management=DEFAULT_CONTEXT_MANAGEMENT,
178 )
179 except Exception:
180 spinner.stop()
181 raise
182
183 for message in runner:
184 spinner.stop()
185
186 last_response_id = message.id
187
188 if hasattr(message, "usage") and message.usage:
189 last_usage = message.usage.model_dump() if hasattr(message.usage, "model_dump") else dict(message.usage)
190
191 if message.context_management:
192 for edit in message.context_management.applied_edits:
193 print(f"\n🧹 [Context Management: {edit.type} applied]")
194
195 assistant_content: list[BetaContentBlockParam] = []
196 for content in message.content:
197 if content.type == "text":
198 print(content.text, end="", flush=True)
199 assistant_content.append({"type": "text", "text": content.text})
200
201 elif content.type == "tool_use" and content.name == "memory":
202 tool_input = TypeAdapter[BetaMemoryTool20250818Command](
203 BetaMemoryTool20250818Command
204 ).validate_python(content.input)
205
206 print(f"\n[Memory tool called: {tool_input.command}]")
207 assistant_content.append(
208 {
209 "type": "tool_use",
210 "id": content.id,
211 "name": content.name,
212 "input": content.input,
213 }
214 )
215
216 if assistant_content:
217 messages.append({"role": "assistant", "content": assistant_content})
218
219 tool_response = runner.generate_tool_call_response()
220 if tool_response and tool_response["content"]:
221 messages.append({"role": "user", "content": tool_response["content"]})
222
223 for result in tool_response["content"]:
224 if isinstance(result, dict) and result.get("type") == "tool_result":
225 print(f"[Tool result processed]")
226
227 print()
228
229
230 if __name__ == "__main__":
231 conversation_loop()