cathedral-langgraph 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,4 @@
1
+ from .checkpointer import CathedralCheckpointer
2
+
3
+ __all__ = ["CathedralCheckpointer"]
4
+ __version__ = "0.1.0"
@@ -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,6 @@
1
+ cathedral_langgraph/__init__.py,sha256=UJQChTxM-HmBrHMrWYyB4iJGVtBGY2c9zpMLIU8Ee-8,107
2
+ cathedral_langgraph/checkpointer.py,sha256=mlE5ex1S4ZUhqm1PYCrb2hPQn0gChlpE30WlAJQrf-M,12802
3
+ cathedral_langgraph-0.1.0.dist-info/METADATA,sha256=jKKcdlnQ0ThKshqg3nW6Jdl5KNEAQC6fHYER0CZGQVQ,2753
4
+ cathedral_langgraph-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ cathedral_langgraph-0.1.0.dist-info/top_level.txt,sha256=mdF5h2R2Se1vit8X_A_MTf9MHRLOoXBtqIYdNKXY8dQ,20
6
+ cathedral_langgraph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ cathedral_langgraph