langgraph-checkpoint-sqlite 1.0.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.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.1
2
+ Name: langgraph-checkpoint-sqlite
3
+ Version: 1.0.0
4
+ Summary: Library with a SQLite implementation of LangGraph checkpoint saver.
5
+ Home-page: https://www.github.com/langchain-ai/langgraph
6
+ License: MIT
7
+ Requires-Python: >=3.9.0,<4.0.0
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: aiosqlite (>=0.20.0,<0.21.0)
15
+ Requires-Dist: langgraph-checkpoint (>=1.0.1,<2.0.0)
16
+ Project-URL: Repository, https://www.github.com/langchain-ai/langgraph
17
+ Description-Content-Type: text/markdown
18
+
19
+ # LangGraph SQLite Checkpoint
20
+
21
+ Implementation of LangGraph CheckpointSaver that uses SQLite DB (both sync and async, via `aiosqlite`)
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ from langgraph.checkpoint.sqlite import SqliteSaver
27
+
28
+ write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
29
+ read_config = {"configurable": {"thread_id": "1"}}
30
+
31
+ with SqliteSaver.from_conn_string(":memory:") as checkpointer:
32
+ checkpoint = {
33
+ "v": 1,
34
+ "ts": "2024-07-31T20:14:19.804150+00:00",
35
+ "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
36
+ "channel_values": {
37
+ "my_key": "meow",
38
+ "node": "node"
39
+ },
40
+ "channel_versions": {
41
+ "__start__": 2,
42
+ "my_key": 3,
43
+ "start:node": 3,
44
+ "node": 3
45
+ },
46
+ "versions_seen": {
47
+ "__input__": {},
48
+ "__start__": {
49
+ "__start__": 1
50
+ },
51
+ "node": {
52
+ "start:node": 2
53
+ }
54
+ },
55
+ "pending_sends": [],
56
+ "current_tasks": {}
57
+ }
58
+
59
+ # store checkpoint
60
+ checkpointer.put(write_config, checkpoint, {}, {})
61
+
62
+ # load checkpoint
63
+ checkpointer.get(read_config)
64
+
65
+ # list checkpoints
66
+ list(checkpointer.list(read_config))
67
+ ```
68
+
69
+ ### Async
70
+
71
+ ```python
72
+ from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
73
+
74
+ async with AsyncSqliteSaver.from_conn_string(":memory:") as checkpointer:
75
+ checkpoint = {
76
+ "v": 1,
77
+ "ts": "2024-07-31T20:14:19.804150+00:00",
78
+ "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
79
+ "channel_values": {
80
+ "my_key": "meow",
81
+ "node": "node"
82
+ },
83
+ "channel_versions": {
84
+ "__start__": 2,
85
+ "my_key": 3,
86
+ "start:node": 3,
87
+ "node": 3
88
+ },
89
+ "versions_seen": {
90
+ "__input__": {},
91
+ "__start__": {
92
+ "__start__": 1
93
+ },
94
+ "node": {
95
+ "start:node": 2
96
+ }
97
+ },
98
+ "pending_sends": [],
99
+ "current_tasks": {}
100
+ }
101
+
102
+ # store checkpoint
103
+ await checkpointer.aput(write_config, checkpoint, {}, {})
104
+
105
+ # load checkpoint
106
+ await checkpointer.aget(read_config)
107
+
108
+ # list checkpoints
109
+ [c async for c in checkpointer.alist(read_config)]
110
+ ```
@@ -0,0 +1,92 @@
1
+ # LangGraph SQLite Checkpoint
2
+
3
+ Implementation of LangGraph CheckpointSaver that uses SQLite DB (both sync and async, via `aiosqlite`)
4
+
5
+ ## Usage
6
+
7
+ ```python
8
+ from langgraph.checkpoint.sqlite import SqliteSaver
9
+
10
+ write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
11
+ read_config = {"configurable": {"thread_id": "1"}}
12
+
13
+ with SqliteSaver.from_conn_string(":memory:") as checkpointer:
14
+ checkpoint = {
15
+ "v": 1,
16
+ "ts": "2024-07-31T20:14:19.804150+00:00",
17
+ "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
18
+ "channel_values": {
19
+ "my_key": "meow",
20
+ "node": "node"
21
+ },
22
+ "channel_versions": {
23
+ "__start__": 2,
24
+ "my_key": 3,
25
+ "start:node": 3,
26
+ "node": 3
27
+ },
28
+ "versions_seen": {
29
+ "__input__": {},
30
+ "__start__": {
31
+ "__start__": 1
32
+ },
33
+ "node": {
34
+ "start:node": 2
35
+ }
36
+ },
37
+ "pending_sends": [],
38
+ "current_tasks": {}
39
+ }
40
+
41
+ # store checkpoint
42
+ checkpointer.put(write_config, checkpoint, {}, {})
43
+
44
+ # load checkpoint
45
+ checkpointer.get(read_config)
46
+
47
+ # list checkpoints
48
+ list(checkpointer.list(read_config))
49
+ ```
50
+
51
+ ### Async
52
+
53
+ ```python
54
+ from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
55
+
56
+ async with AsyncSqliteSaver.from_conn_string(":memory:") as checkpointer:
57
+ checkpoint = {
58
+ "v": 1,
59
+ "ts": "2024-07-31T20:14:19.804150+00:00",
60
+ "id": "1ef4f797-8335-6428-8001-8a1503f9b875",
61
+ "channel_values": {
62
+ "my_key": "meow",
63
+ "node": "node"
64
+ },
65
+ "channel_versions": {
66
+ "__start__": 2,
67
+ "my_key": 3,
68
+ "start:node": 3,
69
+ "node": 3
70
+ },
71
+ "versions_seen": {
72
+ "__input__": {},
73
+ "__start__": {
74
+ "__start__": 1
75
+ },
76
+ "node": {
77
+ "start:node": 2
78
+ }
79
+ },
80
+ "pending_sends": [],
81
+ "current_tasks": {}
82
+ }
83
+
84
+ # store checkpoint
85
+ await checkpointer.aput(write_config, checkpoint, {}, {})
86
+
87
+ # load checkpoint
88
+ await checkpointer.aget(read_config)
89
+
90
+ # list checkpoints
91
+ [c async for c in checkpointer.alist(read_config)]
92
+ ```
@@ -0,0 +1,503 @@
1
+ import sqlite3
2
+ import threading
3
+ from contextlib import contextmanager
4
+ from hashlib import md5
5
+ from typing import Any, AsyncIterator, Dict, Iterator, Optional, Sequence, Tuple
6
+
7
+ from langchain_core.runnables import RunnableConfig
8
+
9
+ from langgraph.checkpoint.base import (
10
+ BaseCheckpointSaver,
11
+ ChannelVersions,
12
+ Checkpoint,
13
+ CheckpointMetadata,
14
+ CheckpointTuple,
15
+ EmptyChannelError,
16
+ SerializerProtocol,
17
+ get_checkpoint_id,
18
+ )
19
+ from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
20
+ from langgraph.checkpoint.serde.types import ChannelProtocol
21
+ from langgraph.checkpoint.sqlite.utils import search_where
22
+
23
+ _AIO_ERROR_MSG = (
24
+ "The SqliteSaver does not support async methods. "
25
+ "Consider using AsyncSqliteSaver instead.\n"
26
+ "from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver\n"
27
+ "Note: AsyncSqliteSaver requires the aiosqlite package to use.\n"
28
+ "Install with:\n`pip install aiosqlite`\n"
29
+ "See https://langchain-ai.github.io/langgraph/reference/checkpoints/asyncsqlitesaver"
30
+ "for more information."
31
+ )
32
+
33
+
34
+ class SqliteSaver(BaseCheckpointSaver):
35
+ """A checkpoint saver that stores checkpoints in a SQLite database.
36
+
37
+ Note:
38
+ This class is meant for lightweight, synchronous use cases
39
+ (demos and small projects) and does not
40
+ scale to multiple threads.
41
+ For a similar sqlite saver with `async` support,
42
+ consider using [AsyncSqliteSaver][asyncsqlitesaver].
43
+
44
+ Args:
45
+ conn (sqlite3.Connection): The SQLite database connection.
46
+ serde (Optional[SerializerProtocol]): The serializer to use for serializing and deserializing checkpoints. Defaults to JsonPlusSerializerCompat.
47
+
48
+ Examples:
49
+
50
+ >>> import sqlite3
51
+ >>> from langgraph.checkpoint.sqlite import SqliteSaver
52
+ >>> from langgraph.graph import StateGraph
53
+ >>>
54
+ >>> builder = StateGraph(int)
55
+ >>> builder.add_node("add_one", lambda x: x + 1)
56
+ >>> builder.set_entry_point("add_one")
57
+ >>> builder.set_finish_point("add_one")
58
+ >>> conn = sqlite3.connect("checkpoints.sqlite")
59
+ >>> memory = SqliteSaver(conn)
60
+ >>> graph = builder.compile(checkpointer=memory)
61
+ >>> config = {"configurable": {"thread_id": "1"}}
62
+ >>> graph.get_state(config)
63
+ >>> result = graph.invoke(3, config)
64
+ >>> graph.get_state(config)
65
+ StateSnapshot(values=4, next=(), config={'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '0c62ca34-ac19-445d-bbb0-5b4984975b2a'}}, parent_config=None)
66
+ """ # noqa
67
+
68
+ conn: sqlite3.Connection
69
+ is_setup: bool
70
+
71
+ def __init__(
72
+ self,
73
+ conn: sqlite3.Connection,
74
+ *,
75
+ serde: Optional[SerializerProtocol] = None,
76
+ ) -> None:
77
+ super().__init__(serde=serde)
78
+ self.jsonplus_serde = JsonPlusSerializer()
79
+ self.conn = conn
80
+ self.is_setup = False
81
+ self.lock = threading.Lock()
82
+
83
+ @classmethod
84
+ @contextmanager
85
+ def from_conn_string(cls, conn_string: str) -> Iterator["SqliteSaver"]:
86
+ """Create a new SqliteSaver instance from a connection string.
87
+
88
+ Args:
89
+ conn_string (str): The SQLite connection string.
90
+
91
+ Yields:
92
+ SqliteSaver: A new SqliteSaver instance.
93
+
94
+ Examples:
95
+
96
+ In memory:
97
+
98
+ with SqliteSaver.from_conn_string(":memory:") as memory:
99
+ ...
100
+
101
+ To disk:
102
+
103
+ with SqliteSaver.from_conn_string("checkpoints.sqlite") as memory:
104
+ ...
105
+ """
106
+ with sqlite3.connect(
107
+ conn_string,
108
+ # https://ricardoanderegg.com/posts/python-sqlite-thread-safety/
109
+ check_same_thread=False,
110
+ ) as conn:
111
+ yield SqliteSaver(conn)
112
+
113
+ def setup(self) -> None:
114
+ """Set up the checkpoint database.
115
+
116
+ This method creates the necessary tables in the SQLite database if they don't
117
+ already exist. It is called automatically when needed and should not be called
118
+ directly by the user.
119
+ """
120
+ if self.is_setup:
121
+ return
122
+
123
+ self.conn.executescript(
124
+ """
125
+ PRAGMA journal_mode=WAL;
126
+ CREATE TABLE IF NOT EXISTS checkpoints (
127
+ thread_id TEXT NOT NULL,
128
+ checkpoint_ns TEXT NOT NULL DEFAULT '',
129
+ checkpoint_id TEXT NOT NULL,
130
+ parent_checkpoint_id TEXT,
131
+ type TEXT,
132
+ checkpoint BLOB,
133
+ metadata BLOB,
134
+ PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
135
+ );
136
+ CREATE TABLE IF NOT EXISTS writes (
137
+ thread_id TEXT NOT NULL,
138
+ checkpoint_ns TEXT NOT NULL DEFAULT '',
139
+ checkpoint_id TEXT NOT NULL,
140
+ task_id TEXT NOT NULL,
141
+ idx INTEGER NOT NULL,
142
+ channel TEXT NOT NULL,
143
+ type TEXT,
144
+ value BLOB,
145
+ PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
146
+ );
147
+ """
148
+ )
149
+
150
+ self.is_setup = True
151
+
152
+ @contextmanager
153
+ def cursor(self, transaction: bool = True) -> Iterator[sqlite3.Cursor]:
154
+ """Get a cursor for the SQLite database.
155
+
156
+ This method returns a cursor for the SQLite database. It is used internally
157
+ by the SqliteSaver and should not be called directly by the user.
158
+
159
+ Args:
160
+ transaction (bool): Whether to commit the transaction when the cursor is closed. Defaults to True.
161
+
162
+ Yields:
163
+ sqlite3.Cursor: A cursor for the SQLite database.
164
+ """
165
+ self.setup()
166
+ cur = self.conn.cursor()
167
+ try:
168
+ yield cur
169
+ finally:
170
+ if transaction:
171
+ self.conn.commit()
172
+ cur.close()
173
+
174
+ def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
175
+ """Get a checkpoint tuple from the database.
176
+
177
+ This method retrieves a checkpoint tuple from the SQLite database based on the
178
+ provided config. If the config contains a "checkpoint_id" key, the checkpoint with
179
+ the matching thread ID and timestamp is retrieved. Otherwise, the latest checkpoint
180
+ for the given thread ID is retrieved.
181
+
182
+ Args:
183
+ config (RunnableConfig): The config to use for retrieving the checkpoint.
184
+
185
+ Returns:
186
+ Optional[CheckpointTuple]: The retrieved checkpoint tuple, or None if no matching checkpoint was found.
187
+
188
+ Examples:
189
+
190
+ Basic:
191
+ >>> config = {"configurable": {"thread_id": "1"}}
192
+ >>> checkpoint_tuple = memory.get_tuple(config)
193
+ >>> print(checkpoint_tuple)
194
+ CheckpointTuple(...)
195
+
196
+ With timestamp:
197
+
198
+ >>> config = {
199
+ ... "configurable": {
200
+ ... "thread_id": "1",
201
+ ... "checkpoint_ns": "",
202
+ ... "checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875",
203
+ ... }
204
+ ... }
205
+ >>> checkpoint_tuple = memory.get_tuple(config)
206
+ >>> print(checkpoint_tuple)
207
+ CheckpointTuple(...)
208
+ """ # noqa
209
+ checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
210
+ with self.cursor(transaction=False) as cur:
211
+ # find the latest checkpoint for the thread_id
212
+ if checkpoint_id := get_checkpoint_id(config):
213
+ cur.execute(
214
+ "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?",
215
+ (
216
+ str(config["configurable"]["thread_id"]),
217
+ checkpoint_ns,
218
+ checkpoint_id,
219
+ ),
220
+ )
221
+ else:
222
+ cur.execute(
223
+ "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1",
224
+ (str(config["configurable"]["thread_id"]), checkpoint_ns),
225
+ )
226
+ # if a checkpoint is found, return it
227
+ if value := cur.fetchone():
228
+ (
229
+ thread_id,
230
+ checkpoint_id,
231
+ parent_checkpoint_id,
232
+ type,
233
+ checkpoint,
234
+ metadata,
235
+ ) = value
236
+ if not get_checkpoint_id(config):
237
+ config = {
238
+ "configurable": {
239
+ "thread_id": thread_id,
240
+ "checkpoint_ns": checkpoint_ns,
241
+ "checkpoint_id": checkpoint_id,
242
+ }
243
+ }
244
+ # find any pending writes
245
+ cur.execute(
246
+ "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?",
247
+ (
248
+ str(config["configurable"]["thread_id"]),
249
+ checkpoint_ns,
250
+ str(config["configurable"]["checkpoint_id"]),
251
+ ),
252
+ )
253
+ # deserialize the checkpoint and metadata
254
+ return CheckpointTuple(
255
+ config,
256
+ self.serde.loads_typed((type, checkpoint)),
257
+ self.jsonplus_serde.loads(metadata) if metadata is not None else {},
258
+ (
259
+ {
260
+ "configurable": {
261
+ "thread_id": thread_id,
262
+ "checkpoint_ns": checkpoint_ns,
263
+ "checkpoint_id": parent_checkpoint_id,
264
+ }
265
+ }
266
+ if parent_checkpoint_id
267
+ else None
268
+ ),
269
+ [
270
+ (task_id, channel, self.serde.loads_typed((type, value)))
271
+ for task_id, channel, type, value in cur
272
+ ],
273
+ )
274
+
275
+ def list(
276
+ self,
277
+ config: Optional[RunnableConfig],
278
+ *,
279
+ filter: Optional[Dict[str, Any]] = None,
280
+ before: Optional[RunnableConfig] = None,
281
+ limit: Optional[int] = None,
282
+ ) -> Iterator[CheckpointTuple]:
283
+ """List checkpoints from the database.
284
+
285
+ This method retrieves a list of checkpoint tuples from the SQLite database based
286
+ on the provided config. The checkpoints are ordered by timestamp in descending order.
287
+
288
+ Args:
289
+ config (RunnableConfig): The config to use for listing the checkpoints.
290
+ filter (Optional[Dict[str, Any]]): Additional filtering criteria for metadata. Defaults to None.
291
+ before (Optional[RunnableConfig]): If provided, only checkpoints before the specified timestamp are returned. Defaults to None.
292
+ limit (Optional[int]): The maximum number of checkpoints to return. Defaults to None.
293
+
294
+ Yields:
295
+ Iterator[CheckpointTuple]: An iterator of checkpoint tuples.
296
+
297
+ Examples:
298
+ >>> from langgraph.checkpoint.sqlite import SqliteSaver
299
+ >>> with SqliteSaver.from_conn_string(":memory:") as memory:
300
+ ... # Run a graph, then list the checkpoints
301
+ >>> config = {"configurable": {"thread_id": "1"}}
302
+ >>> checkpoints = list(memory.list(config, limit=2))
303
+ >>> print(checkpoints)
304
+ [CheckpointTuple(...), CheckpointTuple(...)]
305
+
306
+ >>> config = {"configurable": {"thread_id": "1"}}
307
+ >>> before = {"configurable": {"checkpoint_id": "1ef4f797-8335-6428-8001-8a1503f9b875"}}
308
+ >>> with SqliteSaver.from_conn_string(":memory:") as memory:
309
+ ... # Run a graph, then list the checkpoints
310
+ >>> checkpoints = list(memory.list(config, before=before))
311
+ >>> print(checkpoints)
312
+ [CheckpointTuple(...), ...]
313
+ """
314
+ where, param_values = search_where(config, filter, before)
315
+ query = f"""SELECT thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata
316
+ FROM checkpoints
317
+ {where}
318
+ ORDER BY checkpoint_id DESC"""
319
+ if limit:
320
+ query += f" LIMIT {limit}"
321
+ with self.cursor(transaction=False) as cur:
322
+ cur.execute(query, param_values)
323
+ for (
324
+ thread_id,
325
+ checkpoint_ns,
326
+ checkpoint_id,
327
+ parent_checkpoint_id,
328
+ type,
329
+ checkpoint,
330
+ metadata,
331
+ ) in cur:
332
+ yield CheckpointTuple(
333
+ {
334
+ "configurable": {
335
+ "thread_id": thread_id,
336
+ "checkpoint_ns": checkpoint_ns,
337
+ "checkpoint_id": checkpoint_id,
338
+ }
339
+ },
340
+ self.serde.loads_typed((type, checkpoint)),
341
+ self.jsonplus_serde.loads(metadata) if metadata is not None else {},
342
+ (
343
+ {
344
+ "configurable": {
345
+ "thread_id": thread_id,
346
+ "checkpoint_ns": checkpoint_ns,
347
+ "checkpoint_id": parent_checkpoint_id,
348
+ }
349
+ }
350
+ if parent_checkpoint_id
351
+ else None
352
+ ),
353
+ )
354
+
355
+ def put(
356
+ self,
357
+ config: RunnableConfig,
358
+ checkpoint: Checkpoint,
359
+ metadata: CheckpointMetadata,
360
+ new_versions: ChannelVersions,
361
+ ) -> RunnableConfig:
362
+ """Save a checkpoint to the database.
363
+
364
+ This method saves a checkpoint to the SQLite database. The checkpoint is associated
365
+ with the provided config and its parent config (if any).
366
+
367
+ Args:
368
+ config (RunnableConfig): The config to associate with the checkpoint.
369
+ checkpoint (Checkpoint): The checkpoint to save.
370
+ metadata (Optional[dict[str, Any]]): Additional metadata to save with the checkpoint. Defaults to None.
371
+
372
+ Returns:
373
+ RunnableConfig: The updated config containing the saved checkpoint's timestamp.
374
+
375
+ Examples:
376
+
377
+ >>> from langgraph.checkpoint.sqlite import SqliteSaver
378
+ >>> with SqliteSaver.from_conn_string(":memory:") as memory:
379
+ >>> config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}}
380
+ >>> checkpoint = {"ts": "2024-05-04T06:32:42.235444+00:00", "id": "1ef4f797-8335-6428-8001-8a1503f9b875", "data": {"key": "value"}}
381
+ >>> saved_config = memory.put(config, checkpoint, {"source": "input", "step": 1, "writes": {"key": "value"}}, {})
382
+ >>> print(saved_config)
383
+ {'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1ef4f797-8335-6428-8001-8a1503f9b875'}}
384
+ """
385
+ thread_id = config["configurable"]["thread_id"]
386
+ checkpoint_ns = config["configurable"]["checkpoint_ns"]
387
+ type_, serialized_checkpoint = self.serde.dumps_typed(checkpoint)
388
+ serialized_metadata = self.jsonplus_serde.dumps(metadata)
389
+ with self.lock, self.cursor() as cur:
390
+ cur.execute(
391
+ "INSERT OR REPLACE INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)",
392
+ (
393
+ str(config["configurable"]["thread_id"]),
394
+ checkpoint_ns,
395
+ checkpoint["id"],
396
+ config["configurable"].get("checkpoint_id"),
397
+ type_,
398
+ serialized_checkpoint,
399
+ serialized_metadata,
400
+ ),
401
+ )
402
+ return {
403
+ "configurable": {
404
+ "thread_id": thread_id,
405
+ "checkpoint_ns": checkpoint_ns,
406
+ "checkpoint_id": checkpoint["id"],
407
+ }
408
+ }
409
+
410
+ def put_writes(
411
+ self,
412
+ config: RunnableConfig,
413
+ writes: Sequence[Tuple[str, Any]],
414
+ task_id: str,
415
+ ) -> None:
416
+ """Store intermediate writes linked to a checkpoint.
417
+
418
+ This method saves intermediate writes associated with a checkpoint to the SQLite database.
419
+
420
+ Args:
421
+ config (RunnableConfig): Configuration of the related checkpoint.
422
+ writes (Sequence[Tuple[str, Any]]): List of writes to store, each as (channel, value) pair.
423
+ task_id (str): Identifier for the task creating the writes.
424
+ """
425
+ with self.lock, self.cursor() as cur:
426
+ cur.executemany(
427
+ "INSERT OR REPLACE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
428
+ [
429
+ (
430
+ str(config["configurable"]["thread_id"]),
431
+ str(config["configurable"]["checkpoint_ns"]),
432
+ str(config["configurable"]["checkpoint_id"]),
433
+ task_id,
434
+ idx,
435
+ channel,
436
+ *self.serde.dumps_typed(value),
437
+ )
438
+ for idx, (channel, value) in enumerate(writes)
439
+ ],
440
+ )
441
+
442
+ async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
443
+ """Get a checkpoint tuple from the database asynchronously.
444
+
445
+ Note:
446
+ This async method is not supported by the SqliteSaver class.
447
+ Use get_tuple() instead, or consider using [AsyncSqliteSaver][asyncsqlitesaver].
448
+ """
449
+ raise NotImplementedError(_AIO_ERROR_MSG)
450
+
451
+ async def alist(
452
+ self,
453
+ config: Optional[RunnableConfig],
454
+ *,
455
+ filter: Optional[Dict[str, Any]] = None,
456
+ before: Optional[RunnableConfig] = None,
457
+ limit: Optional[int] = None,
458
+ ) -> AsyncIterator[CheckpointTuple]:
459
+ """List checkpoints from the database asynchronously.
460
+
461
+ Note:
462
+ This async method is not supported by the SqliteSaver class.
463
+ Use list() instead, or consider using [AsyncSqliteSaver][asyncsqlitesaver].
464
+ """
465
+ raise NotImplementedError(_AIO_ERROR_MSG)
466
+ yield
467
+
468
+ async def aput(
469
+ self,
470
+ config: RunnableConfig,
471
+ checkpoint: Checkpoint,
472
+ metadata: CheckpointMetadata,
473
+ ) -> RunnableConfig:
474
+ """Save a checkpoint to the database asynchronously.
475
+
476
+ Note:
477
+ This async method is not supported by the SqliteSaver class.
478
+ Use put() instead, or consider using [AsyncSqliteSaver][asyncsqlitesaver].
479
+ """
480
+ raise NotImplementedError(_AIO_ERROR_MSG)
481
+
482
+ def get_next_version(self, current: Optional[str], channel: ChannelProtocol) -> str:
483
+ """Generate the next version ID for a channel.
484
+
485
+ This method creates a new version identifier for a channel based on its current version.
486
+
487
+ Args:
488
+ current (Optional[str]): The current version identifier of the channel.
489
+ channel (BaseChannel): The channel being versioned.
490
+
491
+ Returns:
492
+ str: The next version identifier, which is guaranteed to be monotonically increasing.
493
+ """
494
+ if current is None:
495
+ current_v = 0
496
+ else:
497
+ current_v = int(current.split(".")[0])
498
+ next_v = current_v + 1
499
+ try:
500
+ next_h = md5(self.serde.dumps_typed(channel.checkpoint())[1]).hexdigest()
501
+ except EmptyChannelError:
502
+ next_h = ""
503
+ return f"{next_v:032}.{next_h}"
@@ -0,0 +1,450 @@
1
+ import asyncio
2
+ import functools
3
+ from contextlib import asynccontextmanager
4
+ from typing import (
5
+ Any,
6
+ AsyncIterator,
7
+ Dict,
8
+ Iterator,
9
+ Optional,
10
+ Sequence,
11
+ Tuple,
12
+ TypeVar,
13
+ )
14
+
15
+ import aiosqlite
16
+ from langchain_core.runnables import RunnableConfig
17
+
18
+ from langgraph.checkpoint.base import (
19
+ BaseCheckpointSaver,
20
+ ChannelVersions,
21
+ Checkpoint,
22
+ CheckpointMetadata,
23
+ CheckpointTuple,
24
+ SerializerProtocol,
25
+ get_checkpoint_id,
26
+ )
27
+ from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
28
+ from langgraph.checkpoint.sqlite.utils import search_where
29
+
30
+ T = TypeVar("T", bound=callable)
31
+
32
+
33
+ def not_implemented_sync_method(func: T) -> T:
34
+ @functools.wraps(func)
35
+ def wrapper(*args, **kwargs):
36
+ raise NotImplementedError(
37
+ "The AsyncSqliteSaver does not support synchronous methods. "
38
+ "Consider using the SqliteSaver instead.\n"
39
+ "from langgraph.checkpoint.sqlite import SqliteSaver\n"
40
+ "See https://langchain-ai.github.io/langgraph/reference/checkpoints/langgraph.checkpoint.sqlite.SqliteSaver "
41
+ "for more information."
42
+ )
43
+
44
+ return wrapper
45
+
46
+
47
+ class AsyncSqliteSaver(BaseCheckpointSaver):
48
+ """An asynchronous checkpoint saver that stores checkpoints in a SQLite database.
49
+
50
+ This class provides an asynchronous interface for saving and retrieving checkpoints
51
+ using a SQLite database. It's designed for use in asynchronous environments and
52
+ offers better performance for I/O-bound operations compared to synchronous alternatives.
53
+
54
+ Attributes:
55
+ conn (aiosqlite.Connection): The asynchronous SQLite database connection.
56
+ serde (SerializerProtocol): The serializer used for encoding/decoding checkpoints.
57
+
58
+ Tip:
59
+ Requires the [aiosqlite](https://pypi.org/project/aiosqlite/) package.
60
+ Install it with `pip install aiosqlite`.
61
+
62
+ Warning:
63
+ While this class supports asynchronous checkpointing, it is not recommended
64
+ for production workloads due to limitations in SQLite's write performance.
65
+ For production use, consider a more robust database like PostgreSQL.
66
+
67
+ Tip:
68
+ Remember to **close the database connection** after executing your code,
69
+ otherwise, you may see the graph "hang" after execution (since the program
70
+ will not exit until the connection is closed).
71
+
72
+ The easiest way is to use the `async with` statement as shown in the examples.
73
+
74
+ ```python
75
+ async with AsyncSqliteSaver.from_conn_string("checkpoints.sqlite") as saver:
76
+ # Your code here
77
+ graph = builder.compile(checkpointer=saver)
78
+ config = {"configurable": {"thread_id": "thread-1"}}
79
+ async for event in graph.astream_events(..., config, version="v1"):
80
+ print(event)
81
+ ```
82
+
83
+ Examples:
84
+ Usage within StateGraph:
85
+
86
+ ```pycon
87
+ >>> import asyncio
88
+ >>>
89
+ >>> from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
90
+ >>> from langgraph.graph import StateGraph
91
+ >>>
92
+ >>> builder = StateGraph(int)
93
+ >>> builder.add_node("add_one", lambda x: x + 1)
94
+ >>> builder.set_entry_point("add_one")
95
+ >>> builder.set_finish_point("add_one")
96
+ >>> async with AsyncSqliteSaver.from_conn_string("checkpoints.db") as memory:
97
+ >>> graph = builder.compile(checkpointer=memory)
98
+ >>> coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}})
99
+ >>> print(asyncio.run(coro))
100
+ Output: 2
101
+ ```
102
+ Raw usage:
103
+
104
+ ```pycon
105
+ >>> import asyncio
106
+ >>> import aiosqlite
107
+ >>> from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
108
+ >>>
109
+ >>> async def main():
110
+ >>> async with aiosqlite.connect("checkpoints.db") as conn:
111
+ ... saver = AsyncSqliteSaver(conn)
112
+ ... config = {"configurable": {"thread_id": "1"}}
113
+ ... checkpoint = {"ts": "2023-05-03T10:00:00Z", "data": {"key": "value"}}
114
+ ... saved_config = await saver.aput(config, checkpoint, {}, {})
115
+ ... print(saved_config)
116
+ >>> asyncio.run(main())
117
+ {"configurable": {"thread_id": "1", "checkpoint_id": "0c62ca34-ac19-445d-bbb0-5b4984975b2a"}}
118
+ ```
119
+ """
120
+
121
+ lock: asyncio.Lock
122
+ is_setup: bool
123
+
124
+ def __init__(
125
+ self,
126
+ conn: aiosqlite.Connection,
127
+ *,
128
+ serde: Optional[SerializerProtocol] = None,
129
+ ):
130
+ super().__init__(serde=serde)
131
+ self.jsonplus_serde = JsonPlusSerializer()
132
+ self.conn = conn
133
+ self.lock = asyncio.Lock()
134
+ self.is_setup = False
135
+
136
+ @classmethod
137
+ @asynccontextmanager
138
+ async def from_conn_string(
139
+ cls, conn_string: str
140
+ ) -> AsyncIterator["AsyncSqliteSaver"]:
141
+ """Create a new AsyncSqliteSaver instance from a connection string.
142
+
143
+ Args:
144
+ conn_string (str): The SQLite connection string.
145
+
146
+ Yields:
147
+ AsyncSqliteSaver: A new AsyncSqliteSaver instance.
148
+ """
149
+ async with aiosqlite.connect(conn_string) as conn:
150
+ yield AsyncSqliteSaver(conn)
151
+
152
+ @not_implemented_sync_method
153
+ def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
154
+ """Get a checkpoint tuple from the database.
155
+
156
+ Note:
157
+ This method is not implemented for the AsyncSqliteSaver. Use `aget` instead.
158
+ Or consider using the [SqliteSaver][sqlitesaver] checkpointer.
159
+ """
160
+
161
+ @not_implemented_sync_method
162
+ def list(
163
+ self,
164
+ config: Optional[RunnableConfig],
165
+ *,
166
+ filter: Optional[Dict[str, Any]] = None,
167
+ before: Optional[RunnableConfig] = None,
168
+ limit: Optional[int] = None,
169
+ ) -> Iterator[CheckpointTuple]:
170
+ """List checkpoints from the database.
171
+
172
+ Note:
173
+ This method is not implemented for the AsyncSqliteSaver. Use `alist` instead.
174
+ Or consider using the [SqliteSaver][sqlitesaver] checkpointer.
175
+ """
176
+
177
+ @not_implemented_sync_method
178
+ def put(
179
+ self,
180
+ config: RunnableConfig,
181
+ checkpoint: Checkpoint,
182
+ metadata: CheckpointMetadata,
183
+ ) -> RunnableConfig:
184
+ """Save a checkpoint to the database. FOO"""
185
+
186
+ async def setup(self) -> None:
187
+ """Set up the checkpoint database asynchronously.
188
+
189
+ This method creates the necessary tables in the SQLite database if they don't
190
+ already exist. It is called automatically when needed and should not be called
191
+ directly by the user.
192
+ """
193
+ async with self.lock:
194
+ if self.is_setup:
195
+ return
196
+ if not self.conn.is_alive():
197
+ await self.conn
198
+ async with self.conn.executescript(
199
+ """
200
+ PRAGMA journal_mode=WAL;
201
+ CREATE TABLE IF NOT EXISTS checkpoints (
202
+ thread_id TEXT NOT NULL,
203
+ checkpoint_ns TEXT NOT NULL DEFAULT '',
204
+ checkpoint_id TEXT NOT NULL,
205
+ parent_checkpoint_id TEXT,
206
+ type TEXT,
207
+ checkpoint BLOB,
208
+ metadata BLOB,
209
+ PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
210
+ );
211
+ CREATE TABLE IF NOT EXISTS writes (
212
+ thread_id TEXT NOT NULL,
213
+ checkpoint_ns TEXT NOT NULL DEFAULT '',
214
+ checkpoint_id TEXT NOT NULL,
215
+ task_id TEXT NOT NULL,
216
+ idx INTEGER NOT NULL,
217
+ channel TEXT NOT NULL,
218
+ type TEXT,
219
+ value BLOB,
220
+ PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
221
+ );
222
+ """
223
+ ):
224
+ await self.conn.commit()
225
+
226
+ self.is_setup = True
227
+
228
+ async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
229
+ """Get a checkpoint tuple from the database asynchronously.
230
+
231
+ This method retrieves a checkpoint tuple from the SQLite database based on the
232
+ provided config. If the config contains a "checkpoint_id" key, the checkpoint with
233
+ the matching thread ID and timestamp is retrieved. Otherwise, the latest checkpoint
234
+ for the given thread ID is retrieved.
235
+
236
+ Args:
237
+ config (RunnableConfig): The config to use for retrieving the checkpoint.
238
+
239
+ Returns:
240
+ Optional[CheckpointTuple]: The retrieved checkpoint tuple, or None if no matching checkpoint was found.
241
+ """
242
+ await self.setup()
243
+ checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
244
+ async with self.conn.cursor() as cur:
245
+ # find the latest checkpoint for the thread_id
246
+ if checkpoint_id := get_checkpoint_id(config):
247
+ await cur.execute(
248
+ "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?",
249
+ (
250
+ str(config["configurable"]["thread_id"]),
251
+ checkpoint_ns,
252
+ checkpoint_id,
253
+ ),
254
+ )
255
+ else:
256
+ await cur.execute(
257
+ "SELECT thread_id, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata FROM checkpoints WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1",
258
+ (str(config["configurable"]["thread_id"]), checkpoint_ns),
259
+ )
260
+ # if a checkpoint is found, return it
261
+ if value := await cur.fetchone():
262
+ (
263
+ thread_id,
264
+ checkpoint_id,
265
+ parent_checkpoint_id,
266
+ type,
267
+ checkpoint,
268
+ metadata,
269
+ ) = value
270
+ if not get_checkpoint_id(config):
271
+ config = {
272
+ "configurable": {
273
+ "thread_id": thread_id,
274
+ "checkpoint_ns": checkpoint_ns,
275
+ "checkpoint_id": checkpoint_id,
276
+ }
277
+ }
278
+ # find any pending writes
279
+ await cur.execute(
280
+ "SELECT task_id, channel, type, value FROM writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?",
281
+ (
282
+ str(config["configurable"]["thread_id"]),
283
+ checkpoint_ns,
284
+ str(config["configurable"]["checkpoint_id"]),
285
+ ),
286
+ )
287
+ # deserialize the checkpoint and metadata
288
+ return CheckpointTuple(
289
+ config,
290
+ self.serde.loads_typed((type, checkpoint)),
291
+ self.jsonplus_serde.loads(metadata) if metadata is not None else {},
292
+ (
293
+ {
294
+ "configurable": {
295
+ "thread_id": thread_id,
296
+ "checkpoint_ns": checkpoint_ns,
297
+ "checkpoint_id": parent_checkpoint_id,
298
+ }
299
+ }
300
+ if parent_checkpoint_id
301
+ else None
302
+ ),
303
+ [
304
+ (task_id, channel, self.serde.loads_typed((type, value)))
305
+ async for task_id, channel, type, value in cur
306
+ ],
307
+ )
308
+
309
+ async def alist(
310
+ self,
311
+ config: Optional[RunnableConfig],
312
+ *,
313
+ filter: Optional[Dict[str, Any]] = None,
314
+ before: Optional[RunnableConfig] = None,
315
+ limit: Optional[int] = None,
316
+ ) -> AsyncIterator[CheckpointTuple]:
317
+ """List checkpoints from the database asynchronously.
318
+
319
+ This method retrieves a list of checkpoint tuples from the SQLite database based
320
+ on the provided config. The checkpoints are ordered by timestamp in descending order.
321
+
322
+ Args:
323
+ config (Optional[RunnableConfig]): Base configuration for filtering checkpoints.
324
+ filter (Optional[Dict[str, Any]]): Additional filtering criteria for metadata.
325
+ before (Optional[RunnableConfig]): List checkpoints created before this configuration.
326
+ limit (Optional[int]): Maximum number of checkpoints to return.
327
+
328
+ Yields:
329
+ AsyncIterator[CheckpointTuple]: An asynchronous iterator of matching checkpoint tuples.
330
+ """
331
+ await self.setup()
332
+ where, param_values = search_where(config, filter, before)
333
+ query = f"""SELECT thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata
334
+ FROM checkpoints
335
+ {where}
336
+ ORDER BY checkpoint_id DESC"""
337
+ if limit:
338
+ query += f" LIMIT {limit}"
339
+ async with self.conn.execute(query, param_values) as cursor:
340
+ async for (
341
+ thread_id,
342
+ checkpoint_ns,
343
+ checkpoint_id,
344
+ parent_checkpoint_id,
345
+ type,
346
+ checkpoint,
347
+ metadata,
348
+ ) in cursor:
349
+ yield CheckpointTuple(
350
+ {
351
+ "configurable": {
352
+ "thread_id": thread_id,
353
+ "checkpoint_ns": checkpoint_ns,
354
+ "checkpoint_id": checkpoint_id,
355
+ }
356
+ },
357
+ self.serde.loads_typed((type, checkpoint)),
358
+ self.jsonplus_serde.loads(metadata) if metadata is not None else {},
359
+ (
360
+ {
361
+ "configurable": {
362
+ "thread_id": thread_id,
363
+ "checkpoint_ns": checkpoint_ns,
364
+ "checkpoint_id": parent_checkpoint_id,
365
+ }
366
+ }
367
+ if parent_checkpoint_id
368
+ else None
369
+ ),
370
+ )
371
+
372
+ async def aput(
373
+ self,
374
+ config: RunnableConfig,
375
+ checkpoint: Checkpoint,
376
+ metadata: CheckpointMetadata,
377
+ new_versions: ChannelVersions,
378
+ ) -> RunnableConfig:
379
+ """Save a checkpoint to the database asynchronously.
380
+
381
+ This method saves a checkpoint to the SQLite database. The checkpoint is associated
382
+ with the provided config and its parent config (if any).
383
+
384
+ Args:
385
+ config (RunnableConfig): The config to associate with the checkpoint.
386
+ checkpoint (Checkpoint): The checkpoint to save.
387
+ metadata (CheckpointMetadata): Additional metadata to save with the checkpoint.
388
+ new_versions (dict): New versions as of this write
389
+
390
+ Returns:
391
+ RunnableConfig: The updated config containing the saved checkpoint's timestamp.
392
+ """
393
+ await self.setup()
394
+ thread_id = config["configurable"]["thread_id"]
395
+ checkpoint_ns = config["configurable"]["checkpoint_ns"]
396
+ type_, serialized_checkpoint = self.serde.dumps_typed(checkpoint)
397
+ serialized_metadata = self.jsonplus_serde.dumps(metadata)
398
+ async with self.conn.execute(
399
+ "INSERT OR REPLACE INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata) VALUES (?, ?, ?, ?, ?, ?, ?)",
400
+ (
401
+ str(config["configurable"]["thread_id"]),
402
+ checkpoint_ns,
403
+ checkpoint["id"],
404
+ config["configurable"].get("checkpoint_id"),
405
+ type_,
406
+ serialized_checkpoint,
407
+ serialized_metadata,
408
+ ),
409
+ ):
410
+ await self.conn.commit()
411
+ return {
412
+ "configurable": {
413
+ "thread_id": thread_id,
414
+ "checkpoint_ns": checkpoint_ns,
415
+ "checkpoint_id": checkpoint["id"],
416
+ }
417
+ }
418
+
419
+ async def aput_writes(
420
+ self,
421
+ config: RunnableConfig,
422
+ writes: Sequence[Tuple[str, Any]],
423
+ task_id: str,
424
+ ) -> None:
425
+ """Store intermediate writes linked to a checkpoint asynchronously.
426
+
427
+ This method saves intermediate writes associated with a checkpoint to the database.
428
+
429
+ Args:
430
+ config (RunnableConfig): Configuration of the related checkpoint.
431
+ writes (Sequence[Tuple[str, Any]]): List of writes to store, each as (channel, value) pair.
432
+ task_id (str): Identifier for the task creating the writes.
433
+ """
434
+ await self.setup()
435
+ async with self.conn.executemany(
436
+ "INSERT OR REPLACE INTO writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
437
+ [
438
+ (
439
+ str(config["configurable"]["thread_id"]),
440
+ str(config["configurable"]["checkpoint_ns"]),
441
+ str(config["configurable"]["checkpoint_id"]),
442
+ task_id,
443
+ idx,
444
+ channel,
445
+ *self.serde.dumps_typed(value),
446
+ )
447
+ for idx, (channel, value) in enumerate(writes)
448
+ ],
449
+ ):
450
+ await self.conn.commit()
@@ -0,0 +1,88 @@
1
+ import json
2
+ from typing import Any, Dict, Optional, Sequence, Tuple
3
+
4
+ from langchain_core.runnables import RunnableConfig
5
+
6
+ from langgraph.checkpoint.base import get_checkpoint_id
7
+
8
+
9
+ def _metadata_predicate(
10
+ metadata_filter: Dict[str, Any],
11
+ ) -> Tuple[Sequence[str], Sequence[Any]]:
12
+ """Return WHERE clause predicates for (a)search() given metadata filter.
13
+
14
+ This method returns a tuple of a string and a tuple of values. The string
15
+ is the parametered WHERE clause predicate (excluding the WHERE keyword):
16
+ "column1 = ? AND column2 IS ?". The tuple of values contains the values
17
+ for each of the corresponding parameters.
18
+ """
19
+
20
+ def _where_value(query_value: Any) -> Tuple[str, Any]:
21
+ """Return tuple of operator and value for WHERE clause predicate."""
22
+ if query_value is None:
23
+ return ("IS ?", None)
24
+ elif (
25
+ isinstance(query_value, str)
26
+ or isinstance(query_value, int)
27
+ or isinstance(query_value, float)
28
+ ):
29
+ return ("= ?", query_value)
30
+ elif isinstance(query_value, bool):
31
+ return ("= ?", 1 if query_value else 0)
32
+ elif isinstance(query_value, dict) or isinstance(query_value, list):
33
+ # query value for JSON object cannot have trailing space after separators (, :)
34
+ # SQLite json_extract() returns JSON string without whitespace
35
+ return ("= ?", json.dumps(query_value, separators=(",", ":")))
36
+ else:
37
+ return ("= ?", str(query_value))
38
+
39
+ predicates = []
40
+ param_values = []
41
+
42
+ # process metadata query
43
+ for query_key, query_value in metadata_filter.items():
44
+ operator, param_value = _where_value(query_value)
45
+ predicates.append(
46
+ f"json_extract(CAST(metadata AS TEXT), '$.{query_key}') {operator}"
47
+ )
48
+ param_values.append(param_value)
49
+
50
+ return (predicates, param_values)
51
+
52
+
53
+ def search_where(
54
+ config: Optional[RunnableConfig],
55
+ filter: Optional[Dict[str, Any]],
56
+ before: Optional[RunnableConfig] = None,
57
+ ) -> Tuple[str, Sequence[Any]]:
58
+ """Return WHERE clause predicates for (a)search() given metadata filter
59
+ and `before` config.
60
+
61
+ This method returns a tuple of a string and a tuple of values. The string
62
+ is the parametered WHERE clause predicate (including the WHERE keyword):
63
+ "WHERE column1 = ? AND column2 IS ?". The tuple of values contains the
64
+ values for each of the corresponding parameters.
65
+ """
66
+ wheres = []
67
+ param_values = []
68
+
69
+ # construct predicate for config filter
70
+ if config is not None:
71
+ wheres.append("thread_id = ?")
72
+ param_values.append(config["configurable"]["thread_id"])
73
+ checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
74
+ wheres.append("checkpoint_ns = ?")
75
+ param_values.append(checkpoint_ns)
76
+
77
+ # construct predicate for metadata filter
78
+ if filter:
79
+ metadata_predicates, metadata_values = _metadata_predicate(filter)
80
+ wheres.extend(metadata_predicates)
81
+ param_values.extend(metadata_values)
82
+
83
+ # construct predicate for `before`
84
+ if before is not None:
85
+ wheres.append("checkpoint_id < ?")
86
+ param_values.append(get_checkpoint_id(before))
87
+
88
+ return ("WHERE " + " AND ".join(wheres) if wheres else "", param_values)
@@ -0,0 +1,55 @@
1
+ [tool.poetry]
2
+ name = "langgraph-checkpoint-sqlite"
3
+ version = "1.0.0"
4
+ description = "Library with a SQLite implementation of LangGraph checkpoint saver."
5
+ authors = []
6
+ license = "MIT"
7
+ readme = "README.md"
8
+ repository = "https://www.github.com/langchain-ai/langgraph"
9
+ packages = [{ include = "langgraph" }]
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.9.0"
13
+ langgraph-checkpoint = "^1.0.1"
14
+ aiosqlite = "^0.20.0"
15
+
16
+ [tool.poetry.group.dev.dependencies]
17
+ ruff = "^0.1.4"
18
+ codespell = "^2.2.0"
19
+ pytest = "^7.2.1"
20
+ pytest-asyncio = "^0.21.1"
21
+ pytest-mock = "^3.11.1"
22
+ pytest-watcher = "^0.4.1"
23
+ mypy = "^1.10.0"
24
+ langgraph-checkpoint = {path = "../checkpoint", develop = true}
25
+
26
+ [tool.pytest.ini_options]
27
+ # --strict-markers will raise errors on unknown marks.
28
+ # https://docs.pytest.org/en/7.1.x/how-to/mark.html#raising-errors-on-unknown-marks
29
+ #
30
+ # https://docs.pytest.org/en/7.1.x/reference/reference.html
31
+ # --strict-config any warnings encountered while parsing the `pytest`
32
+ # section of the configuration file raise errors.
33
+ addopts = "--strict-markers --strict-config --durations=5 -vv"
34
+ asyncio_mode = "auto"
35
+
36
+
37
+ [build-system]
38
+ requires = ["poetry-core"]
39
+ build-backend = "poetry.core.masonry.api"
40
+
41
+ [tool.ruff]
42
+ lint.select = [
43
+ "E", # pycodestyle
44
+ "F", # Pyflakes
45
+ "UP", # pyupgrade
46
+ "B", # flake8-bugbear
47
+ "I", # isort
48
+ ]
49
+ lint.ignore = ["E501", "B008", "UP007", "UP006"]
50
+
51
+ [tool.pytest-watcher]
52
+ now = true
53
+ delay = 0.1
54
+ runner_args = ["--ff", "-v", "--tb", "short"]
55
+ patterns = ["*.py"]