langgraph_checkpoint_firestore 0.2.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.
- langgraph_checkpoint_firestore/LICENSE +19 -0
- langgraph_checkpoint_firestore/__init__.py +7 -0
- langgraph_checkpoint_firestore/firestoreSaver.py +362 -0
- langgraph_checkpoint_firestore/firestoreSerializer.py +15 -0
- langgraph_checkpoint_firestore-0.2.0.dist-info/METADATA +191 -0
- langgraph_checkpoint_firestore-0.2.0.dist-info/RECORD +7 -0
- langgraph_checkpoint_firestore-0.2.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2018 The Python Packaging Authority
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
# create firestore Saver (langgraph checkpointer) basis firestoredb implementation in included code include=src/langgraph_checkpoint_firestore/firestoredbSaver.py
|
|
2
|
+
# Remember there is no partition key in firestore only unique ID.
|
|
3
|
+
# create separate collection for checkpoints and writes. Next level collection will be thread_id and then checkpoint_id
|
|
4
|
+
# we have to preserve the function signatures and return values (as in firestoredbsaver) as it is.
|
|
5
|
+
# Do provide full and complete code, i.e all function along with Saver in the included file.
|
|
6
|
+
# @!
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from typing import Any, Iterator, List, Optional, Tuple, AsyncIterator
|
|
11
|
+
|
|
12
|
+
from langchain_core.runnables import RunnableConfig
|
|
13
|
+
|
|
14
|
+
from langgraph.checkpoint.base import WRITES_IDX_MAP, BaseCheckpointSaver, ChannelVersions, Checkpoint, CheckpointMetadata, CheckpointTuple, PendingWrite, get_checkpoint_id
|
|
15
|
+
|
|
16
|
+
from google.cloud import firestore
|
|
17
|
+
from langgraph_checkpoint_firestore.firestoreSerializer import FirestoreSerializer
|
|
18
|
+
import asyncio
|
|
19
|
+
|
|
20
|
+
FIRESTORE_KEY_SEPARATOR = "/"
|
|
21
|
+
|
|
22
|
+
def _make_firestore_checkpoint_key(thread_id: str, checkpoint_ns: str, checkpoint_id: str) -> str:
|
|
23
|
+
return FIRESTORE_KEY_SEPARATOR.join([
|
|
24
|
+
"checkpoint", thread_id, checkpoint_ns, checkpoint_id
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _make_firestore_checkpoint_writes_key(thread_id: str, checkpoint_ns: str, checkpoint_id: str, task_id: str, idx: Optional[int]) -> str:
|
|
29
|
+
if idx is None:
|
|
30
|
+
return FIRESTORE_KEY_SEPARATOR.join([
|
|
31
|
+
"writes", thread_id, checkpoint_ns, checkpoint_id, task_id
|
|
32
|
+
])
|
|
33
|
+
|
|
34
|
+
return FIRESTORE_KEY_SEPARATOR.join([
|
|
35
|
+
"writes", thread_id, checkpoint_ns, checkpoint_id, task_id, str(idx)
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _parse_firestore_checkpoint_key(firestoredb_key: str) -> dict:
|
|
40
|
+
namespace, thread_id, checkpoint_ns, checkpoint_id = firestoredb_key.split(
|
|
41
|
+
FIRESTORE_KEY_SEPARATOR
|
|
42
|
+
)
|
|
43
|
+
if namespace != "checkpoint":
|
|
44
|
+
raise ValueError("Expected checkpoint key to start with 'checkpoint'")
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
"thread_id": thread_id,
|
|
48
|
+
"checkpoint_ns": checkpoint_ns,
|
|
49
|
+
"checkpoint_id": checkpoint_id,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse_firestore_checkpoint_writes_key(firestoredb_key: str) -> dict:
|
|
54
|
+
namespace, thread_id, checkpoint_ns, checkpoint_id, task_id, idx = firestoredb_key.split(
|
|
55
|
+
FIRESTORE_KEY_SEPARATOR
|
|
56
|
+
)
|
|
57
|
+
if namespace != "writes":
|
|
58
|
+
raise ValueError("Expected checkpoint key to start with 'writes'")
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
"thread_id": thread_id,
|
|
62
|
+
"checkpoint_ns": checkpoint_ns,
|
|
63
|
+
"checkpoint_id": checkpoint_id,
|
|
64
|
+
"task_id": task_id,
|
|
65
|
+
"idx": idx,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _filter_keys(keys: List[str], before: Optional[RunnableConfig], limit: Optional[int]) -> list:
|
|
70
|
+
if before:
|
|
71
|
+
keys = [
|
|
72
|
+
k
|
|
73
|
+
for k in keys
|
|
74
|
+
if _parse_firestore_checkpoint_key(k)["checkpoint_id"]
|
|
75
|
+
< before["configurable"]["checkpoint_id"]
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
keys = sorted(
|
|
79
|
+
keys,
|
|
80
|
+
key=lambda k: _parse_firestore_checkpoint_key(k)["checkpoint_id"],
|
|
81
|
+
reverse=True,
|
|
82
|
+
)
|
|
83
|
+
if limit:
|
|
84
|
+
keys = keys[:limit]
|
|
85
|
+
return keys
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _load_writes(serde: FirestoreSerializer, task_id_to_data: dict[tuple[str, str], dict]) -> list[PendingWrite]:
|
|
89
|
+
writes = [
|
|
90
|
+
(
|
|
91
|
+
task_id,
|
|
92
|
+
data["channel"],
|
|
93
|
+
serde.loads_typed((data["type"], data["value"])),
|
|
94
|
+
)
|
|
95
|
+
for (task_id, _), data in task_id_to_data.items()
|
|
96
|
+
]
|
|
97
|
+
return writes
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _parse_firestore_checkpoint_data(serde: FirestoreSerializer, key: str, data: dict, pending_writes: Optional[List[PendingWrite]] = None) -> Optional[CheckpointTuple]:
|
|
101
|
+
if not data:
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
parsed_key = _parse_firestore_checkpoint_key(key)
|
|
105
|
+
thread_id = parsed_key["thread_id"]
|
|
106
|
+
checkpoint_ns = parsed_key["checkpoint_ns"]
|
|
107
|
+
checkpoint_id = parsed_key["checkpoint_id"]
|
|
108
|
+
config = {
|
|
109
|
+
"configurable": {
|
|
110
|
+
"thread_id": thread_id,
|
|
111
|
+
"checkpoint_ns": checkpoint_ns,
|
|
112
|
+
"checkpoint_id": checkpoint_id,
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
checkpoint = serde.loads_typed((data["type"], data["checkpoint"]))
|
|
117
|
+
|
|
118
|
+
metadata = serde.loads_typed(data["metadata"])
|
|
119
|
+
parent_checkpoint_id = data.get("parent_checkpoint_id", "")
|
|
120
|
+
parent_config = (
|
|
121
|
+
{
|
|
122
|
+
"configurable": {
|
|
123
|
+
"thread_id": thread_id,
|
|
124
|
+
"checkpoint_ns": checkpoint_ns,
|
|
125
|
+
"checkpoint_id": parent_checkpoint_id,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if parent_checkpoint_id
|
|
129
|
+
else None
|
|
130
|
+
)
|
|
131
|
+
return CheckpointTuple(
|
|
132
|
+
config=config,
|
|
133
|
+
checkpoint=checkpoint,
|
|
134
|
+
metadata=metadata,
|
|
135
|
+
parent_config=parent_config,
|
|
136
|
+
pending_writes=pending_writes,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
class FirestoreSaver(BaseCheckpointSaver):
|
|
140
|
+
def __init__(self, project_id, checkpoints_collection='checkpoints', reducer=None, messages_key="messages"):
|
|
141
|
+
super().__init__()
|
|
142
|
+
self.client = firestore.Client(project=project_id)
|
|
143
|
+
self.firestore_serde = FirestoreSerializer(self.serde)
|
|
144
|
+
self.checkpoints_collection = self.client.collection(checkpoints_collection)
|
|
145
|
+
self.reducer = reducer
|
|
146
|
+
self.messages_key = messages_key
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
@contextmanager
|
|
150
|
+
def from_conn_info(cls, *, project_id: str, checkpoints_collection: str, reducer=None, messages_key="messages", **kwargs) -> Iterator['FirestoreSaver']:
|
|
151
|
+
saver = None
|
|
152
|
+
try:
|
|
153
|
+
saver = FirestoreSaver(project_id, checkpoints_collection, reducer=reducer, messages_key=messages_key)
|
|
154
|
+
yield saver
|
|
155
|
+
finally:
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
def _apply_reducer(self, checkpoint: Checkpoint) -> Checkpoint:
|
|
159
|
+
if self.reducer is None:
|
|
160
|
+
return checkpoint
|
|
161
|
+
channel_values = checkpoint.get("channel_values", {})
|
|
162
|
+
messages = channel_values.get(self.messages_key)
|
|
163
|
+
if not messages:
|
|
164
|
+
return checkpoint
|
|
165
|
+
result = self.reducer.reduce(existing=messages, new=[])
|
|
166
|
+
new_channel_values = dict(channel_values)
|
|
167
|
+
new_channel_values[self.messages_key] = result.surviving
|
|
168
|
+
new_checkpoint = copy.copy(checkpoint)
|
|
169
|
+
new_checkpoint["channel_values"] = new_channel_values
|
|
170
|
+
return new_checkpoint
|
|
171
|
+
|
|
172
|
+
# Helper to get subcollection for a given partition
|
|
173
|
+
def _get_partition_collection(self, thread_id: str, checkpoint_ns: str):
|
|
174
|
+
"""Return the Firestore collection reference representing one partition (thread+ns)."""
|
|
175
|
+
partition_doc = self.checkpoints_collection.document(f"{thread_id}_{checkpoint_ns}")
|
|
176
|
+
return partition_doc.collection("checkpoints")
|
|
177
|
+
|
|
178
|
+
def put(self, config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, new_versions: ChannelVersions) -> RunnableConfig:
|
|
179
|
+
checkpoint = self._apply_reducer(checkpoint)
|
|
180
|
+
thread_id = config['configurable']['thread_id']
|
|
181
|
+
checkpoint_ns = config['configurable']['checkpoint_ns']
|
|
182
|
+
checkpoint_id = checkpoint['id']
|
|
183
|
+
parent_checkpoint_id = config['configurable'].get('checkpoint_id')
|
|
184
|
+
key = _make_firestore_checkpoint_key(thread_id, checkpoint_ns, checkpoint_id)
|
|
185
|
+
|
|
186
|
+
type_, serialized_checkpoint = self.firestore_serde.dumps_typed(checkpoint)
|
|
187
|
+
serialized_metadata = self.firestore_serde.dumps_typed(metadata)
|
|
188
|
+
data = {
|
|
189
|
+
'checkpoint': serialized_checkpoint,
|
|
190
|
+
'checkpoint_id': checkpoint_id,
|
|
191
|
+
"checkpoint_key": key,
|
|
192
|
+
'type': type_,
|
|
193
|
+
'metadata': serialized_metadata,
|
|
194
|
+
'parent_checkpoint_id': parent_checkpoint_id if parent_checkpoint_id else ''
|
|
195
|
+
}
|
|
196
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
197
|
+
partition_collection.document(checkpoint_id).set(data)
|
|
198
|
+
return {
|
|
199
|
+
'configurable': {
|
|
200
|
+
'thread_id': thread_id,
|
|
201
|
+
'checkpoint_ns': checkpoint_ns,
|
|
202
|
+
'checkpoint_id': checkpoint_id
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
def put_writes(self, config: RunnableConfig, writes: List[Tuple[str, Any]], task_id: str) -> None:
|
|
207
|
+
thread_id = config['configurable']['thread_id']
|
|
208
|
+
checkpoint_ns = config['configurable']['checkpoint_ns']
|
|
209
|
+
checkpoint_id = config['configurable']['checkpoint_id']
|
|
210
|
+
|
|
211
|
+
# Writes belong under the checkpoint itself
|
|
212
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
213
|
+
# self.write_collection is not used anymore.
|
|
214
|
+
writes_collection = partition_collection.document(checkpoint_id).collection("writes")
|
|
215
|
+
|
|
216
|
+
for idx, (channel, value) in enumerate(writes):
|
|
217
|
+
key = _make_firestore_checkpoint_writes_key(
|
|
218
|
+
thread_id,
|
|
219
|
+
checkpoint_ns,
|
|
220
|
+
checkpoint_id,
|
|
221
|
+
task_id,
|
|
222
|
+
WRITES_IDX_MAP.get(channel, idx),
|
|
223
|
+
)
|
|
224
|
+
type_, serialized_value = self.firestore_serde.dumps_typed(value)
|
|
225
|
+
data = {"checkpoint_key": key, 'channel': channel, 'type': type_,
|
|
226
|
+
'value': serialized_value,
|
|
227
|
+
"task_id": task_id,
|
|
228
|
+
"idx": WRITES_IDX_MAP.get(channel, idx)}
|
|
229
|
+
writes_collection.document(f"{task_id}_{idx}").set(data)
|
|
230
|
+
|
|
231
|
+
def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
232
|
+
thread_id = config['configurable']['thread_id']
|
|
233
|
+
checkpoint_id = get_checkpoint_id(config)
|
|
234
|
+
|
|
235
|
+
checkpoint_ns = config['configurable'].get('checkpoint_ns', '')
|
|
236
|
+
|
|
237
|
+
checkpoint_key = self._get_checkpoint_key(
|
|
238
|
+
thread_id, checkpoint_ns, checkpoint_id
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
if not checkpoint_key:
|
|
242
|
+
return None
|
|
243
|
+
checkpoint_id = _parse_firestore_checkpoint_key(checkpoint_key)["checkpoint_id"]
|
|
244
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
245
|
+
|
|
246
|
+
doc_ref = partition_collection.document(checkpoint_id)
|
|
247
|
+
doc = doc_ref.get()
|
|
248
|
+
if not doc.exists:
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
checkpoint_data = doc.to_dict()
|
|
252
|
+
|
|
253
|
+
pending_writes = self._load_pending_writes(
|
|
254
|
+
thread_id, checkpoint_ns, checkpoint_id
|
|
255
|
+
)
|
|
256
|
+
return _parse_firestore_checkpoint_data(
|
|
257
|
+
self.firestore_serde, checkpoint_key, checkpoint_data, pending_writes=pending_writes
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
def list(self, config: Optional[RunnableConfig], *, filter: Optional[dict[str, Any]] = None, before: Optional[RunnableConfig] = None, limit: Optional[int] = None) -> Iterator[CheckpointTuple]:
|
|
261
|
+
thread_id = config['configurable']['thread_id']
|
|
262
|
+
checkpoint_ns = config['configurable'].get('checkpoint_ns', '')
|
|
263
|
+
|
|
264
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
265
|
+
|
|
266
|
+
# Order by checkpoint_id descending (latest first)
|
|
267
|
+
query = partition_collection.order_by("checkpoint_id", direction=firestore.Query.DESCENDING)
|
|
268
|
+
|
|
269
|
+
if limit:
|
|
270
|
+
query = query.limit(limit)
|
|
271
|
+
|
|
272
|
+
checkpoints = query.stream()
|
|
273
|
+
|
|
274
|
+
for checkpoint in checkpoints:
|
|
275
|
+
if not checkpoint.exists:
|
|
276
|
+
continue
|
|
277
|
+
checkpoint_data = checkpoint.to_dict()
|
|
278
|
+
checkpoint_id = checkpoint_data["checkpoint_id"]
|
|
279
|
+
pending_writes = self._load_pending_writes(thread_id, checkpoint_ns, checkpoint_id)
|
|
280
|
+
yield _parse_firestore_checkpoint_data(self.firestore_serde, checkpoint_data["checkpoint_key"],checkpoint_data, pending_writes)
|
|
281
|
+
|
|
282
|
+
def _load_pending_writes(self, thread_id: str, checkpoint_ns: Optional[str] , checkpoint_id: str) -> List[PendingWrite]:
|
|
283
|
+
|
|
284
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
285
|
+
writes_ref = partition_collection.document(checkpoint_id).collection("writes")
|
|
286
|
+
|
|
287
|
+
# Stream all write documents under this checkpoint
|
|
288
|
+
write_docs = [doc.to_dict() for doc in writes_ref.stream() if doc.exists]
|
|
289
|
+
|
|
290
|
+
if not write_docs:
|
|
291
|
+
return []
|
|
292
|
+
|
|
293
|
+
# Parse checkpoint keys and sort by idx
|
|
294
|
+
parsed_keys = [
|
|
295
|
+
_parse_firestore_checkpoint_writes_key(w["checkpoint_key"]) for w in write_docs
|
|
296
|
+
]
|
|
297
|
+
|
|
298
|
+
# Sort by idx (to maintain deterministic replay order)
|
|
299
|
+
combined = sorted(zip(write_docs, parsed_keys), key=lambda x: x[1]["idx"])
|
|
300
|
+
|
|
301
|
+
pending_writes = _load_writes(
|
|
302
|
+
self.firestore_serde,
|
|
303
|
+
{
|
|
304
|
+
(parsed_key["task_id"], parsed_key["idx"]): key
|
|
305
|
+
for key, parsed_key in combined
|
|
306
|
+
},
|
|
307
|
+
)
|
|
308
|
+
return pending_writes
|
|
309
|
+
|
|
310
|
+
def _get_checkpoint_key(self, thread_id: str, checkpoint_ns: str, checkpoint_id: Optional[str]) -> Optional[str]:
|
|
311
|
+
if checkpoint_id:
|
|
312
|
+
return _make_firestore_checkpoint_key(thread_id, checkpoint_ns, checkpoint_id)
|
|
313
|
+
|
|
314
|
+
partition_collection = self._get_partition_collection(thread_id, checkpoint_ns)
|
|
315
|
+
docs = (
|
|
316
|
+
partition_collection
|
|
317
|
+
.order_by("checkpoint_id", direction=firestore.Query.DESCENDING)
|
|
318
|
+
.limit(1)
|
|
319
|
+
.stream()
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
if not docs:
|
|
323
|
+
return None
|
|
324
|
+
|
|
325
|
+
latest_doc = next(docs, None)
|
|
326
|
+
if not latest_doc or not latest_doc.exists:
|
|
327
|
+
return None
|
|
328
|
+
|
|
329
|
+
data = latest_doc.to_dict()
|
|
330
|
+
return data["checkpoint_key"]
|
|
331
|
+
|
|
332
|
+
async def aget(self, config: RunnableConfig) -> Optional[Checkpoint]:
|
|
333
|
+
if value := await self.aget_tuple(config):
|
|
334
|
+
return value.checkpoint
|
|
335
|
+
|
|
336
|
+
async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
337
|
+
return await asyncio.get_running_loop().run_in_executor(
|
|
338
|
+
None, self.get_tuple, config
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
async def alist(self, config: RunnableConfig) -> AsyncIterator[CheckpointTuple]:
|
|
342
|
+
loop = asyncio.get_running_loop()
|
|
343
|
+
iter = loop.run_in_executor(None, self.list, config)
|
|
344
|
+
while True:
|
|
345
|
+
try:
|
|
346
|
+
yield await loop.run_in_executor(None, next, iter)
|
|
347
|
+
except StopIteration:
|
|
348
|
+
return
|
|
349
|
+
|
|
350
|
+
async def aput(
|
|
351
|
+
self, config: RunnableConfig, checkpoint: Checkpoint, metadata: Optional[CheckpointMetadata] = None, new_versions: Optional[ChannelVersions] = None
|
|
352
|
+
) -> RunnableConfig:
|
|
353
|
+
return await asyncio.get_running_loop().run_in_executor(
|
|
354
|
+
None, self.put, config, checkpoint, metadata, new_versions
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
async def aput_writes(
|
|
358
|
+
self, config: RunnableConfig, writes: List[Tuple[str, Any]], task_id: str
|
|
359
|
+
) -> None:
|
|
360
|
+
return await asyncio.get_running_loop().run_in_executor(
|
|
361
|
+
None, self.put_writes, config, writes, task_id
|
|
362
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
|
|
3
|
+
class FirestoreSerializer:
|
|
4
|
+
def __init__(self, serde):
|
|
5
|
+
self.serde = serde
|
|
6
|
+
|
|
7
|
+
def dumps_typed(self, obj):
|
|
8
|
+
type_, data = self.serde.dumps_typed(obj)
|
|
9
|
+
data_base64 = base64.b64encode(data).decode('utf-8')
|
|
10
|
+
return type_, data_base64
|
|
11
|
+
|
|
12
|
+
def loads_typed(self, data):
|
|
13
|
+
type_name, serialized_obj = data
|
|
14
|
+
serialized_obj = base64.b64decode(serialized_obj.encode('utf-8'))
|
|
15
|
+
return self.serde.loads_typed((type_name, serialized_obj))
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langgraph_checkpoint_firestore
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: LangGraph checkpoint saver for Google Firestore with built-in message history pruning via agentstate-reducer
|
|
5
|
+
Author-email: Kamal <skamalj@github.com>
|
|
6
|
+
Keywords: agent-state,checkpoint,firestore,google-cloud,langchain,langgraph,memory,message-reducer
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: google-cloud-firestore
|
|
13
|
+
Requires-Dist: langchain-core
|
|
14
|
+
Requires-Dist: langgraph
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: black; extra == 'dev'
|
|
17
|
+
Requires-Dist: isort; extra == 'dev'
|
|
18
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
19
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
21
|
+
Provides-Extra: reducer
|
|
22
|
+
Requires-Dist: agentstate-reducer>=0.1.1; extra == 'reducer'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# langgraph-checkpoint-firestore
|
|
26
|
+
|
|
27
|
+
Google Firestore checkpoint saver for [LangGraph](https://github.com/langchain-ai/langgraph). Persists agent state between runs so your graphs can resume from any prior checkpoint.
|
|
28
|
+
|
|
29
|
+
**What makes this checkpointer different:** it has message history pruning built in. Pass a `MessageReducer` and the checkpointer automatically caps your message list before writing to Firestore — no extra code in your graph, no state annotation changes required. This is the only LangGraph Firestore checkpointer with this capability.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- **Full checkpoint persistence** — save, retrieve, and list LangGraph checkpoints in Google Firestore
|
|
34
|
+
- **Built-in message pruning** — optional `MessageReducer` prunes message history at the persistence layer, keeping checkpoints lean without changing your graph code
|
|
35
|
+
- **Sync and async API** — `put`/`get_tuple`/`list` and their `aput`/`aget_tuple`/`alist` async counterparts
|
|
36
|
+
- **Subgraph support** — correctly checkpoints parent and subgraph state independently
|
|
37
|
+
- **Native Firestore hierarchy** — checkpoints stored in subcollections per thread, enabling efficient per-thread queries
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install langgraph-checkpoint-firestore
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
With optional message pruning support:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install "langgraph-checkpoint-firestore[reducer]"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
**Requires Python 3.10+**
|
|
52
|
+
|
|
53
|
+
## Firestore Setup
|
|
54
|
+
|
|
55
|
+
The saver uses Google Cloud Application Default Credentials. Set up auth with one of:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Local development — authenticate with your Google account
|
|
59
|
+
gcloud auth application-default login
|
|
60
|
+
|
|
61
|
+
# Service account (CI / production)
|
|
62
|
+
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Your Firestore instance must be in **Native mode** (not Datastore mode). Collections are created automatically on first write — no manual setup required.
|
|
66
|
+
|
|
67
|
+
## Quick Start
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from langgraph.graph import StateGraph, MessagesState, START
|
|
71
|
+
from langchain_openai import ChatOpenAI
|
|
72
|
+
from langgraph_checkpoint_firestore import FirestoreSaver
|
|
73
|
+
|
|
74
|
+
model = ChatOpenAI(model="gpt-4o-mini")
|
|
75
|
+
|
|
76
|
+
def call_model(state: MessagesState):
|
|
77
|
+
return {"messages": model.invoke(state["messages"])}
|
|
78
|
+
|
|
79
|
+
builder = StateGraph(MessagesState)
|
|
80
|
+
builder.add_node("call_model", call_model)
|
|
81
|
+
builder.add_edge(START, "call_model")
|
|
82
|
+
|
|
83
|
+
with FirestoreSaver.from_conn_info(project_id="my-gcp-project", checkpoints_collection="checkpoints") as checkpointer:
|
|
84
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
85
|
+
|
|
86
|
+
config = {"configurable": {"thread_id": "user-123"}}
|
|
87
|
+
|
|
88
|
+
# First run — state is saved to Firestore
|
|
89
|
+
graph.invoke({"messages": [{"role": "user", "content": "Hi, I'm Kamal"}]}, config)
|
|
90
|
+
|
|
91
|
+
# Second run — picks up where it left off
|
|
92
|
+
graph.invoke({"messages": [{"role": "user", "content": "What's my name?"}]}, config)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## API Reference
|
|
96
|
+
|
|
97
|
+
### `FirestoreSaver(project_id, checkpoints_collection, reducer=None, messages_key="messages")`
|
|
98
|
+
|
|
99
|
+
| Parameter | Type | Default | Description |
|
|
100
|
+
|---|---|---|---|
|
|
101
|
+
| `project_id` | `str` | required | Google Cloud project ID |
|
|
102
|
+
| `checkpoints_collection` | `str` | `"checkpoints"` | Root Firestore collection name |
|
|
103
|
+
| `reducer` | `MessageReducer` | `None` | Optional pruner — see [Message Pruning](#built-in-message-pruning) |
|
|
104
|
+
| `messages_key` | `str` | `"messages"` | State channel name that holds the message list |
|
|
105
|
+
|
|
106
|
+
You can also use the context manager factory:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
with FirestoreSaver.from_conn_info(
|
|
110
|
+
project_id="my-gcp-project",
|
|
111
|
+
checkpoints_collection="checkpoints",
|
|
112
|
+
reducer=reducer,
|
|
113
|
+
messages_key="messages"
|
|
114
|
+
) as saver:
|
|
115
|
+
graph = builder.compile(checkpointer=saver)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Sync methods
|
|
119
|
+
|
|
120
|
+
| Method | Description |
|
|
121
|
+
|---|---|
|
|
122
|
+
| `put(config, checkpoint, metadata, new_versions)` | Save a checkpoint |
|
|
123
|
+
| `put_writes(config, writes, task_id)` | Save pending writes for a checkpoint |
|
|
124
|
+
| `get_tuple(config)` | Retrieve the latest (or a specific) checkpoint |
|
|
125
|
+
| `list(config, *, before, limit)` | Iterate checkpoints for a thread |
|
|
126
|
+
|
|
127
|
+
### Async methods
|
|
128
|
+
|
|
129
|
+
All sync methods have async counterparts: `aput`, `aput_writes`, `aget_tuple`, `alist`.
|
|
130
|
+
|
|
131
|
+
## Built-in Message Pruning
|
|
132
|
+
|
|
133
|
+
Long-running agents accumulate message history with every turn. Left unchecked this inflates checkpoint size, increases Firestore storage costs, and eventually blows past LLM context limits.
|
|
134
|
+
|
|
135
|
+
This checkpointer solves that at the persistence layer: pass a `MessageReducer` and it automatically prunes the message list inside `put()` before the checkpoint is serialised and written to Firestore. **Your graph code, state definition, and node logic stay untouched.**
|
|
136
|
+
|
|
137
|
+
This is an alternative to — or complement of — the LangGraph `Annotated[list, reducer_fn]` pattern. Use the checkpoint-layer approach when:
|
|
138
|
+
|
|
139
|
+
- You don't own the graph or state definition (e.g. using a pre-built LangGraph agent)
|
|
140
|
+
- You want pruning to happen unconditionally at every save, regardless of which node triggered it
|
|
141
|
+
- You want to keep all in-memory state intact and only prune what gets persisted
|
|
142
|
+
|
|
143
|
+
### Install with reducer support
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
pip install "langgraph-checkpoint-firestore[reducer]"
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Usage
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from agentstate_reducer import MessageReducer
|
|
153
|
+
from langgraph_checkpoint_firestore import FirestoreSaver
|
|
154
|
+
|
|
155
|
+
reducer = MessageReducer(min_messages=10, max_messages=20)
|
|
156
|
+
|
|
157
|
+
with FirestoreSaver.from_conn_info(
|
|
158
|
+
project_id="my-gcp-project",
|
|
159
|
+
checkpoints_collection="checkpoints",
|
|
160
|
+
reducer=reducer, # prune before each checkpoint save
|
|
161
|
+
messages_key="messages" # state channel holding the message list (default)
|
|
162
|
+
) as checkpointer:
|
|
163
|
+
graph = builder.compile(checkpointer=checkpointer)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
When `len(messages) > max_messages`, the oldest `human`/`ai` messages are removed until `min_messages` remain. The following are **never** pruned:
|
|
167
|
+
|
|
168
|
+
- Index 0 (typically the system prompt) — controlled by `preserve_first=True`
|
|
169
|
+
- `system` and `function` messages
|
|
170
|
+
- `tool` messages — unless their parent `ai` message is pruned (cascade behaviour, configurable)
|
|
171
|
+
|
|
172
|
+
See [agentstate-reducer on PyPI](https://pypi.org/project/agentstate-reducer/) for full configuration: `preserve_first`, `cascade_tool_messages`, `summarize_fn`, and role alias support (`user`/`assistant`/`agent`).
|
|
173
|
+
|
|
174
|
+
## Data Model
|
|
175
|
+
|
|
176
|
+
Checkpoints are stored in a hierarchical Firestore structure:
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
{checkpoints_collection}/
|
|
180
|
+
{thread_id}_{checkpoint_ns}/ ← partition document
|
|
181
|
+
checkpoints/
|
|
182
|
+
{checkpoint_id} ← checkpoint document
|
|
183
|
+
writes/
|
|
184
|
+
{task_id}_{idx} ← pending write documents
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
This structure enables efficient per-thread checkpoint queries and keeps checkpoint data co-located with its pending writes.
|
|
188
|
+
|
|
189
|
+
## License
|
|
190
|
+
|
|
191
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
langgraph_checkpoint_firestore/LICENSE,sha256=6kbiFSfobTZ7beWiKnHpN902HgBx-Jzgcme0SvKqhKY,1091
|
|
2
|
+
langgraph_checkpoint_firestore/__init__.py,sha256=pAPZVXuwPnlab62o-Q2nQMc62eeqRxSSaw3Zjm2GGYI,189
|
|
3
|
+
langgraph_checkpoint_firestore/firestoreSaver.py,sha256=dZklpzOw6JDdwek1cGO7kSGeilYUCud0Mh5E_pOgb-A,14932
|
|
4
|
+
langgraph_checkpoint_firestore/firestoreSerializer.py,sha256=xL2a7MVu47n0vxir4arpSkbP4mpSUWLiiFCEmQLPXJY,513
|
|
5
|
+
langgraph_checkpoint_firestore-0.2.0.dist-info/METADATA,sha256=QVZ854MZauxBExnHxRxaMLVVgjymgAjrUuG3g4g1vAo,7685
|
|
6
|
+
langgraph_checkpoint_firestore-0.2.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
7
|
+
langgraph_checkpoint_firestore-0.2.0.dist-info/RECORD,,
|