langgraph-checkpoint 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.
- langgraph_checkpoint-1.0.0/LICENSE +21 -0
- langgraph_checkpoint-1.0.0/PKG-INFO +103 -0
- langgraph_checkpoint-1.0.0/README.md +85 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/base/__init__.py +432 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/base/id.py +108 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/memory.py +351 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/py.typed +0 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/serde/__init__.py +0 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/serde/base.py +45 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/serde/jsonplus.py +112 -0
- langgraph_checkpoint-1.0.0/langgraph/checkpoint/serde/types.py +66 -0
- langgraph_checkpoint-1.0.0/pyproject.toml +54 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 LangChain, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: langgraph-checkpoint
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Library with base interfaces for LangGraph checkpoint savers.
|
|
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: langchain-core (>=0.2.22,<0.3)
|
|
15
|
+
Project-URL: Repository, https://www.github.com/langchain-ai/langgraph
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# LangGraph Checkpoint
|
|
19
|
+
|
|
20
|
+
This library defines the base interface for LangGraph checkpointers. Checkpointers provide persistence layer for LangGraph. They allow you to interact with and manage the graph's state. When you use a graph with a checkpointer, the checkpointer saves a _checkpoint_ of the graph state at every superstep, enabling several powerful capabilities like human-in-the-loop, "memory" between interactions and more.
|
|
21
|
+
|
|
22
|
+
## Key concepts
|
|
23
|
+
|
|
24
|
+
### Checkpoint
|
|
25
|
+
|
|
26
|
+
Checkpoint is a snapshot of the graph state at a given point in time. Checkpoint tuple refers to an object containing checkpoint and the associated config, metadata and pending writes.
|
|
27
|
+
|
|
28
|
+
### Thread
|
|
29
|
+
|
|
30
|
+
Threads enable the checkpointing of multiple different runs, making them essential for multi-tenant chat applications and other scenarios where maintaining separate states is necessary. A thread is a unique ID assigned to a series of checkpoints saved by a checkpointer. When using a checkpointer, you must specify a `thread_id` and optionally `checkpoint_id` when running the graph.
|
|
31
|
+
|
|
32
|
+
- `thread_id` is simply the ID of a thread. This is always required
|
|
33
|
+
- `checkpoint_id` can optionally be passed. This identifier refers to a specific checkpoint within a thread. This can be used to kick of a run of a graph from some point halfway through a thread.
|
|
34
|
+
|
|
35
|
+
You must pass these when invoking the graph as part of the configurable part of the config, e.g.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
{"configurable": {"thread_id": "1"}} # valid config
|
|
39
|
+
{"configurable": {"thread_id": "1", "checkpoint_id": "0c62ca34-ac19-445d-bbb0-5b4984975b2a"}} # also valid config
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Serde
|
|
43
|
+
|
|
44
|
+
`langgraph_checkpoint` also defines protocol for serialization/deserialization (serde) and provides an default implementation (`langgraph.checkpoint.serde.jsonplus.JsonPlusSerializer`) that handles a wide variety of types, including LangChain and LangGraph primitives, datetimes, enums and more.
|
|
45
|
+
|
|
46
|
+
### Pending writes
|
|
47
|
+
|
|
48
|
+
When a graph node fails mid-execution at a given superstep, LangGraph stores pending checkpoint writes from any other nodes that completed successfully at that superstep, so that whenever we resume graph execution from that superstep we don't re-run the successful nodes.
|
|
49
|
+
|
|
50
|
+
## Interface
|
|
51
|
+
|
|
52
|
+
Each checkpointer should conform to `langgraph.checkpoint.base.BaseCheckpointSaver` interface and must implement the following methods:
|
|
53
|
+
|
|
54
|
+
- `.put` - Store a checkpoint with its configuration and metadata.
|
|
55
|
+
- `.put_writes` - Store intermediate writes linked to a checkpoint (i.e. pending writes).
|
|
56
|
+
- `.get_tuple` - Fetch a checkpoint tuple using for a given configuration (`thread_id` and `thread_ts`).
|
|
57
|
+
- `.list` - List checkpoints that match a given configuration and filter criteria.
|
|
58
|
+
|
|
59
|
+
If the checkpointer will be used with asynchronous graph execution (i.e. executing the graph via `.ainvoke`, `.astream`, `.abatch`), checkpointer must implement asynchronous versions of the above methods (`.aput`, `.aput_writes`, `.aget_tuple`, `.alist`).
|
|
60
|
+
|
|
61
|
+
## Usage
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from langgraph.checkpoint.memory import MemorySaver
|
|
65
|
+
|
|
66
|
+
checkpointer = MemorySaver()
|
|
67
|
+
checkpoint = {
|
|
68
|
+
"v": 1,
|
|
69
|
+
"ts": "2024-07-31T20:14:19.804150+00:00",
|
|
70
|
+
"id": "1ef4f797-8335-6428-8001-8a1503f9b875",
|
|
71
|
+
"channel_values": {
|
|
72
|
+
"my_key": "meow",
|
|
73
|
+
"node": "node"
|
|
74
|
+
},
|
|
75
|
+
"channel_versions": {
|
|
76
|
+
"__start__": 2,
|
|
77
|
+
"my_key": 3,
|
|
78
|
+
"start:node": 3,
|
|
79
|
+
"node": 3
|
|
80
|
+
},
|
|
81
|
+
"versions_seen": {
|
|
82
|
+
"__input__": {},
|
|
83
|
+
"__start__": {
|
|
84
|
+
"__start__": 1
|
|
85
|
+
},
|
|
86
|
+
"node": {
|
|
87
|
+
"start:node": 2
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
"pending_sends": [],
|
|
91
|
+
"current_tasks": {}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# store checkpoint
|
|
95
|
+
checkpointer.put(thread_config, checkpoint, {})
|
|
96
|
+
|
|
97
|
+
# load checkpoint
|
|
98
|
+
checkpointer.get(thread_config)
|
|
99
|
+
|
|
100
|
+
# list checkpoints
|
|
101
|
+
list(checkpointer.list(thread_config))
|
|
102
|
+
```
|
|
103
|
+
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# LangGraph Checkpoint
|
|
2
|
+
|
|
3
|
+
This library defines the base interface for LangGraph checkpointers. Checkpointers provide persistence layer for LangGraph. They allow you to interact with and manage the graph's state. When you use a graph with a checkpointer, the checkpointer saves a _checkpoint_ of the graph state at every superstep, enabling several powerful capabilities like human-in-the-loop, "memory" between interactions and more.
|
|
4
|
+
|
|
5
|
+
## Key concepts
|
|
6
|
+
|
|
7
|
+
### Checkpoint
|
|
8
|
+
|
|
9
|
+
Checkpoint is a snapshot of the graph state at a given point in time. Checkpoint tuple refers to an object containing checkpoint and the associated config, metadata and pending writes.
|
|
10
|
+
|
|
11
|
+
### Thread
|
|
12
|
+
|
|
13
|
+
Threads enable the checkpointing of multiple different runs, making them essential for multi-tenant chat applications and other scenarios where maintaining separate states is necessary. A thread is a unique ID assigned to a series of checkpoints saved by a checkpointer. When using a checkpointer, you must specify a `thread_id` and optionally `checkpoint_id` when running the graph.
|
|
14
|
+
|
|
15
|
+
- `thread_id` is simply the ID of a thread. This is always required
|
|
16
|
+
- `checkpoint_id` can optionally be passed. This identifier refers to a specific checkpoint within a thread. This can be used to kick of a run of a graph from some point halfway through a thread.
|
|
17
|
+
|
|
18
|
+
You must pass these when invoking the graph as part of the configurable part of the config, e.g.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
{"configurable": {"thread_id": "1"}} # valid config
|
|
22
|
+
{"configurable": {"thread_id": "1", "checkpoint_id": "0c62ca34-ac19-445d-bbb0-5b4984975b2a"}} # also valid config
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Serde
|
|
26
|
+
|
|
27
|
+
`langgraph_checkpoint` also defines protocol for serialization/deserialization (serde) and provides an default implementation (`langgraph.checkpoint.serde.jsonplus.JsonPlusSerializer`) that handles a wide variety of types, including LangChain and LangGraph primitives, datetimes, enums and more.
|
|
28
|
+
|
|
29
|
+
### Pending writes
|
|
30
|
+
|
|
31
|
+
When a graph node fails mid-execution at a given superstep, LangGraph stores pending checkpoint writes from any other nodes that completed successfully at that superstep, so that whenever we resume graph execution from that superstep we don't re-run the successful nodes.
|
|
32
|
+
|
|
33
|
+
## Interface
|
|
34
|
+
|
|
35
|
+
Each checkpointer should conform to `langgraph.checkpoint.base.BaseCheckpointSaver` interface and must implement the following methods:
|
|
36
|
+
|
|
37
|
+
- `.put` - Store a checkpoint with its configuration and metadata.
|
|
38
|
+
- `.put_writes` - Store intermediate writes linked to a checkpoint (i.e. pending writes).
|
|
39
|
+
- `.get_tuple` - Fetch a checkpoint tuple using for a given configuration (`thread_id` and `thread_ts`).
|
|
40
|
+
- `.list` - List checkpoints that match a given configuration and filter criteria.
|
|
41
|
+
|
|
42
|
+
If the checkpointer will be used with asynchronous graph execution (i.e. executing the graph via `.ainvoke`, `.astream`, `.abatch`), checkpointer must implement asynchronous versions of the above methods (`.aput`, `.aput_writes`, `.aget_tuple`, `.alist`).
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from langgraph.checkpoint.memory import MemorySaver
|
|
48
|
+
|
|
49
|
+
checkpointer = MemorySaver()
|
|
50
|
+
checkpoint = {
|
|
51
|
+
"v": 1,
|
|
52
|
+
"ts": "2024-07-31T20:14:19.804150+00:00",
|
|
53
|
+
"id": "1ef4f797-8335-6428-8001-8a1503f9b875",
|
|
54
|
+
"channel_values": {
|
|
55
|
+
"my_key": "meow",
|
|
56
|
+
"node": "node"
|
|
57
|
+
},
|
|
58
|
+
"channel_versions": {
|
|
59
|
+
"__start__": 2,
|
|
60
|
+
"my_key": 3,
|
|
61
|
+
"start:node": 3,
|
|
62
|
+
"node": 3
|
|
63
|
+
},
|
|
64
|
+
"versions_seen": {
|
|
65
|
+
"__input__": {},
|
|
66
|
+
"__start__": {
|
|
67
|
+
"__start__": 1
|
|
68
|
+
},
|
|
69
|
+
"node": {
|
|
70
|
+
"start:node": 2
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
"pending_sends": [],
|
|
74
|
+
"current_tasks": {}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
# store checkpoint
|
|
78
|
+
checkpointer.put(thread_config, checkpoint, {})
|
|
79
|
+
|
|
80
|
+
# load checkpoint
|
|
81
|
+
checkpointer.get(thread_config)
|
|
82
|
+
|
|
83
|
+
# list checkpoints
|
|
84
|
+
list(checkpointer.list(thread_config))
|
|
85
|
+
```
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
from abc import ABC
|
|
2
|
+
from datetime import datetime, timezone
|
|
3
|
+
from typing import (
|
|
4
|
+
Any,
|
|
5
|
+
AsyncIterator,
|
|
6
|
+
Dict,
|
|
7
|
+
Iterator,
|
|
8
|
+
List,
|
|
9
|
+
Literal,
|
|
10
|
+
Mapping,
|
|
11
|
+
NamedTuple,
|
|
12
|
+
Optional,
|
|
13
|
+
Tuple,
|
|
14
|
+
TypedDict,
|
|
15
|
+
TypeVar,
|
|
16
|
+
Union,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from langchain_core.runnables import ConfigurableFieldSpec, RunnableConfig
|
|
20
|
+
|
|
21
|
+
from langgraph.checkpoint.base.id import uuid6
|
|
22
|
+
from langgraph.checkpoint.serde.base import SerializerProtocol, maybe_add_typed_methods
|
|
23
|
+
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
|
24
|
+
from langgraph.checkpoint.serde.types import (
|
|
25
|
+
ChannelProtocol,
|
|
26
|
+
SendProtocol,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
V = TypeVar("V", int, float, str)
|
|
30
|
+
PendingWrite = Tuple[str, str, Any]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Marked as total=False to allow for future expansion.
|
|
34
|
+
class CheckpointMetadata(TypedDict, total=False):
|
|
35
|
+
"""Metadata associated with a checkpoint."""
|
|
36
|
+
|
|
37
|
+
source: Literal["input", "loop", "update"]
|
|
38
|
+
"""The source of the checkpoint.
|
|
39
|
+
- "input": The checkpoint was created from an input to invoke/stream/batch.
|
|
40
|
+
- "loop": The checkpoint was created from inside the pregel loop.
|
|
41
|
+
- "update": The checkpoint was created from a manual state update.
|
|
42
|
+
"""
|
|
43
|
+
step: int
|
|
44
|
+
"""The step number of the checkpoint.
|
|
45
|
+
-1 for the first "input" checkpoint.
|
|
46
|
+
0 for the first "loop" checkpoint.
|
|
47
|
+
... for the nth checkpoint afterwards.
|
|
48
|
+
"""
|
|
49
|
+
writes: dict[str, Any]
|
|
50
|
+
"""The writes that were made between the previous checkpoint and this one.
|
|
51
|
+
|
|
52
|
+
Mapping from node name to writes emitted by that node.
|
|
53
|
+
"""
|
|
54
|
+
score: Optional[int]
|
|
55
|
+
"""The score of the checkpoint.
|
|
56
|
+
|
|
57
|
+
The score can be used to mark a checkpoint as "good".
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TaskInfo(TypedDict):
|
|
62
|
+
status: Literal["scheduled", "success", "error"]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Checkpoint(TypedDict):
|
|
66
|
+
"""State snapshot at a given point in time."""
|
|
67
|
+
|
|
68
|
+
v: int
|
|
69
|
+
"""The version of the checkpoint format. Currently 1."""
|
|
70
|
+
id: str
|
|
71
|
+
"""The ID of the checkpoint. This is both unique and monotonically
|
|
72
|
+
increasing, so can be used for sorting checkpoints from first to last."""
|
|
73
|
+
ts: str
|
|
74
|
+
"""The timestamp of the checkpoint in ISO 8601 format."""
|
|
75
|
+
channel_values: dict[str, Any]
|
|
76
|
+
"""The values of the channels at the time of the checkpoint.
|
|
77
|
+
|
|
78
|
+
Mapping from channel name to channel snapshot value.
|
|
79
|
+
"""
|
|
80
|
+
channel_versions: dict[str, Union[str, int, float]]
|
|
81
|
+
"""The versions of the channels at the time of the checkpoint.
|
|
82
|
+
|
|
83
|
+
The keys are channel names and the values are the logical time step
|
|
84
|
+
at which the channel was last updated.
|
|
85
|
+
"""
|
|
86
|
+
versions_seen: dict[str, dict[str, Union[str, int, float]]]
|
|
87
|
+
"""Map from node ID to map from channel name to version seen.
|
|
88
|
+
|
|
89
|
+
This keeps track of the versions of the channels that each node has seen.
|
|
90
|
+
|
|
91
|
+
Used to determine which nodes to execute next.
|
|
92
|
+
"""
|
|
93
|
+
pending_sends: List[SendProtocol]
|
|
94
|
+
"""List of packets sent to nodes but not yet processed.
|
|
95
|
+
Cleared by the next checkpoint."""
|
|
96
|
+
current_tasks: Dict[str, TaskInfo]
|
|
97
|
+
"""Map from task ID to task info."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def empty_checkpoint() -> Checkpoint:
|
|
101
|
+
return Checkpoint(
|
|
102
|
+
v=1,
|
|
103
|
+
id=str(uuid6(clock_seq=-2)),
|
|
104
|
+
ts=datetime.now(timezone.utc).isoformat(),
|
|
105
|
+
channel_values={},
|
|
106
|
+
channel_versions={},
|
|
107
|
+
versions_seen={},
|
|
108
|
+
pending_sends=[],
|
|
109
|
+
current_tasks={},
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
|
|
114
|
+
return Checkpoint(
|
|
115
|
+
v=checkpoint["v"],
|
|
116
|
+
ts=checkpoint["ts"],
|
|
117
|
+
id=checkpoint["id"],
|
|
118
|
+
channel_values=checkpoint["channel_values"].copy(),
|
|
119
|
+
channel_versions=checkpoint["channel_versions"].copy(),
|
|
120
|
+
versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()},
|
|
121
|
+
pending_sends=checkpoint.get("pending_sends", []).copy(),
|
|
122
|
+
current_tasks=checkpoint.get("current_tasks", {}).copy(),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def create_checkpoint(
|
|
127
|
+
checkpoint: Checkpoint,
|
|
128
|
+
channels: Optional[Mapping[str, ChannelProtocol]],
|
|
129
|
+
step: int,
|
|
130
|
+
*,
|
|
131
|
+
id: Optional[str] = None,
|
|
132
|
+
) -> Checkpoint:
|
|
133
|
+
"""Create a checkpoint for the given channels."""
|
|
134
|
+
ts = datetime.now(timezone.utc).isoformat()
|
|
135
|
+
if channels is None:
|
|
136
|
+
values = checkpoint["channel_values"]
|
|
137
|
+
else:
|
|
138
|
+
values: dict[str, Any] = {}
|
|
139
|
+
for k, v in channels.items():
|
|
140
|
+
try:
|
|
141
|
+
values[k] = v.checkpoint()
|
|
142
|
+
except EmptyChannelError:
|
|
143
|
+
pass
|
|
144
|
+
return Checkpoint(
|
|
145
|
+
v=1,
|
|
146
|
+
ts=ts,
|
|
147
|
+
id=id or str(uuid6(clock_seq=step)),
|
|
148
|
+
channel_values=values,
|
|
149
|
+
channel_versions=checkpoint["channel_versions"],
|
|
150
|
+
versions_seen=checkpoint["versions_seen"],
|
|
151
|
+
pending_sends=checkpoint.get("pending_sends", []),
|
|
152
|
+
current_tasks={},
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class CheckpointTuple(NamedTuple):
|
|
157
|
+
"""A tuple containing a checkpoint and its associated data."""
|
|
158
|
+
|
|
159
|
+
config: RunnableConfig
|
|
160
|
+
checkpoint: Checkpoint
|
|
161
|
+
metadata: CheckpointMetadata
|
|
162
|
+
parent_config: Optional[RunnableConfig] = None
|
|
163
|
+
pending_writes: Optional[List[PendingWrite]] = None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
CheckpointThreadId = ConfigurableFieldSpec(
|
|
167
|
+
id="thread_id",
|
|
168
|
+
annotation=str,
|
|
169
|
+
name="Thread ID",
|
|
170
|
+
description=None,
|
|
171
|
+
default="",
|
|
172
|
+
is_shared=True,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
CheckpointNS = ConfigurableFieldSpec(
|
|
176
|
+
id="checkpoint_ns",
|
|
177
|
+
annotation=str,
|
|
178
|
+
name="Checkpoint NS",
|
|
179
|
+
description='Checkpoint namespace. Denotes the path to the subgraph node the checkpoint originates from, separated by `|` character, e.g. `"child|grandchild"`. Defaults to "" (root graph).',
|
|
180
|
+
default=None,
|
|
181
|
+
is_shared=True,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
CheckpointId = ConfigurableFieldSpec(
|
|
185
|
+
id="checkpoint_id",
|
|
186
|
+
annotation=Optional[str],
|
|
187
|
+
name="Checkpoint ID",
|
|
188
|
+
description="Pass to fetch a past checkpoint. If None, fetches the latest checkpoint.",
|
|
189
|
+
default=None,
|
|
190
|
+
is_shared=True,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class BaseCheckpointSaver(ABC):
|
|
195
|
+
"""Base class for creating a graph checkpointer.
|
|
196
|
+
|
|
197
|
+
Checkpointers allow LangGraph agents to persist their state
|
|
198
|
+
within and across multiple interactions.
|
|
199
|
+
|
|
200
|
+
Attributes:
|
|
201
|
+
serde (SerializerProtocol): Serializer for encoding/decoding checkpoints.
|
|
202
|
+
|
|
203
|
+
Note:
|
|
204
|
+
When creating a custom checkpoint saver, consider implementing async
|
|
205
|
+
versions to avoid blocking the main thread.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
serde: SerializerProtocol = JsonPlusSerializer()
|
|
209
|
+
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
*,
|
|
213
|
+
serde: Optional[SerializerProtocol] = None,
|
|
214
|
+
) -> None:
|
|
215
|
+
self.serde = maybe_add_typed_methods(serde or self.serde)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def config_specs(self) -> list[ConfigurableFieldSpec]:
|
|
219
|
+
"""Define the configuration options for the checkpoint saver.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
list[ConfigurableFieldSpec]: List of configuration field specs.
|
|
223
|
+
"""
|
|
224
|
+
return [CheckpointThreadId, CheckpointNS, CheckpointId]
|
|
225
|
+
|
|
226
|
+
def get(self, config: RunnableConfig) -> Optional[Checkpoint]:
|
|
227
|
+
"""Fetch a checkpoint using the given configuration.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
config (RunnableConfig): Configuration specifying which checkpoint to retrieve.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
Optional[Checkpoint]: The requested checkpoint, or None if not found.
|
|
234
|
+
"""
|
|
235
|
+
if value := self.get_tuple(config):
|
|
236
|
+
return value.checkpoint
|
|
237
|
+
|
|
238
|
+
def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
239
|
+
"""Fetch a checkpoint tuple using the given configuration.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
config (RunnableConfig): Configuration specifying which checkpoint to retrieve.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Optional[CheckpointTuple]: The requested checkpoint tuple, or None if not found.
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
249
|
+
"""
|
|
250
|
+
raise NotImplementedError
|
|
251
|
+
|
|
252
|
+
def list(
|
|
253
|
+
self,
|
|
254
|
+
config: Optional[RunnableConfig],
|
|
255
|
+
*,
|
|
256
|
+
filter: Optional[Dict[str, Any]] = None,
|
|
257
|
+
before: Optional[RunnableConfig] = None,
|
|
258
|
+
limit: Optional[int] = None,
|
|
259
|
+
) -> Iterator[CheckpointTuple]:
|
|
260
|
+
"""List checkpoints that match the given criteria.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
config (Optional[RunnableConfig]): Base configuration for filtering checkpoints.
|
|
264
|
+
filter (Optional[Dict[str, Any]]): Additional filtering criteria.
|
|
265
|
+
before (Optional[RunnableConfig]): List checkpoints created before this configuration.
|
|
266
|
+
limit (Optional[int]): Maximum number of checkpoints to return.
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
Iterator[CheckpointTuple]: Iterator of matching checkpoint tuples.
|
|
270
|
+
|
|
271
|
+
Raises:
|
|
272
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
273
|
+
"""
|
|
274
|
+
raise NotImplementedError
|
|
275
|
+
|
|
276
|
+
def put(
|
|
277
|
+
self,
|
|
278
|
+
config: RunnableConfig,
|
|
279
|
+
checkpoint: Checkpoint,
|
|
280
|
+
metadata: CheckpointMetadata,
|
|
281
|
+
) -> RunnableConfig:
|
|
282
|
+
"""Store a checkpoint with its configuration and metadata.
|
|
283
|
+
|
|
284
|
+
Args:
|
|
285
|
+
config (RunnableConfig): Configuration for the checkpoint.
|
|
286
|
+
checkpoint (Checkpoint): The checkpoint to store.
|
|
287
|
+
metadata (CheckpointMetadata): Additional metadata for the checkpoint.
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
RunnableConfig: Updated configuration after storing the checkpoint.
|
|
291
|
+
|
|
292
|
+
Raises:
|
|
293
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
294
|
+
"""
|
|
295
|
+
raise NotImplementedError
|
|
296
|
+
|
|
297
|
+
def put_writes(
|
|
298
|
+
self,
|
|
299
|
+
config: RunnableConfig,
|
|
300
|
+
writes: List[Tuple[str, Any]],
|
|
301
|
+
task_id: str,
|
|
302
|
+
) -> None:
|
|
303
|
+
"""Store intermediate writes linked to a checkpoint.
|
|
304
|
+
|
|
305
|
+
Args:
|
|
306
|
+
config (RunnableConfig): Configuration of the related checkpoint.
|
|
307
|
+
writes (List[Tuple[str, Any]]): List of writes to store.
|
|
308
|
+
task_id (str): Identifier for the task creating the writes.
|
|
309
|
+
|
|
310
|
+
Raises:
|
|
311
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
312
|
+
"""
|
|
313
|
+
raise NotImplementedError
|
|
314
|
+
|
|
315
|
+
async def aget(self, config: RunnableConfig) -> Optional[Checkpoint]:
|
|
316
|
+
"""Asynchronously fetch a checkpoint using the given configuration.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
config (RunnableConfig): Configuration specifying which checkpoint to retrieve.
|
|
320
|
+
|
|
321
|
+
Returns:
|
|
322
|
+
Optional[Checkpoint]: The requested checkpoint, or None if not found.
|
|
323
|
+
"""
|
|
324
|
+
if value := await self.aget_tuple(config):
|
|
325
|
+
return value.checkpoint
|
|
326
|
+
|
|
327
|
+
async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
|
|
328
|
+
"""Asynchronously fetch a checkpoint tuple using the given configuration.
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
config (RunnableConfig): Configuration specifying which checkpoint to retrieve.
|
|
332
|
+
|
|
333
|
+
Returns:
|
|
334
|
+
Optional[CheckpointTuple]: The requested checkpoint tuple, or None if not found.
|
|
335
|
+
|
|
336
|
+
Raises:
|
|
337
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
338
|
+
"""
|
|
339
|
+
raise NotImplementedError
|
|
340
|
+
|
|
341
|
+
async def alist(
|
|
342
|
+
self,
|
|
343
|
+
config: Optional[RunnableConfig],
|
|
344
|
+
*,
|
|
345
|
+
filter: Optional[Dict[str, Any]] = None,
|
|
346
|
+
before: Optional[RunnableConfig] = None,
|
|
347
|
+
limit: Optional[int] = None,
|
|
348
|
+
) -> AsyncIterator[CheckpointTuple]:
|
|
349
|
+
"""Asynchronously list checkpoints that match the given criteria.
|
|
350
|
+
|
|
351
|
+
Args:
|
|
352
|
+
config (Optional[RunnableConfig]): Base configuration for filtering checkpoints.
|
|
353
|
+
filter (Optional[Dict[str, Any]]): Additional filtering criteria for metadata.
|
|
354
|
+
before (Optional[RunnableConfig]): List checkpoints created before this configuration.
|
|
355
|
+
limit (Optional[int]): Maximum number of checkpoints to return.
|
|
356
|
+
|
|
357
|
+
Returns:
|
|
358
|
+
AsyncIterator[CheckpointTuple]: Async iterator of matching checkpoint tuples.
|
|
359
|
+
|
|
360
|
+
Raises:
|
|
361
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
362
|
+
"""
|
|
363
|
+
raise NotImplementedError
|
|
364
|
+
yield
|
|
365
|
+
|
|
366
|
+
async def aput(
|
|
367
|
+
self,
|
|
368
|
+
config: RunnableConfig,
|
|
369
|
+
checkpoint: Checkpoint,
|
|
370
|
+
metadata: CheckpointMetadata,
|
|
371
|
+
) -> RunnableConfig:
|
|
372
|
+
"""Asynchronously store a checkpoint with its configuration and metadata.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
config (RunnableConfig): Configuration for the checkpoint.
|
|
376
|
+
checkpoint (Checkpoint): The checkpoint to store.
|
|
377
|
+
metadata (CheckpointMetadata): Additional metadata for the checkpoint.
|
|
378
|
+
|
|
379
|
+
Returns:
|
|
380
|
+
RunnableConfig: Updated configuration after storing the checkpoint.
|
|
381
|
+
|
|
382
|
+
Raises:
|
|
383
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
384
|
+
"""
|
|
385
|
+
raise NotImplementedError
|
|
386
|
+
|
|
387
|
+
async def aput_writes(
|
|
388
|
+
self,
|
|
389
|
+
config: RunnableConfig,
|
|
390
|
+
writes: List[Tuple[str, Any]],
|
|
391
|
+
task_id: str,
|
|
392
|
+
) -> None:
|
|
393
|
+
"""Asynchronously store intermediate writes linked to a checkpoint.
|
|
394
|
+
|
|
395
|
+
Args:
|
|
396
|
+
config (RunnableConfig): Configuration of the related checkpoint.
|
|
397
|
+
writes (List[Tuple[str, Any]]): List of writes to store.
|
|
398
|
+
task_id (str): Identifier for the task creating the writes.
|
|
399
|
+
|
|
400
|
+
Raises:
|
|
401
|
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
|
402
|
+
"""
|
|
403
|
+
raise NotImplementedError
|
|
404
|
+
|
|
405
|
+
def get_next_version(self, current: Optional[V], channel: ChannelProtocol) -> V:
|
|
406
|
+
"""Generate the next version ID for a channel.
|
|
407
|
+
|
|
408
|
+
Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions,
|
|
409
|
+
as long as they are monotonically increasing.
|
|
410
|
+
|
|
411
|
+
Args:
|
|
412
|
+
current (Optional[V]): The current version identifier (int, float, or str).
|
|
413
|
+
channel (BaseChannel): The channel being versioned.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
V: The next version identifier, which must be increasing.
|
|
417
|
+
"""
|
|
418
|
+
return current + 1 if current is not None else 1
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
class EmptyChannelError(Exception):
|
|
422
|
+
"""Raised when attempting to get the value of a channel that hasn't been updated
|
|
423
|
+
for the first time yet."""
|
|
424
|
+
|
|
425
|
+
pass
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def get_checkpoint_id(config: RunnableConfig) -> Optional[str]:
|
|
429
|
+
"""Get checkpoint ID in a backwards-compatible manner (fallback on thread_ts)."""
|
|
430
|
+
return config["configurable"].get(
|
|
431
|
+
"checkpoint_id", config["configurable"].get("thread_ts")
|
|
432
|
+
)
|