cathedral-langgraph 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cathedral_langgraph-0.1.0/PKG-INFO +69 -0
- cathedral_langgraph-0.1.0/README.md +47 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph/__init__.py +4 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph/checkpointer.py +347 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph.egg-info/PKG-INFO +69 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph.egg-info/SOURCES.txt +10 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph.egg-info/dependency_links.txt +1 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph.egg-info/requires.txt +8 -0
- cathedral_langgraph-0.1.0/cathedral_langgraph.egg-info/top_level.txt +1 -0
- cathedral_langgraph-0.1.0/pyproject.toml +34 -0
- cathedral_langgraph-0.1.0/setup.cfg +4 -0
- cathedral_langgraph-0.1.0/tests/test_checkpointer.py +175 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cathedral-langgraph
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangGraph checkpointer backed by Cathedral's persistent memory API
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://cathedral-ai.com
|
|
7
|
+
Project-URL: Repository, https://github.com/AILIFE1/cathedral-langgraph
|
|
8
|
+
Project-URL: Documentation, https://cathedral-ai.com/docs/langgraph
|
|
9
|
+
Keywords: langgraph,cathedral,memory,checkpointer,ai,agents
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: langgraph>=0.2.0
|
|
16
|
+
Requires-Dist: langchain-core>=0.2.0
|
|
17
|
+
Requires-Dist: requests>=2.28.0
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-mock; extra == "dev"
|
|
22
|
+
|
|
23
|
+
# cathedral-langgraph
|
|
24
|
+
|
|
25
|
+
LangGraph checkpointer backed by [Cathedral](https://cathedral-ai.com)'s persistent memory API.
|
|
26
|
+
|
|
27
|
+
Persists LangGraph graph state to Cathedral, giving agents verifiable, drift-detectable state across sessions.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cathedral-langgraph
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from cathedral_langgraph import CathedralCheckpointer
|
|
39
|
+
from langgraph.graph import StateGraph, MessagesState
|
|
40
|
+
|
|
41
|
+
checkpointer = CathedralCheckpointer(api_key="cathedral_your_key_here")
|
|
42
|
+
|
|
43
|
+
builder = StateGraph(MessagesState)
|
|
44
|
+
# ... add nodes and edges ...
|
|
45
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
46
|
+
|
|
47
|
+
# thread_id identifies the conversation/session
|
|
48
|
+
config = {"configurable": {"thread_id": "user-123"}}
|
|
49
|
+
result = graph.invoke({"messages": [{"role": "user", "content": "Hello"}]}, config=config)
|
|
50
|
+
|
|
51
|
+
# Resume the same thread later — state is restored from Cathedral
|
|
52
|
+
result2 = graph.invoke({"messages": [{"role": "user", "content": "What did I just say?"}]}, config=config)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## How it works
|
|
56
|
+
|
|
57
|
+
- Each LangGraph **thread** maps to a set of Cathedral memories tagged with the thread ID.
|
|
58
|
+
- Checkpoint state is **gzip-compressed and base64-encoded** to fit within Cathedral's 16 KB content limit.
|
|
59
|
+
- Intermediate writes (`put_writes`) are stored as separate memories and associated with their checkpoint.
|
|
60
|
+
- Retrieval uses Cathedral's tag-based search to find the latest checkpoint for a thread.
|
|
61
|
+
|
|
62
|
+
## Cathedral benefits
|
|
63
|
+
|
|
64
|
+
Because state is stored in Cathedral, you also get:
|
|
65
|
+
|
|
66
|
+
- **Drift detection** — `GET /drift` shows if checkpoint memories diverged from baseline
|
|
67
|
+
- **Audit log** — every memory mutation is logged at `GET /audit`
|
|
68
|
+
- **BCH anchoring** — optional blockchain provenance for checkpoint state
|
|
69
|
+
- **Multi-agent** — multiple LangGraph instances can share state via Cathedral Shared Spaces
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# cathedral-langgraph
|
|
2
|
+
|
|
3
|
+
LangGraph checkpointer backed by [Cathedral](https://cathedral-ai.com)'s persistent memory API.
|
|
4
|
+
|
|
5
|
+
Persists LangGraph graph state to Cathedral, giving agents verifiable, drift-detectable state across sessions.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install cathedral-langgraph
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from cathedral_langgraph import CathedralCheckpointer
|
|
17
|
+
from langgraph.graph import StateGraph, MessagesState
|
|
18
|
+
|
|
19
|
+
checkpointer = CathedralCheckpointer(api_key="cathedral_your_key_here")
|
|
20
|
+
|
|
21
|
+
builder = StateGraph(MessagesState)
|
|
22
|
+
# ... add nodes and edges ...
|
|
23
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
24
|
+
|
|
25
|
+
# thread_id identifies the conversation/session
|
|
26
|
+
config = {"configurable": {"thread_id": "user-123"}}
|
|
27
|
+
result = graph.invoke({"messages": [{"role": "user", "content": "Hello"}]}, config=config)
|
|
28
|
+
|
|
29
|
+
# Resume the same thread later — state is restored from Cathedral
|
|
30
|
+
result2 = graph.invoke({"messages": [{"role": "user", "content": "What did I just say?"}]}, config=config)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## How it works
|
|
34
|
+
|
|
35
|
+
- Each LangGraph **thread** maps to a set of Cathedral memories tagged with the thread ID.
|
|
36
|
+
- Checkpoint state is **gzip-compressed and base64-encoded** to fit within Cathedral's 16 KB content limit.
|
|
37
|
+
- Intermediate writes (`put_writes`) are stored as separate memories and associated with their checkpoint.
|
|
38
|
+
- Retrieval uses Cathedral's tag-based search to find the latest checkpoint for a thread.
|
|
39
|
+
|
|
40
|
+
## Cathedral benefits
|
|
41
|
+
|
|
42
|
+
Because state is stored in Cathedral, you also get:
|
|
43
|
+
|
|
44
|
+
- **Drift detection** — `GET /drift` shows if checkpoint memories diverged from baseline
|
|
45
|
+
- **Audit log** — every memory mutation is logged at `GET /audit`
|
|
46
|
+
- **BCH anchoring** — optional blockchain provenance for checkpoint state
|
|
47
|
+
- **Multi-agent** — multiple LangGraph instances can share state via Cathedral Shared Spaces
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cathedral checkpointer for LangGraph.
|
|
3
|
+
|
|
4
|
+
Persists LangGraph graph state to Cathedral's memory API, giving agents
|
|
5
|
+
verifiable, drift-detectable state across sessions.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
from cathedral_langgraph import CathedralCheckpointer
|
|
9
|
+
|
|
10
|
+
checkpointer = CathedralCheckpointer(api_key="cathedral_...")
|
|
11
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
12
|
+
result = graph.invoke({"messages": [...]}, config={"configurable": {"thread_id": "my-thread"}})
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import base64
|
|
19
|
+
import gzip
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Tuple
|
|
24
|
+
|
|
25
|
+
import requests
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from langgraph.checkpoint.base import (
|
|
31
|
+
BaseCheckpointSaver,
|
|
32
|
+
Checkpoint,
|
|
33
|
+
CheckpointMetadata,
|
|
34
|
+
CheckpointTuple,
|
|
35
|
+
ChannelVersions,
|
|
36
|
+
)
|
|
37
|
+
from langchain_core.runnables import RunnableConfig
|
|
38
|
+
except ImportError as e:
|
|
39
|
+
raise ImportError(
|
|
40
|
+
"langgraph and langchain-core are required. "
|
|
41
|
+
"Install with: pip install langgraph langchain-core"
|
|
42
|
+
) from e
|
|
43
|
+
|
|
44
|
+
CATEGORY_CHECKPOINT = "langgraph"
|
|
45
|
+
CATEGORY_WRITES = "langgraph_write"
|
|
46
|
+
MAX_CONTENT_CHARS = 15000 # leave headroom below the 16384 API limit
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CathedralCheckpointer(BaseCheckpointSaver):
|
|
50
|
+
"""
|
|
51
|
+
LangGraph checkpointer backed by Cathedral's memory API.
|
|
52
|
+
|
|
53
|
+
Each LangGraph thread maps to a set of Cathedral memories tagged with the
|
|
54
|
+
thread_id. Checkpoint state is gzip-compressed and base64-encoded to fit
|
|
55
|
+
within Cathedral's 16 KB content limit while supporting large agent states.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
api_key: str,
|
|
61
|
+
base_url: str = "https://cathedral-ai.com/api/v1",
|
|
62
|
+
timeout: int = 30,
|
|
63
|
+
) -> None:
|
|
64
|
+
super().__init__()
|
|
65
|
+
self.api_key = api_key
|
|
66
|
+
self.base_url = base_url.rstrip("/")
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
self._session = requests.Session()
|
|
69
|
+
self._session.headers.update({
|
|
70
|
+
"Authorization": f"Bearer {api_key}",
|
|
71
|
+
"Content-Type": "application/json",
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
# ------------------------------------------------------------------ #
|
|
75
|
+
# Internal helpers #
|
|
76
|
+
# ------------------------------------------------------------------ #
|
|
77
|
+
|
|
78
|
+
def _pack(self, checkpoint: Checkpoint, metadata: CheckpointMetadata,
|
|
79
|
+
thread_id: str, parent_checkpoint_id: Optional[str]) -> str:
|
|
80
|
+
"""Serialize checkpoint to a compressed, base64-encoded string."""
|
|
81
|
+
payload = {
|
|
82
|
+
"checkpoint": checkpoint,
|
|
83
|
+
"metadata": metadata,
|
|
84
|
+
"thread_id": thread_id,
|
|
85
|
+
"parent_checkpoint_id": parent_checkpoint_id,
|
|
86
|
+
"step": metadata.get("step", 0),
|
|
87
|
+
}
|
|
88
|
+
raw = json.dumps(payload, separators=(",", ":"), default=str)
|
|
89
|
+
compressed = gzip.compress(raw.encode("utf-8"), compresslevel=6)
|
|
90
|
+
encoded = base64.b64encode(compressed).decode("ascii")
|
|
91
|
+
result = json.dumps({"v": 1, "z": True, "d": encoded}, separators=(",", ":"))
|
|
92
|
+
if len(result) > MAX_CONTENT_CHARS:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
f"Checkpoint for thread '{thread_id}' step {metadata.get('step')} "
|
|
95
|
+
f"is {len(result)} chars after compression, exceeding the {MAX_CONTENT_CHARS} "
|
|
96
|
+
f"char Cathedral limit. Consider reducing graph state size."
|
|
97
|
+
)
|
|
98
|
+
return result
|
|
99
|
+
|
|
100
|
+
def _unpack(self, content: str) -> Tuple[Checkpoint, CheckpointMetadata, str, Optional[str]]:
|
|
101
|
+
"""Deserialize a checkpoint from stored content."""
|
|
102
|
+
wrapper = json.loads(content)
|
|
103
|
+
if wrapper.get("z"):
|
|
104
|
+
raw = gzip.decompress(base64.b64decode(wrapper["d"])).decode("utf-8")
|
|
105
|
+
payload = json.loads(raw)
|
|
106
|
+
else:
|
|
107
|
+
payload = wrapper
|
|
108
|
+
return (
|
|
109
|
+
payload["checkpoint"],
|
|
110
|
+
payload["metadata"],
|
|
111
|
+
payload["thread_id"],
|
|
112
|
+
payload.get("parent_checkpoint_id"),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def _thread_tag(self, thread_id: str, checkpoint_ns: str) -> str:
|
|
116
|
+
ns = f":{checkpoint_ns}" if checkpoint_ns else ""
|
|
117
|
+
return f"lg:{thread_id}{ns}"
|
|
118
|
+
|
|
119
|
+
def _checkpoint_tag(self, checkpoint_id: str) -> str:
|
|
120
|
+
return f"lgc:{checkpoint_id}"
|
|
121
|
+
|
|
122
|
+
def _make_checkpoint_config(
|
|
123
|
+
self, thread_id: str, checkpoint_ns: str, checkpoint_id: str
|
|
124
|
+
) -> RunnableConfig:
|
|
125
|
+
return {
|
|
126
|
+
"configurable": {
|
|
127
|
+
"thread_id": thread_id,
|
|
128
|
+
"checkpoint_ns": checkpoint_ns,
|
|
129
|
+
"checkpoint_id": checkpoint_id,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
def _memory_to_tuple(self, mem: Dict[str, Any], thread_id: str, checkpoint_ns: str
|
|
134
|
+
) -> Optional[CheckpointTuple]:
|
|
135
|
+
try:
|
|
136
|
+
checkpoint, metadata, _tid, parent_cid = self._unpack(mem["content"])
|
|
137
|
+
except Exception as exc:
|
|
138
|
+
logger.warning("Failed to deserialize checkpoint memory %s: %s", mem.get("id"), exc)
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
checkpoint_id = checkpoint.get("id", mem["id"])
|
|
142
|
+
config = self._make_checkpoint_config(thread_id, checkpoint_ns, checkpoint_id)
|
|
143
|
+
parent_config = (
|
|
144
|
+
self._make_checkpoint_config(thread_id, checkpoint_ns, parent_cid)
|
|
145
|
+
if parent_cid else None
|
|
146
|
+
)
|
|
147
|
+
return CheckpointTuple(
|
|
148
|
+
config=config,
|
|
149
|
+
checkpoint=checkpoint,
|
|
150
|
+
metadata=metadata,
|
|
151
|
+
parent_config=parent_config,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# ------------------------------------------------------------------ #
|
|
155
|
+
# Cathedral API calls #
|
|
156
|
+
# ------------------------------------------------------------------ #
|
|
157
|
+
|
|
158
|
+
def _search_memories(self, tag: str, category: str, limit: int = 100) -> List[Dict]:
|
|
159
|
+
resp = self._session.get(
|
|
160
|
+
f"{self.base_url}/memories",
|
|
161
|
+
params={"tag": tag, "category": category, "limit": limit, "sort": "recent"},
|
|
162
|
+
timeout=self.timeout,
|
|
163
|
+
)
|
|
164
|
+
if resp.status_code != 200:
|
|
165
|
+
logger.warning("Cathedral memories GET %s: %s %s", resp.url, resp.status_code, resp.text[:200])
|
|
166
|
+
return []
|
|
167
|
+
data = resp.json()
|
|
168
|
+
return data.get("memories", data) if isinstance(data, dict) else data
|
|
169
|
+
|
|
170
|
+
def _store_memory(self, content: str, category: str, tags: List[str]) -> Optional[str]:
|
|
171
|
+
resp = self._session.post(
|
|
172
|
+
f"{self.base_url}/memories",
|
|
173
|
+
json={
|
|
174
|
+
"content": content,
|
|
175
|
+
"category": category,
|
|
176
|
+
"tags": tags,
|
|
177
|
+
"importance": 1.0,
|
|
178
|
+
"source_type": "api",
|
|
179
|
+
},
|
|
180
|
+
timeout=self.timeout,
|
|
181
|
+
)
|
|
182
|
+
if resp.status_code not in (200, 201):
|
|
183
|
+
raise RuntimeError(
|
|
184
|
+
f"Cathedral store failed ({resp.status_code}): {resp.text[:300]}"
|
|
185
|
+
)
|
|
186
|
+
data = resp.json()
|
|
187
|
+
return data.get("id") or data.get("memory_id")
|
|
188
|
+
|
|
189
|
+
# ------------------------------------------------------------------ #
|
|
190
|
+
# BaseCheckpointSaver interface — sync #
|
|
191
|
+
# ------------------------------------------------------------------ #
|
|
192
|
+
|
|
193
|
+
def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
194
|
+
cfg = config.get("configurable", {})
|
|
195
|
+
thread_id = cfg.get("thread_id", "")
|
|
196
|
+
checkpoint_ns = cfg.get("checkpoint_ns", "")
|
|
197
|
+
checkpoint_id = cfg.get("checkpoint_id")
|
|
198
|
+
|
|
199
|
+
if checkpoint_id:
|
|
200
|
+
# Fetch a specific checkpoint by its ID tag
|
|
201
|
+
memories = self._search_memories(
|
|
202
|
+
tag=self._checkpoint_tag(checkpoint_id),
|
|
203
|
+
category=CATEGORY_CHECKPOINT,
|
|
204
|
+
limit=1,
|
|
205
|
+
)
|
|
206
|
+
else:
|
|
207
|
+
# Fetch the most recent checkpoint for this thread
|
|
208
|
+
memories = self._search_memories(
|
|
209
|
+
tag=self._thread_tag(thread_id, checkpoint_ns),
|
|
210
|
+
category=CATEGORY_CHECKPOINT,
|
|
211
|
+
limit=1,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
if not memories:
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
return self._memory_to_tuple(memories[0], thread_id, checkpoint_ns)
|
|
218
|
+
|
|
219
|
+
def list(
|
|
220
|
+
self,
|
|
221
|
+
config: Optional[RunnableConfig],
|
|
222
|
+
*,
|
|
223
|
+
filter: Optional[Dict[str, Any]] = None,
|
|
224
|
+
before: Optional[RunnableConfig] = None,
|
|
225
|
+
limit: Optional[int] = None,
|
|
226
|
+
) -> Iterator[CheckpointTuple]:
|
|
227
|
+
cfg = (config or {}).get("configurable", {})
|
|
228
|
+
thread_id = cfg.get("thread_id", "")
|
|
229
|
+
checkpoint_ns = cfg.get("checkpoint_ns", "")
|
|
230
|
+
|
|
231
|
+
memories = self._search_memories(
|
|
232
|
+
tag=self._thread_tag(thread_id, checkpoint_ns),
|
|
233
|
+
category=CATEGORY_CHECKPOINT,
|
|
234
|
+
limit=limit or 100,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
before_id = (before or {}).get("configurable", {}).get("checkpoint_id")
|
|
238
|
+
emitting = before_id is None
|
|
239
|
+
|
|
240
|
+
for mem in memories:
|
|
241
|
+
tpl = self._memory_to_tuple(mem, thread_id, checkpoint_ns)
|
|
242
|
+
if tpl is None:
|
|
243
|
+
continue
|
|
244
|
+
if not emitting:
|
|
245
|
+
if tpl.checkpoint.get("id") == before_id:
|
|
246
|
+
emitting = True
|
|
247
|
+
continue
|
|
248
|
+
if filter:
|
|
249
|
+
if not all(tpl.metadata.get(k) == v for k, v in filter.items()):
|
|
250
|
+
continue
|
|
251
|
+
yield tpl
|
|
252
|
+
|
|
253
|
+
def put(
|
|
254
|
+
self,
|
|
255
|
+
config: RunnableConfig,
|
|
256
|
+
checkpoint: Checkpoint,
|
|
257
|
+
metadata: CheckpointMetadata,
|
|
258
|
+
new_versions: ChannelVersions,
|
|
259
|
+
) -> RunnableConfig:
|
|
260
|
+
cfg = config.get("configurable", {})
|
|
261
|
+
thread_id = cfg.get("thread_id", "")
|
|
262
|
+
checkpoint_ns = cfg.get("checkpoint_ns", "")
|
|
263
|
+
parent_checkpoint_id = cfg.get("checkpoint_id")
|
|
264
|
+
checkpoint_id = checkpoint.get("id", "")
|
|
265
|
+
|
|
266
|
+
content = self._pack(checkpoint, metadata, thread_id, parent_checkpoint_id)
|
|
267
|
+
tags = [
|
|
268
|
+
self._thread_tag(thread_id, checkpoint_ns),
|
|
269
|
+
self._checkpoint_tag(checkpoint_id),
|
|
270
|
+
]
|
|
271
|
+
self._store_memory(content, CATEGORY_CHECKPOINT, tags)
|
|
272
|
+
|
|
273
|
+
return self._make_checkpoint_config(thread_id, checkpoint_ns, checkpoint_id)
|
|
274
|
+
|
|
275
|
+
def put_writes(
|
|
276
|
+
self,
|
|
277
|
+
config: RunnableConfig,
|
|
278
|
+
writes: Sequence[Tuple[str, Any]],
|
|
279
|
+
task_id: str,
|
|
280
|
+
) -> None:
|
|
281
|
+
"""Persist intermediate writes for a checkpoint step."""
|
|
282
|
+
cfg = config.get("configurable", {})
|
|
283
|
+
thread_id = cfg.get("thread_id", "")
|
|
284
|
+
checkpoint_id = cfg.get("checkpoint_id", "")
|
|
285
|
+
|
|
286
|
+
payload = json.dumps(
|
|
287
|
+
{"writes": [(c, v) for c, v in writes], "task_id": task_id},
|
|
288
|
+
separators=(",", ":"), default=str,
|
|
289
|
+
)
|
|
290
|
+
content_hash = hashlib.sha256(payload.encode()).hexdigest()
|
|
291
|
+
wrapper = json.dumps(
|
|
292
|
+
{"v": 1, "thread_id": thread_id, "checkpoint_id": checkpoint_id,
|
|
293
|
+
"task_id": task_id, "content_hash": content_hash, "writes": payload},
|
|
294
|
+
separators=(",", ":"),
|
|
295
|
+
)
|
|
296
|
+
if len(wrapper) > MAX_CONTENT_CHARS:
|
|
297
|
+
logger.warning(
|
|
298
|
+
"put_writes for checkpoint %s exceeds size limit; writes not persisted", checkpoint_id
|
|
299
|
+
)
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
tags = [
|
|
303
|
+
self._checkpoint_tag(checkpoint_id),
|
|
304
|
+
f"lgt:{task_id}",
|
|
305
|
+
]
|
|
306
|
+
try:
|
|
307
|
+
self._store_memory(wrapper, CATEGORY_WRITES, tags)
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
logger.warning("put_writes storage failed: %s", exc)
|
|
310
|
+
|
|
311
|
+
# ------------------------------------------------------------------ #
|
|
312
|
+
# BaseCheckpointSaver interface — async #
|
|
313
|
+
# ------------------------------------------------------------------ #
|
|
314
|
+
|
|
315
|
+
async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
316
|
+
return await asyncio.to_thread(self.get_tuple, config)
|
|
317
|
+
|
|
318
|
+
async def alist(
|
|
319
|
+
self,
|
|
320
|
+
config: Optional[RunnableConfig],
|
|
321
|
+
*,
|
|
322
|
+
filter: Optional[Dict[str, Any]] = None,
|
|
323
|
+
before: Optional[RunnableConfig] = None,
|
|
324
|
+
limit: Optional[int] = None,
|
|
325
|
+
) -> AsyncIterator[CheckpointTuple]:
|
|
326
|
+
results = await asyncio.to_thread(
|
|
327
|
+
lambda: list(self.list(config, filter=filter, before=before, limit=limit))
|
|
328
|
+
)
|
|
329
|
+
for item in results:
|
|
330
|
+
yield item
|
|
331
|
+
|
|
332
|
+
async def aput(
|
|
333
|
+
self,
|
|
334
|
+
config: RunnableConfig,
|
|
335
|
+
checkpoint: Checkpoint,
|
|
336
|
+
metadata: CheckpointMetadata,
|
|
337
|
+
new_versions: ChannelVersions,
|
|
338
|
+
) -> RunnableConfig:
|
|
339
|
+
return await asyncio.to_thread(self.put, config, checkpoint, metadata, new_versions)
|
|
340
|
+
|
|
341
|
+
async def aput_writes(
|
|
342
|
+
self,
|
|
343
|
+
config: RunnableConfig,
|
|
344
|
+
writes: Sequence[Tuple[str, Any]],
|
|
345
|
+
task_id: str,
|
|
346
|
+
) -> None:
|
|
347
|
+
await asyncio.to_thread(self.put_writes, config, writes, task_id)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cathedral-langgraph
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangGraph checkpointer backed by Cathedral's persistent memory API
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://cathedral-ai.com
|
|
7
|
+
Project-URL: Repository, https://github.com/AILIFE1/cathedral-langgraph
|
|
8
|
+
Project-URL: Documentation, https://cathedral-ai.com/docs/langgraph
|
|
9
|
+
Keywords: langgraph,cathedral,memory,checkpointer,ai,agents
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: langgraph>=0.2.0
|
|
16
|
+
Requires-Dist: langchain-core>=0.2.0
|
|
17
|
+
Requires-Dist: requests>=2.28.0
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-mock; extra == "dev"
|
|
22
|
+
|
|
23
|
+
# cathedral-langgraph
|
|
24
|
+
|
|
25
|
+
LangGraph checkpointer backed by [Cathedral](https://cathedral-ai.com)'s persistent memory API.
|
|
26
|
+
|
|
27
|
+
Persists LangGraph graph state to Cathedral, giving agents verifiable, drift-detectable state across sessions.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install cathedral-langgraph
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from cathedral_langgraph import CathedralCheckpointer
|
|
39
|
+
from langgraph.graph import StateGraph, MessagesState
|
|
40
|
+
|
|
41
|
+
checkpointer = CathedralCheckpointer(api_key="cathedral_your_key_here")
|
|
42
|
+
|
|
43
|
+
builder = StateGraph(MessagesState)
|
|
44
|
+
# ... add nodes and edges ...
|
|
45
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
46
|
+
|
|
47
|
+
# thread_id identifies the conversation/session
|
|
48
|
+
config = {"configurable": {"thread_id": "user-123"}}
|
|
49
|
+
result = graph.invoke({"messages": [{"role": "user", "content": "Hello"}]}, config=config)
|
|
50
|
+
|
|
51
|
+
# Resume the same thread later — state is restored from Cathedral
|
|
52
|
+
result2 = graph.invoke({"messages": [{"role": "user", "content": "What did I just say?"}]}, config=config)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## How it works
|
|
56
|
+
|
|
57
|
+
- Each LangGraph **thread** maps to a set of Cathedral memories tagged with the thread ID.
|
|
58
|
+
- Checkpoint state is **gzip-compressed and base64-encoded** to fit within Cathedral's 16 KB content limit.
|
|
59
|
+
- Intermediate writes (`put_writes`) are stored as separate memories and associated with their checkpoint.
|
|
60
|
+
- Retrieval uses Cathedral's tag-based search to find the latest checkpoint for a thread.
|
|
61
|
+
|
|
62
|
+
## Cathedral benefits
|
|
63
|
+
|
|
64
|
+
Because state is stored in Cathedral, you also get:
|
|
65
|
+
|
|
66
|
+
- **Drift detection** — `GET /drift` shows if checkpoint memories diverged from baseline
|
|
67
|
+
- **Audit log** — every memory mutation is logged at `GET /audit`
|
|
68
|
+
- **BCH anchoring** — optional blockchain provenance for checkpoint state
|
|
69
|
+
- **Multi-agent** — multiple LangGraph instances can share state via Cathedral Shared Spaces
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
cathedral_langgraph/__init__.py
|
|
4
|
+
cathedral_langgraph/checkpointer.py
|
|
5
|
+
cathedral_langgraph.egg-info/PKG-INFO
|
|
6
|
+
cathedral_langgraph.egg-info/SOURCES.txt
|
|
7
|
+
cathedral_langgraph.egg-info/dependency_links.txt
|
|
8
|
+
cathedral_langgraph.egg-info/requires.txt
|
|
9
|
+
cathedral_langgraph.egg-info/top_level.txt
|
|
10
|
+
tests/test_checkpointer.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cathedral_langgraph
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cathedral-langgraph"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "LangGraph checkpointer backed by Cathedral's persistent memory API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
keywords = ["langgraph", "cathedral", "memory", "checkpointer", "ai", "agents"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
17
|
+
]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"langgraph>=0.2.0",
|
|
20
|
+
"langchain-core>=0.2.0",
|
|
21
|
+
"requests>=2.28.0",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
dev = ["pytest", "pytest-asyncio", "pytest-mock"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://cathedral-ai.com"
|
|
29
|
+
Repository = "https://github.com/AILIFE1/cathedral-langgraph"
|
|
30
|
+
Documentation = "https://cathedral-ai.com/docs/langgraph"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.packages.find]
|
|
33
|
+
where = ["."]
|
|
34
|
+
include = ["cathedral_langgraph*"]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Tests for CathedralCheckpointer."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import uuid
|
|
5
|
+
from unittest.mock import MagicMock, patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from cathedral_langgraph import CathedralCheckpointer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _make_checkpoint(step: int = 0) -> dict:
|
|
13
|
+
return {
|
|
14
|
+
"v": 1,
|
|
15
|
+
"id": str(uuid.uuid4()),
|
|
16
|
+
"ts": "2026-12-06T10:00:00+00:00",
|
|
17
|
+
"channel_values": {"messages": [{"role": "user", "content": f"step {step}"}]},
|
|
18
|
+
"channel_versions": {"messages": step},
|
|
19
|
+
"versions_seen": {},
|
|
20
|
+
"pending_sends": [],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _make_metadata(step: int = 0) -> dict:
|
|
25
|
+
return {"source": "loop", "step": step, "writes": {}, "parents": {}}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _make_config(thread_id: str = "test-thread", checkpoint_id: str = None) -> dict:
|
|
29
|
+
cfg = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
|
30
|
+
if checkpoint_id:
|
|
31
|
+
cfg["configurable"]["checkpoint_id"] = checkpoint_id
|
|
32
|
+
return cfg
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@pytest.fixture
|
|
36
|
+
def checkpointer():
|
|
37
|
+
return CathedralCheckpointer(api_key="cathedral_test", base_url="https://cathedral-ai.com/api/v1")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TestPackUnpack:
|
|
41
|
+
def test_roundtrip(self, checkpointer):
|
|
42
|
+
cp = _make_checkpoint(step=3)
|
|
43
|
+
meta = _make_metadata(step=3)
|
|
44
|
+
content = checkpointer._pack(cp, meta, "thread-1", "parent-123")
|
|
45
|
+
checkpoint2, metadata2, tid, parent = checkpointer._unpack(content)
|
|
46
|
+
assert checkpoint2["id"] == cp["id"]
|
|
47
|
+
assert metadata2["step"] == 3
|
|
48
|
+
assert tid == "thread-1"
|
|
49
|
+
assert parent == "parent-123"
|
|
50
|
+
|
|
51
|
+
def test_compresses(self, checkpointer):
|
|
52
|
+
cp = _make_checkpoint()
|
|
53
|
+
meta = _make_metadata()
|
|
54
|
+
# Large state
|
|
55
|
+
cp["channel_values"]["big"] = "x" * 5000
|
|
56
|
+
content = checkpointer._pack(cp, meta, "t", None)
|
|
57
|
+
wrapper = json.loads(content)
|
|
58
|
+
assert wrapper["z"] is True
|
|
59
|
+
assert len(content) < 5000 # compressed is smaller than raw
|
|
60
|
+
|
|
61
|
+
def test_oversized_raises(self, checkpointer):
|
|
62
|
+
import uuid
|
|
63
|
+
cp = _make_checkpoint()
|
|
64
|
+
meta = _make_metadata()
|
|
65
|
+
# Use unique UUIDs — high entropy, compresses poorly
|
|
66
|
+
cp["channel_values"]["giant"] = [str(uuid.uuid4()) for _ in range(5_000)]
|
|
67
|
+
with pytest.raises(ValueError, match="exceeding"):
|
|
68
|
+
checkpointer._pack(cp, meta, "t", None)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class TestGetTuple:
|
|
72
|
+
def test_returns_none_when_empty(self, checkpointer):
|
|
73
|
+
with patch.object(checkpointer, "_search_memories", return_value=[]):
|
|
74
|
+
result = checkpointer.get_tuple(_make_config())
|
|
75
|
+
assert result is None
|
|
76
|
+
|
|
77
|
+
def test_returns_tuple_from_memory(self, checkpointer):
|
|
78
|
+
cp = _make_checkpoint(step=1)
|
|
79
|
+
meta = _make_metadata(step=1)
|
|
80
|
+
content = checkpointer._pack(cp, meta, "test-thread", None)
|
|
81
|
+
mem = {"id": "mem-1", "content": content}
|
|
82
|
+
|
|
83
|
+
with patch.object(checkpointer, "_search_memories", return_value=[mem]):
|
|
84
|
+
result = checkpointer.get_tuple(_make_config("test-thread"))
|
|
85
|
+
|
|
86
|
+
assert result is not None
|
|
87
|
+
assert result.checkpoint["id"] == cp["id"]
|
|
88
|
+
assert result.metadata["step"] == 1
|
|
89
|
+
assert result.parent_config is None
|
|
90
|
+
|
|
91
|
+
def test_includes_parent_config(self, checkpointer):
|
|
92
|
+
cp = _make_checkpoint(step=2)
|
|
93
|
+
meta = _make_metadata(step=2)
|
|
94
|
+
content = checkpointer._pack(cp, meta, "test-thread", "parent-abc")
|
|
95
|
+
mem = {"id": "mem-2", "content": content}
|
|
96
|
+
|
|
97
|
+
with patch.object(checkpointer, "_search_memories", return_value=[mem]):
|
|
98
|
+
result = checkpointer.get_tuple(_make_config("test-thread"))
|
|
99
|
+
|
|
100
|
+
assert result.parent_config["configurable"]["checkpoint_id"] == "parent-abc"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TestPut:
|
|
104
|
+
def test_stores_memory_and_returns_config(self, checkpointer):
|
|
105
|
+
cp = _make_checkpoint(step=5)
|
|
106
|
+
meta = _make_metadata(step=5)
|
|
107
|
+
config = _make_config("thread-put")
|
|
108
|
+
|
|
109
|
+
with patch.object(checkpointer, "_store_memory", return_value="new-mem-id") as mock_store:
|
|
110
|
+
result = checkpointer.put(config, cp, meta, {})
|
|
111
|
+
|
|
112
|
+
mock_store.assert_called_once()
|
|
113
|
+
call_args = mock_store.call_args
|
|
114
|
+
category = call_args[0][1]
|
|
115
|
+
tags = call_args[0][2]
|
|
116
|
+
|
|
117
|
+
assert category == "langgraph"
|
|
118
|
+
assert any("thread-put" in t for t in tags)
|
|
119
|
+
assert any(cp["id"] in t for t in tags)
|
|
120
|
+
assert result["configurable"]["thread_id"] == "thread-put"
|
|
121
|
+
assert result["configurable"]["checkpoint_id"] == cp["id"]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class TestList:
|
|
125
|
+
def test_yields_all_memories_for_thread(self, checkpointer):
|
|
126
|
+
memories = []
|
|
127
|
+
for i in range(3):
|
|
128
|
+
cp = _make_checkpoint(step=i)
|
|
129
|
+
meta = _make_metadata(step=i)
|
|
130
|
+
content = checkpointer._pack(cp, meta, "list-thread", None)
|
|
131
|
+
memories.append({"id": f"mem-{i}", "content": content})
|
|
132
|
+
|
|
133
|
+
with patch.object(checkpointer, "_search_memories", return_value=memories):
|
|
134
|
+
results = list(checkpointer.list(_make_config("list-thread")))
|
|
135
|
+
|
|
136
|
+
assert len(results) == 3
|
|
137
|
+
|
|
138
|
+
def test_before_filter(self, checkpointer):
|
|
139
|
+
checkpoints = [_make_checkpoint(step=i) for i in range(3)]
|
|
140
|
+
memories = []
|
|
141
|
+
for cp in checkpoints:
|
|
142
|
+
content = checkpointer._pack(cp, _make_metadata(step=0), "t", None)
|
|
143
|
+
memories.append({"id": cp["id"], "content": content})
|
|
144
|
+
|
|
145
|
+
before_config = {"configurable": {"checkpoint_id": checkpoints[1]["id"]}}
|
|
146
|
+
with patch.object(checkpointer, "_search_memories", return_value=memories):
|
|
147
|
+
results = list(checkpointer.list(_make_config("t"), before=before_config))
|
|
148
|
+
|
|
149
|
+
# Should yield only items after (older than) the before checkpoint
|
|
150
|
+
assert len(results) == 1
|
|
151
|
+
assert results[0].checkpoint["id"] == checkpoints[2]["id"]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@pytest.mark.asyncio
|
|
155
|
+
class TestAsync:
|
|
156
|
+
async def test_aget_tuple_delegates(self, checkpointer):
|
|
157
|
+
cp = _make_checkpoint()
|
|
158
|
+
meta = _make_metadata()
|
|
159
|
+
content = checkpointer._pack(cp, meta, "async-thread", None)
|
|
160
|
+
mem = {"id": "am-1", "content": content}
|
|
161
|
+
|
|
162
|
+
with patch.object(checkpointer, "_search_memories", return_value=[mem]):
|
|
163
|
+
result = await checkpointer.aget_tuple(_make_config("async-thread"))
|
|
164
|
+
|
|
165
|
+
assert result is not None
|
|
166
|
+
assert result.checkpoint["id"] == cp["id"]
|
|
167
|
+
|
|
168
|
+
async def test_aput_delegates(self, checkpointer):
|
|
169
|
+
cp = _make_checkpoint()
|
|
170
|
+
meta = _make_metadata()
|
|
171
|
+
|
|
172
|
+
with patch.object(checkpointer, "_store_memory", return_value="id"):
|
|
173
|
+
result = await checkpointer.aput(_make_config("async-thread"), cp, meta, {})
|
|
174
|
+
|
|
175
|
+
assert result["configurable"]["checkpoint_id"] == cp["id"]
|