Repository navigation
Expand file tree
/
Copy pathchat_with_memory.py
More file actions
103 lines (83 loc) · 3.07 KB
/
Copy pathchat_with_memory.py
File metadata and controls
103 lines (83 loc) · 3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env python3
"""End-to-end Claude API + MemDB memory tool example.
Two completely separate `tool_runner` invocations share state only through
MemDB. Session 1 stores a user preference; Session 2 — with no shared chat
history — recalls it via the MemDB-backed `memory_20250818` tool.
Run:
pip install -r requirements.txt
export ANTHROPIC_API_KEY=sk-ant-...
python3 chat_with_memory.py
Optional env:
MEMDB_URL default http://localhost:8080
CUBE_ID, USER_ID default python-chat-demo
MEMDB_SERVICE_SECRET only when MemDB AUTH_ENABLED=true
"""
from __future__ import annotations
import os
import sys
import anthropic
import requests
from memdb_claude_memory import MemDBMemoryTool
MEMDB_URL = os.getenv("MEMDB_URL", "http://localhost:8080")
CUBE_ID = os.getenv("CUBE_ID", "python-chat-demo")
USER_ID = os.getenv("USER_ID", "python-chat-demo")
SERVICE_SECRET = os.getenv("MEMDB_SERVICE_SECRET", "")
MODEL = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-5")
def check_memdb() -> None:
"""Fail fast if MemDB is not reachable."""
try:
r = requests.get(f"{MEMDB_URL}/health", timeout=5)
r.raise_for_status()
except Exception as exc: # noqa: BLE001 — startup probe, surface anything
print(f"ERROR: MemDB not reachable at {MEMDB_URL}: {exc}", file=sys.stderr)
print(
"Start it with: cd ~/deploy/server-config && docker compose up -d",
file=sys.stderr,
)
sys.exit(1)
print(f"MemDB reachable at {MEMDB_URL}\n")
def chat_once(client: anthropic.Anthropic, tool: MemDBMemoryTool, user_msg: str) -> str:
"""One independent conversation: no history carried over.
`tool_runner` drives the tool-use loop until Claude emits a final text
response. The adapter (`tool`) handles all `memory_save` / `memory_recall`
/ `memory_delete` calls transparently against MemDB.
"""
runner = client.beta.messages.tool_runner(
model=MODEL,
betas=["context-management-2025-06-27"],
max_tokens=1024,
tools=[tool],
messages=[{"role": "user", "content": user_msg}],
)
result = runner.until_done()
# Final assistant message is the last text block in the last response.
for block in reversed(result.content):
if getattr(block, "type", None) == "text":
return block.text
return "(no text response)"
def main() -> None:
check_memdb()
if not os.getenv("ANTHROPIC_API_KEY"):
print("ERROR: ANTHROPIC_API_KEY not set", file=sys.stderr)
sys.exit(1)
tool = MemDBMemoryTool(
memdb_url=MEMDB_URL,
cube_id=CUBE_ID,
user_id=USER_ID,
service_secret=SERVICE_SECRET,
)
client = anthropic.Anthropic()
print("Session 1 (store preference):")
print("Claude:", chat_once(
client,
tool,
"Remember that I prefer TypeScript over Python.",
))
print("\nSession 2 (fresh thread, recall):")
print("Claude:", chat_once(
client,
tool,
"What language do I prefer?",
))
if __name__ == "__main__":
main()