Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_cache.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_config.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_constants.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_fields.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_future.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_queue.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_replay.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_retry.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_serde.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_typing.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__init__.py +48 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/py.typed +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__init__.py +73 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__init__.py +144 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__init__.py +120 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/any_value.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/base.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/binop.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/delta.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/last_value.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/topic.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__init__.py +860 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/id.py +109 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/py.typed +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__init__.py +704 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/py.typed +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__init__.py +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-311.pyc +0 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (343 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_cache.cpython-311.pyc
ADDED
|
Binary file (2.46 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_config.cpython-311.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_constants.cpython-311.pyc
ADDED
|
Binary file (3.97 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_fields.cpython-311.pyc
ADDED
|
Binary file (9.51 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_future.cpython-311.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_pydantic.cpython-311.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_queue.cpython-311.pyc
ADDED
|
Binary file (6.7 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_replay.cpython-311.pyc
ADDED
|
Binary file (4.14 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_retry.cpython-311.pyc
ADDED
|
Binary file (1.37 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_runnable.cpython-311.pyc
ADDED
|
Binary file (38.3 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_scratchpad.cpython-311.pyc
ADDED
|
Binary file (1.15 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_serde.cpython-311.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_timeout.cpython-311.pyc
ADDED
|
Binary file (1.42 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/_internal/__pycache__/_typing.cpython-311.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
from collections.abc import Mapping, Sequence
|
| 5 |
+
from typing import Generic, TypeVar
|
| 6 |
+
|
| 7 |
+
from langgraph.checkpoint.serde.base import SerializerProtocol
|
| 8 |
+
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
| 9 |
+
|
| 10 |
+
ValueT = TypeVar("ValueT")
|
| 11 |
+
Namespace = tuple[str, ...]
|
| 12 |
+
FullKey = tuple[Namespace, str]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BaseCache(ABC, Generic[ValueT]):
|
| 16 |
+
"""Base class for a cache."""
|
| 17 |
+
|
| 18 |
+
serde: SerializerProtocol = JsonPlusSerializer(pickle_fallback=False)
|
| 19 |
+
|
| 20 |
+
def __init__(self, *, serde: SerializerProtocol | None = None) -> None:
|
| 21 |
+
"""Initialize the cache with a serializer."""
|
| 22 |
+
self.serde = serde or self.serde
|
| 23 |
+
|
| 24 |
+
@abstractmethod
|
| 25 |
+
def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 26 |
+
"""Get the cached values for the given keys."""
|
| 27 |
+
|
| 28 |
+
@abstractmethod
|
| 29 |
+
async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 30 |
+
"""Asynchronously get the cached values for the given keys."""
|
| 31 |
+
|
| 32 |
+
@abstractmethod
|
| 33 |
+
def set(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 34 |
+
"""Set the cached values for the given keys and TTLs."""
|
| 35 |
+
|
| 36 |
+
@abstractmethod
|
| 37 |
+
async def aset(self, pairs: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 38 |
+
"""Asynchronously set the cached values for the given keys and TTLs."""
|
| 39 |
+
|
| 40 |
+
@abstractmethod
|
| 41 |
+
def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 42 |
+
"""Delete the cached values for the given namespaces.
|
| 43 |
+
If no namespaces are provided, clear all cached values."""
|
| 44 |
+
|
| 45 |
+
@abstractmethod
|
| 46 |
+
async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 47 |
+
"""Asynchronously delete the cached values for the given namespaces.
|
| 48 |
+
If no namespaces are provided, clear all cached values."""
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (3.3 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/base/py.typed
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import threading
|
| 5 |
+
from collections.abc import Mapping, Sequence
|
| 6 |
+
|
| 7 |
+
from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT
|
| 8 |
+
from langgraph.checkpoint.serde.base import SerializerProtocol
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class InMemoryCache(BaseCache[ValueT]):
|
| 12 |
+
def __init__(self, *, serde: SerializerProtocol | None = None):
|
| 13 |
+
super().__init__(serde=serde)
|
| 14 |
+
self._cache: dict[Namespace, dict[str, tuple[str, bytes, float | None]]] = {}
|
| 15 |
+
self._lock = threading.RLock()
|
| 16 |
+
|
| 17 |
+
def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 18 |
+
"""Get the cached values for the given keys."""
|
| 19 |
+
with self._lock:
|
| 20 |
+
if not keys:
|
| 21 |
+
return {}
|
| 22 |
+
now = datetime.datetime.now(datetime.timezone.utc).timestamp()
|
| 23 |
+
values: dict[FullKey, ValueT] = {}
|
| 24 |
+
for ns_tuple, key in keys:
|
| 25 |
+
ns = Namespace(ns_tuple)
|
| 26 |
+
if ns in self._cache and key in self._cache[ns]:
|
| 27 |
+
enc, val, expiry = self._cache[ns][key]
|
| 28 |
+
if expiry is None or now < expiry:
|
| 29 |
+
values[(ns, key)] = self.serde.loads_typed((enc, val))
|
| 30 |
+
else:
|
| 31 |
+
del self._cache[ns][key]
|
| 32 |
+
return values
|
| 33 |
+
|
| 34 |
+
async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 35 |
+
"""Asynchronously get the cached values for the given keys."""
|
| 36 |
+
return self.get(keys)
|
| 37 |
+
|
| 38 |
+
def set(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 39 |
+
"""Set the cached values for the given keys."""
|
| 40 |
+
with self._lock:
|
| 41 |
+
now = datetime.datetime.now(datetime.timezone.utc)
|
| 42 |
+
for (ns, key), (value, ttl) in keys.items():
|
| 43 |
+
if ttl is not None:
|
| 44 |
+
delta = datetime.timedelta(seconds=ttl)
|
| 45 |
+
expiry: float | None = (now + delta).timestamp()
|
| 46 |
+
else:
|
| 47 |
+
expiry = None
|
| 48 |
+
if ns not in self._cache:
|
| 49 |
+
self._cache[ns] = {}
|
| 50 |
+
self._cache[ns][key] = (
|
| 51 |
+
*self.serde.dumps_typed(value),
|
| 52 |
+
expiry,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
async def aset(self, keys: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 56 |
+
"""Asynchronously set the cached values for the given keys."""
|
| 57 |
+
self.set(keys)
|
| 58 |
+
|
| 59 |
+
def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 60 |
+
"""Delete the cached values for the given namespaces.
|
| 61 |
+
If no namespaces are provided, clear all cached values."""
|
| 62 |
+
with self._lock:
|
| 63 |
+
if namespaces is None:
|
| 64 |
+
self._cache.clear()
|
| 65 |
+
else:
|
| 66 |
+
for ns in namespaces:
|
| 67 |
+
if ns in self._cache:
|
| 68 |
+
del self._cache[ns]
|
| 69 |
+
|
| 70 |
+
async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 71 |
+
"""Asynchronously delete the cached values for the given namespaces.
|
| 72 |
+
If no namespaces are provided, clear all cached values."""
|
| 73 |
+
self.clear(namespaces)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/memory/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (5.4 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__init__.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Mapping, Sequence
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT
|
| 7 |
+
from langgraph.checkpoint.serde.base import SerializerProtocol
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RedisCache(BaseCache[ValueT]):
|
| 11 |
+
"""Redis-based cache implementation with TTL support."""
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
redis: Any,
|
| 16 |
+
*,
|
| 17 |
+
serde: SerializerProtocol | None = None,
|
| 18 |
+
prefix: str = "langgraph:cache:",
|
| 19 |
+
) -> None:
|
| 20 |
+
"""Initialize the cache with a Redis client.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
redis: Redis client instance (sync or async)
|
| 24 |
+
serde: Serializer to use for values
|
| 25 |
+
prefix: Key prefix for all cached values
|
| 26 |
+
"""
|
| 27 |
+
super().__init__(serde=serde)
|
| 28 |
+
self.redis = redis
|
| 29 |
+
self.prefix = prefix
|
| 30 |
+
|
| 31 |
+
def _make_key(self, ns: Namespace, key: str) -> str:
|
| 32 |
+
"""Create a Redis key from namespace and key."""
|
| 33 |
+
ns_str = ":".join(ns) if ns else ""
|
| 34 |
+
return f"{self.prefix}{ns_str}:{key}" if ns_str else f"{self.prefix}{key}"
|
| 35 |
+
|
| 36 |
+
def _parse_key(self, redis_key: str) -> tuple[Namespace, str]:
|
| 37 |
+
"""Parse a Redis key back to namespace and key."""
|
| 38 |
+
if not redis_key.startswith(self.prefix):
|
| 39 |
+
raise ValueError(
|
| 40 |
+
f"Key {redis_key} does not start with prefix {self.prefix}"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
remaining = redis_key[len(self.prefix) :]
|
| 44 |
+
if ":" in remaining:
|
| 45 |
+
parts = remaining.split(":")
|
| 46 |
+
key = parts[-1]
|
| 47 |
+
ns_parts = parts[:-1]
|
| 48 |
+
return (tuple(ns_parts), key)
|
| 49 |
+
else:
|
| 50 |
+
return (tuple(), remaining)
|
| 51 |
+
|
| 52 |
+
def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 53 |
+
"""Get the cached values for the given keys."""
|
| 54 |
+
if not keys:
|
| 55 |
+
return {}
|
| 56 |
+
|
| 57 |
+
# Build Redis keys
|
| 58 |
+
redis_keys = [self._make_key(ns, key) for ns, key in keys]
|
| 59 |
+
|
| 60 |
+
# Get values from Redis using MGET
|
| 61 |
+
try:
|
| 62 |
+
raw_values = self.redis.mget(redis_keys)
|
| 63 |
+
except Exception:
|
| 64 |
+
# If Redis is unavailable, return empty dict
|
| 65 |
+
return {}
|
| 66 |
+
|
| 67 |
+
values: dict[FullKey, ValueT] = {}
|
| 68 |
+
for i, raw_value in enumerate(raw_values):
|
| 69 |
+
if raw_value is not None:
|
| 70 |
+
try:
|
| 71 |
+
# Deserialize the value
|
| 72 |
+
encoding, data = raw_value.split(b":", 1)
|
| 73 |
+
values[keys[i]] = self.serde.loads_typed((encoding.decode(), data))
|
| 74 |
+
except Exception:
|
| 75 |
+
# Skip corrupted entries
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
return values
|
| 79 |
+
|
| 80 |
+
async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 81 |
+
"""Asynchronously get the cached values for the given keys."""
|
| 82 |
+
return self.get(keys)
|
| 83 |
+
|
| 84 |
+
def set(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 85 |
+
"""Set the cached values for the given keys and TTLs."""
|
| 86 |
+
if not mapping:
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
# Use pipeline for efficient batch operations
|
| 90 |
+
pipe = self.redis.pipeline()
|
| 91 |
+
|
| 92 |
+
for (ns, key), (value, ttl) in mapping.items():
|
| 93 |
+
redis_key = self._make_key(ns, key)
|
| 94 |
+
encoding, data = self.serde.dumps_typed(value)
|
| 95 |
+
|
| 96 |
+
# Store as "encoding:data" format
|
| 97 |
+
serialized_value = f"{encoding}:".encode() + data
|
| 98 |
+
|
| 99 |
+
if ttl is not None:
|
| 100 |
+
pipe.setex(redis_key, ttl, serialized_value)
|
| 101 |
+
else:
|
| 102 |
+
pipe.set(redis_key, serialized_value)
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
pipe.execute()
|
| 106 |
+
except Exception:
|
| 107 |
+
# Silently fail if Redis is unavailable
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
async def aset(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 111 |
+
"""Asynchronously set the cached values for the given keys and TTLs."""
|
| 112 |
+
self.set(mapping)
|
| 113 |
+
|
| 114 |
+
def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 115 |
+
"""Delete the cached values for the given namespaces.
|
| 116 |
+
If no namespaces are provided, clear all cached values."""
|
| 117 |
+
try:
|
| 118 |
+
if namespaces is None:
|
| 119 |
+
# Clear all keys with our prefix
|
| 120 |
+
pattern = f"{self.prefix}*"
|
| 121 |
+
keys = self.redis.keys(pattern)
|
| 122 |
+
if keys:
|
| 123 |
+
self.redis.delete(*keys)
|
| 124 |
+
else:
|
| 125 |
+
# Clear specific namespaces
|
| 126 |
+
keys_to_delete = []
|
| 127 |
+
for ns in namespaces:
|
| 128 |
+
ns_str = ":".join(ns) if ns else ""
|
| 129 |
+
pattern = (
|
| 130 |
+
f"{self.prefix}{ns_str}:*" if ns_str else f"{self.prefix}*"
|
| 131 |
+
)
|
| 132 |
+
keys = self.redis.keys(pattern)
|
| 133 |
+
keys_to_delete.extend(keys)
|
| 134 |
+
|
| 135 |
+
if keys_to_delete:
|
| 136 |
+
self.redis.delete(*keys_to_delete)
|
| 137 |
+
except Exception:
|
| 138 |
+
# Silently fail if Redis is unavailable
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 142 |
+
"""Asynchronously delete the cached values for the given namespaces.
|
| 143 |
+
If no namespaces are provided, clear all cached values."""
|
| 144 |
+
self.clear(namespaces)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/redis/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (7.54 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__init__.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import datetime
|
| 5 |
+
import sqlite3
|
| 6 |
+
import threading
|
| 7 |
+
from collections.abc import Mapping, Sequence
|
| 8 |
+
|
| 9 |
+
from langgraph.cache.base import BaseCache, FullKey, Namespace, ValueT
|
| 10 |
+
from langgraph.checkpoint.serde.base import SerializerProtocol
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SqliteCache(BaseCache[ValueT]):
|
| 14 |
+
"""File-based cache using SQLite."""
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
*,
|
| 19 |
+
path: str,
|
| 20 |
+
serde: SerializerProtocol | None = None,
|
| 21 |
+
) -> None:
|
| 22 |
+
"""Initialize the cache with a file path."""
|
| 23 |
+
super().__init__(serde=serde)
|
| 24 |
+
# SQLite backing store
|
| 25 |
+
self._conn = sqlite3.connect(
|
| 26 |
+
path,
|
| 27 |
+
check_same_thread=False,
|
| 28 |
+
)
|
| 29 |
+
# Serialize access to the shared connection across threads
|
| 30 |
+
self._lock = threading.RLock()
|
| 31 |
+
# Better concurrency & atomicity
|
| 32 |
+
self._conn.execute("PRAGMA journal_mode=WAL;")
|
| 33 |
+
# Schema: key -> (expiry, encoding, value)
|
| 34 |
+
self._conn.execute(
|
| 35 |
+
"""CREATE TABLE IF NOT EXISTS cache (
|
| 36 |
+
ns TEXT,
|
| 37 |
+
key TEXT,
|
| 38 |
+
expiry REAL,
|
| 39 |
+
encoding TEXT NOT NULL,
|
| 40 |
+
val BLOB NOT NULL,
|
| 41 |
+
PRIMARY KEY (ns, key)
|
| 42 |
+
)"""
|
| 43 |
+
)
|
| 44 |
+
self._conn.commit()
|
| 45 |
+
|
| 46 |
+
def get(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 47 |
+
"""Get the cached values for the given keys."""
|
| 48 |
+
with self._lock, self._conn:
|
| 49 |
+
now = datetime.datetime.now(datetime.timezone.utc).timestamp()
|
| 50 |
+
if not keys:
|
| 51 |
+
return {}
|
| 52 |
+
placeholders = ",".join("(?, ?)" for _ in keys)
|
| 53 |
+
params: list[str] = []
|
| 54 |
+
for ns_tuple, key in keys:
|
| 55 |
+
params.extend((",".join(ns_tuple), key))
|
| 56 |
+
cursor = self._conn.execute(
|
| 57 |
+
f"SELECT ns, key, expiry, encoding, val FROM cache WHERE (ns, key) IN ({placeholders})",
|
| 58 |
+
tuple(params),
|
| 59 |
+
)
|
| 60 |
+
values: dict[FullKey, ValueT] = {}
|
| 61 |
+
rows = cursor.fetchall()
|
| 62 |
+
for ns, key, expiry, encoding, raw in rows:
|
| 63 |
+
if expiry is not None and now > expiry:
|
| 64 |
+
# purge expired entry
|
| 65 |
+
self._conn.execute(
|
| 66 |
+
"DELETE FROM cache WHERE (ns, key) = (?, ?)", (ns, key)
|
| 67 |
+
)
|
| 68 |
+
continue
|
| 69 |
+
values[(tuple(ns.split(",")), key)] = self.serde.loads_typed(
|
| 70 |
+
(encoding, raw)
|
| 71 |
+
)
|
| 72 |
+
return values
|
| 73 |
+
|
| 74 |
+
async def aget(self, keys: Sequence[FullKey]) -> dict[FullKey, ValueT]:
|
| 75 |
+
"""Asynchronously get the cached values for the given keys."""
|
| 76 |
+
return await asyncio.to_thread(self.get, keys)
|
| 77 |
+
|
| 78 |
+
def set(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 79 |
+
"""Set the cached values for the given keys and TTLs."""
|
| 80 |
+
with self._lock, self._conn:
|
| 81 |
+
now = datetime.datetime.now(datetime.timezone.utc)
|
| 82 |
+
for key, (value, ttl) in mapping.items():
|
| 83 |
+
if ttl is not None:
|
| 84 |
+
delta = datetime.timedelta(seconds=ttl)
|
| 85 |
+
expiry: float | None = (now + delta).timestamp()
|
| 86 |
+
else:
|
| 87 |
+
expiry = None
|
| 88 |
+
encoding, raw = self.serde.dumps_typed(value)
|
| 89 |
+
self._conn.execute(
|
| 90 |
+
"INSERT OR REPLACE INTO cache (ns, key, expiry, encoding, val) VALUES (?, ?, ?, ?, ?)",
|
| 91 |
+
(",".join(key[0]), key[1], expiry, encoding, raw),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
async def aset(self, mapping: Mapping[FullKey, tuple[ValueT, int | None]]) -> None:
|
| 95 |
+
"""Asynchronously set the cached values for the given keys and TTLs."""
|
| 96 |
+
await asyncio.to_thread(self.set, mapping)
|
| 97 |
+
|
| 98 |
+
def clear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 99 |
+
"""Delete the cached values for the given namespaces.
|
| 100 |
+
If no namespaces are provided, clear all cached values."""
|
| 101 |
+
with self._lock, self._conn:
|
| 102 |
+
if namespaces is None:
|
| 103 |
+
self._conn.execute("DELETE FROM cache")
|
| 104 |
+
else:
|
| 105 |
+
placeholders = ",".join("?" for _ in namespaces)
|
| 106 |
+
self._conn.execute(
|
| 107 |
+
f"DELETE FROM cache WHERE (ns) IN ({placeholders})",
|
| 108 |
+
tuple(",".join(key) for key in namespaces),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
async def aclear(self, namespaces: Sequence[Namespace] | None = None) -> None:
|
| 112 |
+
"""Asynchronously delete the cached values for the given namespaces.
|
| 113 |
+
If no namespaces are provided, clear all cached values."""
|
| 114 |
+
await asyncio.to_thread(self.clear, namespaces)
|
| 115 |
+
|
| 116 |
+
def __del__(self) -> None:
|
| 117 |
+
try:
|
| 118 |
+
self._conn.close()
|
| 119 |
+
except Exception:
|
| 120 |
+
pass
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/cache/sqlite/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (9.09 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (1.12 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/any_value.cpython-311.pyc
ADDED
|
Binary file (4.11 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (5.7 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/binop.cpython-311.pyc
ADDED
|
Binary file (7.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/delta.cpython-311.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/ephemeral_value.cpython-311.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/last_value.cpython-311.pyc
ADDED
|
Binary file (8.13 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/named_barrier_value.cpython-311.pyc
ADDED
|
Binary file (9.5 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/topic.cpython-311.pyc
ADDED
|
Binary file (5.33 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/channels/__pycache__/untracked_value.cpython-311.pyc
ADDED
|
Binary file (4.52 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__init__.py
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import logging
|
| 5 |
+
from collections.abc import AsyncIterator, Collection, Iterator, Mapping, Sequence
|
| 6 |
+
from typing import (
|
| 7 |
+
Any,
|
| 8 |
+
Generic,
|
| 9 |
+
Literal,
|
| 10 |
+
NamedTuple,
|
| 11 |
+
TypedDict,
|
| 12 |
+
TypeVar,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from langchain_core.runnables import RunnableConfig
|
| 16 |
+
from typing_extensions import NotRequired
|
| 17 |
+
|
| 18 |
+
from langgraph.checkpoint.base.id import uuid6
|
| 19 |
+
from langgraph.checkpoint.serde.base import SerializerProtocol, maybe_add_typed_methods
|
| 20 |
+
from langgraph.checkpoint.serde.encrypted import EncryptedSerializer
|
| 21 |
+
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
| 22 |
+
from langgraph.checkpoint.serde.types import (
|
| 23 |
+
ERROR,
|
| 24 |
+
INTERRUPT,
|
| 25 |
+
RESUME,
|
| 26 |
+
SCHEDULED,
|
| 27 |
+
ChannelProtocol,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
V = TypeVar("V", int, float, str)
|
| 31 |
+
PendingWrite = tuple[str, str, Any]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Marked as total=False to allow for future expansion.
|
| 38 |
+
class CheckpointMetadata(TypedDict, total=False):
|
| 39 |
+
"""Metadata associated with a checkpoint."""
|
| 40 |
+
|
| 41 |
+
source: Literal["input", "loop", "update", "fork"]
|
| 42 |
+
"""The source of the checkpoint.
|
| 43 |
+
|
| 44 |
+
- `"input"`: The checkpoint was created from an input to invoke/stream/batch.
|
| 45 |
+
- `"loop"`: The checkpoint was created from inside the pregel loop.
|
| 46 |
+
- `"update"`: The checkpoint was created from a manual state update.
|
| 47 |
+
- `"fork"`: The checkpoint was created as a copy of another checkpoint.
|
| 48 |
+
"""
|
| 49 |
+
step: int
|
| 50 |
+
"""The step number of the checkpoint.
|
| 51 |
+
|
| 52 |
+
`-1` for the first `"input"` checkpoint.
|
| 53 |
+
`0` for the first `"loop"` checkpoint.
|
| 54 |
+
`...` for the `nth` checkpoint afterwards.
|
| 55 |
+
"""
|
| 56 |
+
parents: dict[str, str]
|
| 57 |
+
"""The IDs of the parent checkpoints.
|
| 58 |
+
|
| 59 |
+
Mapping from checkpoint namespace to checkpoint ID.
|
| 60 |
+
"""
|
| 61 |
+
run_id: str
|
| 62 |
+
"""The ID of the run that created this checkpoint."""
|
| 63 |
+
counters_since_delta_snapshot: dict[str, tuple[int, int]]
|
| 64 |
+
"""Per-channel counters since the last `_DeltaSnapshot` was written.
|
| 65 |
+
|
| 66 |
+
!!! warning "Beta"
|
| 67 |
+
|
| 68 |
+
This metadata field backs `DeltaChannel` (beta). The key name and
|
| 69 |
+
contents may change while the delta-channel design stabilizes.
|
| 70 |
+
|
| 71 |
+
Maps channel name -> `(updates, supersteps)`:
|
| 72 |
+
|
| 73 |
+
- index 0 (`updates`): number of supersteps that wrote to this channel
|
| 74 |
+
since its last snapshot blob.
|
| 75 |
+
- index 1 (`supersteps`): total supersteps elapsed since this channel's
|
| 76 |
+
last snapshot, regardless of whether the channel was written.
|
| 77 |
+
|
| 78 |
+
A snapshot fires when EITHER `updates >= ch.snapshot_frequency` OR
|
| 79 |
+
`supersteps >= DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` (system-wide bound,
|
| 80 |
+
default 5000, env `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`).
|
| 81 |
+
The supersteps bound prevents unbounded ancestor walks on threads where
|
| 82 |
+
a delta channel exists but is no longer being updated.
|
| 83 |
+
|
| 84 |
+
Absent on threads that don't use delta channels. Persisted as a
|
| 85 |
+
2-element list in JSON (no native tuple).
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
ChannelVersions = dict[str, str | int | float]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Checkpoint(TypedDict):
|
| 93 |
+
"""State snapshot at a given point in time."""
|
| 94 |
+
|
| 95 |
+
v: int
|
| 96 |
+
"""The version of the checkpoint format. Currently `1`."""
|
| 97 |
+
id: str
|
| 98 |
+
"""The ID of the checkpoint.
|
| 99 |
+
|
| 100 |
+
This is both unique and monotonically increasing, so can be used for sorting
|
| 101 |
+
checkpoints from first to last."""
|
| 102 |
+
ts: str
|
| 103 |
+
"""The timestamp of the checkpoint in ISO 8601 format."""
|
| 104 |
+
channel_values: dict[str, Any]
|
| 105 |
+
"""The values of the channels at the time of the checkpoint.
|
| 106 |
+
|
| 107 |
+
Mapping from channel name to deserialized channel snapshot value.
|
| 108 |
+
"""
|
| 109 |
+
channel_versions: ChannelVersions
|
| 110 |
+
"""The versions of the channels at the time of the checkpoint.
|
| 111 |
+
|
| 112 |
+
The keys are channel names and the values are monotonically increasing
|
| 113 |
+
version strings for each channel.
|
| 114 |
+
"""
|
| 115 |
+
versions_seen: dict[str, ChannelVersions]
|
| 116 |
+
"""Map from node ID to map from channel name to version seen.
|
| 117 |
+
|
| 118 |
+
This keeps track of the versions of the channels that each node has seen.
|
| 119 |
+
Used to determine which nodes to execute next.
|
| 120 |
+
"""
|
| 121 |
+
updated_channels: list[str] | None
|
| 122 |
+
"""The channels that were updated in this checkpoint.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def copy_checkpoint(checkpoint: Checkpoint) -> Checkpoint:
|
| 127 |
+
return Checkpoint(
|
| 128 |
+
v=checkpoint["v"],
|
| 129 |
+
ts=checkpoint["ts"],
|
| 130 |
+
id=checkpoint["id"],
|
| 131 |
+
channel_values=checkpoint["channel_values"].copy(),
|
| 132 |
+
channel_versions=checkpoint["channel_versions"].copy(),
|
| 133 |
+
versions_seen={k: v.copy() for k, v in checkpoint["versions_seen"].items()},
|
| 134 |
+
pending_sends=checkpoint.get("pending_sends", []).copy(),
|
| 135 |
+
updated_channels=checkpoint.get("updated_channels", None),
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class CheckpointTuple(NamedTuple):
|
| 140 |
+
"""A tuple containing a checkpoint and its associated data."""
|
| 141 |
+
|
| 142 |
+
config: RunnableConfig
|
| 143 |
+
checkpoint: Checkpoint
|
| 144 |
+
metadata: CheckpointMetadata
|
| 145 |
+
parent_config: RunnableConfig | None = None
|
| 146 |
+
pending_writes: list[PendingWrite] | None = None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class DeltaChannelHistory(TypedDict):
|
| 150 |
+
"""Per-channel result entry from `BaseCheckpointSaver.get_delta_channel_history`.
|
| 151 |
+
|
| 152 |
+
!!! warning "Beta"
|
| 153 |
+
|
| 154 |
+
Part of the `DeltaChannel` support surface; in beta. Field names and
|
| 155 |
+
semantics may change.
|
| 156 |
+
|
| 157 |
+
Storage-level view of what one channel contributed across the ancestor
|
| 158 |
+
chain of a target checkpoint:
|
| 159 |
+
|
| 160 |
+
* `writes` — on-path deltas oldest→newest as `PendingWrite` tuples.
|
| 161 |
+
Always present; possibly empty. Already filtered to one channel.
|
| 162 |
+
Writes stored at the target checkpoint itself are pending for the
|
| 163 |
+
next super-step and are excluded.
|
| 164 |
+
* `seed` — the stored value at the nearest ancestor whose
|
| 165 |
+
`channel_values[ch]` is populated. Omitted if the walk reached the
|
| 166 |
+
root without finding any stored value (consumer treats absence as
|
| 167 |
+
"start empty"). Typically a `_DeltaSnapshot` for delta channels with
|
| 168 |
+
finite snapshot frequency, or a plain value for threads migrated
|
| 169 |
+
from a pre-delta channel type.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
writes: list[PendingWrite]
|
| 173 |
+
seed: NotRequired[Any]
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class BaseCheckpointSaver(Generic[V]):
|
| 177 |
+
"""Base class for creating a graph checkpointer.
|
| 178 |
+
|
| 179 |
+
Checkpointers allow LangGraph agents to persist their state
|
| 180 |
+
within and across multiple interactions.
|
| 181 |
+
|
| 182 |
+
When a checkpointer is configured, you should pass a `thread_id` in the config when
|
| 183 |
+
invoking the graph:
|
| 184 |
+
|
| 185 |
+
```python
|
| 186 |
+
config = {"configurable": {"thread_id": "my-thread"}}
|
| 187 |
+
graph.invoke(inputs, config)
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
The `thread_id` is the primary key used to store and retrieve checkpoints. Without
|
| 191 |
+
it, the checkpointer cannot save state, resume from interrupts, or enable
|
| 192 |
+
time-travel debugging.
|
| 193 |
+
|
| 194 |
+
How you choose ``thread_id`` depends on your use case:
|
| 195 |
+
|
| 196 |
+
- **Single-shot workflows**: Use a unique ID (e.g., uuid4) for each run when
|
| 197 |
+
executions are independent.
|
| 198 |
+
- **Conversational memory**: Reuse the same `thread_id` across invocations
|
| 199 |
+
to accumulate state (e.g., chat history) within a conversation.
|
| 200 |
+
|
| 201 |
+
Attributes:
|
| 202 |
+
serde (SerializerProtocol): Serializer for encoding/decoding checkpoints.
|
| 203 |
+
|
| 204 |
+
Note:
|
| 205 |
+
When creating a custom checkpoint saver, consider implementing async
|
| 206 |
+
versions to avoid blocking the main thread.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
serde: SerializerProtocol = JsonPlusSerializer()
|
| 210 |
+
|
| 211 |
+
def __init__(
|
| 212 |
+
self,
|
| 213 |
+
*,
|
| 214 |
+
serde: SerializerProtocol | None = None,
|
| 215 |
+
) -> None:
|
| 216 |
+
self.serde = maybe_add_typed_methods(serde or self.serde)
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def config_specs(self) -> list:
|
| 220 |
+
"""Define the configuration options for the checkpoint saver.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
list: List of configuration field specs.
|
| 224 |
+
"""
|
| 225 |
+
return []
|
| 226 |
+
|
| 227 |
+
def get(self, config: RunnableConfig) -> Checkpoint | None:
|
| 228 |
+
"""Fetch a checkpoint using the given configuration.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
config: Configuration specifying which checkpoint to retrieve.
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
The requested checkpoint, or `None` if not found.
|
| 235 |
+
"""
|
| 236 |
+
if value := self.get_tuple(config):
|
| 237 |
+
return value.checkpoint
|
| 238 |
+
|
| 239 |
+
def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
| 240 |
+
"""Fetch a checkpoint tuple using the given configuration.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
config: Configuration specifying which checkpoint to retrieve.
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
The requested checkpoint tuple, or `None` if not found.
|
| 247 |
+
|
| 248 |
+
Raises:
|
| 249 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 250 |
+
"""
|
| 251 |
+
raise NotImplementedError
|
| 252 |
+
|
| 253 |
+
def list(
|
| 254 |
+
self,
|
| 255 |
+
config: RunnableConfig | None,
|
| 256 |
+
*,
|
| 257 |
+
filter: dict[str, Any] | None = None,
|
| 258 |
+
before: RunnableConfig | None = None,
|
| 259 |
+
limit: int | None = None,
|
| 260 |
+
) -> Iterator[CheckpointTuple]:
|
| 261 |
+
"""List checkpoints that match the given criteria.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
config: Base configuration for filtering checkpoints.
|
| 265 |
+
filter: Additional filtering criteria.
|
| 266 |
+
before: List checkpoints created before this configuration.
|
| 267 |
+
limit: Maximum number of checkpoints to return.
|
| 268 |
+
|
| 269 |
+
Returns:
|
| 270 |
+
Iterator of matching checkpoint tuples.
|
| 271 |
+
|
| 272 |
+
Raises:
|
| 273 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 274 |
+
"""
|
| 275 |
+
raise NotImplementedError
|
| 276 |
+
|
| 277 |
+
def put(
|
| 278 |
+
self,
|
| 279 |
+
config: RunnableConfig,
|
| 280 |
+
checkpoint: Checkpoint,
|
| 281 |
+
metadata: CheckpointMetadata,
|
| 282 |
+
new_versions: ChannelVersions,
|
| 283 |
+
) -> RunnableConfig:
|
| 284 |
+
"""Store a checkpoint with its configuration and metadata.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
config: Configuration for the checkpoint.
|
| 288 |
+
checkpoint: The checkpoint to store.
|
| 289 |
+
metadata: Additional metadata for the checkpoint.
|
| 290 |
+
new_versions: New channel versions as of this write.
|
| 291 |
+
|
| 292 |
+
Returns:
|
| 293 |
+
RunnableConfig: Updated configuration after storing the checkpoint.
|
| 294 |
+
|
| 295 |
+
Raises:
|
| 296 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 297 |
+
"""
|
| 298 |
+
raise NotImplementedError
|
| 299 |
+
|
| 300 |
+
def put_writes(
|
| 301 |
+
self,
|
| 302 |
+
config: RunnableConfig,
|
| 303 |
+
writes: Sequence[tuple[str, Any]],
|
| 304 |
+
task_id: str,
|
| 305 |
+
task_path: str = "",
|
| 306 |
+
) -> None:
|
| 307 |
+
"""Store intermediate writes linked to a checkpoint.
|
| 308 |
+
|
| 309 |
+
Args:
|
| 310 |
+
config: Configuration of the related checkpoint.
|
| 311 |
+
writes: List of writes to store.
|
| 312 |
+
task_id: Identifier for the task creating the writes.
|
| 313 |
+
task_path: Path of the task creating the writes.
|
| 314 |
+
|
| 315 |
+
Raises:
|
| 316 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 317 |
+
"""
|
| 318 |
+
raise NotImplementedError
|
| 319 |
+
|
| 320 |
+
def delete_thread(
|
| 321 |
+
self,
|
| 322 |
+
thread_id: str,
|
| 323 |
+
) -> None:
|
| 324 |
+
"""Delete all checkpoints and writes associated with a specific thread ID.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
thread_id: The thread ID whose checkpoints should be deleted.
|
| 328 |
+
"""
|
| 329 |
+
raise NotImplementedError
|
| 330 |
+
|
| 331 |
+
def delete_for_runs(
|
| 332 |
+
self,
|
| 333 |
+
run_ids: Sequence[str],
|
| 334 |
+
) -> None:
|
| 335 |
+
"""Delete all checkpoints and writes associated with the given run IDs.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
run_ids: The run IDs whose checkpoints should be deleted.
|
| 339 |
+
|
| 340 |
+
!!! warning "DeltaChannel"
|
| 341 |
+
|
| 342 |
+
Deleting a run that produced ancestor `checkpoint_writes` — or
|
| 343 |
+
the only `_DeltaSnapshot` blob — for a still-live thread will
|
| 344 |
+
break reconstruction of any `DeltaChannel` whose history
|
| 345 |
+
depended on those rows. See the `DeltaChannel` note on `prune`
|
| 346 |
+
for safe-recovery strategies.
|
| 347 |
+
"""
|
| 348 |
+
raise NotImplementedError
|
| 349 |
+
|
| 350 |
+
def copy_thread(
|
| 351 |
+
self,
|
| 352 |
+
source_thread_id: str,
|
| 353 |
+
target_thread_id: str,
|
| 354 |
+
) -> None:
|
| 355 |
+
"""Copy all checkpoints and writes from one thread to another.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
source_thread_id: The thread ID to copy from.
|
| 359 |
+
target_thread_id: The thread ID to copy to.
|
| 360 |
+
|
| 361 |
+
!!! warning "DeltaChannel"
|
| 362 |
+
|
| 363 |
+
Implementations must copy the **complete** parent chain (all
|
| 364 |
+
ancestor checkpoints and their `checkpoint_writes`) — copying
|
| 365 |
+
only the head checkpoint will leave the target thread with
|
| 366 |
+
`DeltaChannel` state that cannot be reconstructed (no path back
|
| 367 |
+
to a `_DeltaSnapshot` ancestor). Equivalently, the copy must
|
| 368 |
+
include enough ancestors that every `DeltaChannel`-backed key
|
| 369 |
+
has either a `_DeltaSnapshot` in `channel_values` somewhere in
|
| 370 |
+
the chain, or a complete write history back to the chain root.
|
| 371 |
+
"""
|
| 372 |
+
raise NotImplementedError
|
| 373 |
+
|
| 374 |
+
def prune(
|
| 375 |
+
self,
|
| 376 |
+
thread_ids: Sequence[str],
|
| 377 |
+
*,
|
| 378 |
+
strategy: str = "keep_latest",
|
| 379 |
+
) -> None:
|
| 380 |
+
"""Prune checkpoints for the given threads.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
thread_ids: The thread IDs to prune.
|
| 384 |
+
strategy: The pruning strategy. `"keep_latest"` retains only the most
|
| 385 |
+
recent checkpoint per namespace. `"delete"` removes all checkpoints.
|
| 386 |
+
|
| 387 |
+
!!! warning "DeltaChannel"
|
| 388 |
+
|
| 389 |
+
Custom implementations must be `DeltaChannel`-aware. `DeltaChannel`
|
| 390 |
+
stores only a sentinel in `channel_values` for non-snapshot steps;
|
| 391 |
+
reconstruction walks the parent chain via
|
| 392 |
+
`get_delta_channel_history`, accumulating rows from
|
| 393 |
+
`checkpoint_writes` until it reaches an ancestor whose
|
| 394 |
+
`channel_values` contains a `_DeltaSnapshot` blob (written every
|
| 395 |
+
`snapshot_frequency` updates).
|
| 396 |
+
|
| 397 |
+
A naive `"keep_latest"` that drops intermediate checkpoints and
|
| 398 |
+
their writes can sever that chain: the surviving "latest"
|
| 399 |
+
checkpoint is rarely a snapshot point itself, so its delta
|
| 400 |
+
channels would silently reconstruct as empty (no error raised —
|
| 401 |
+
`get_delta_channel_history` simply returns no `seed`). Safe
|
| 402 |
+
options when the graph uses `DeltaChannel`:
|
| 403 |
+
|
| 404 |
+
* Walk back from each kept checkpoint and preserve every
|
| 405 |
+
ancestor (plus its `checkpoint_writes`) up to the nearest one
|
| 406 |
+
whose `channel_values` already contains a `_DeltaSnapshot` for
|
| 407 |
+
every `DeltaChannel`-backed key.
|
| 408 |
+
* Force a fresh snapshot on the kept checkpoint before deleting
|
| 409 |
+
ancestors — rewrite `channel_values[k] = _DeltaSnapshot(value)`
|
| 410 |
+
for each delta channel `k` (resolving `value` via the existing
|
| 411 |
+
ancestor walk first), then prune.
|
| 412 |
+
* Skip pruning threads whose graph uses `DeltaChannel` until one
|
| 413 |
+
of the above is implemented.
|
| 414 |
+
"""
|
| 415 |
+
raise NotImplementedError
|
| 416 |
+
|
| 417 |
+
async def aget(self, config: RunnableConfig) -> Checkpoint | None:
|
| 418 |
+
"""Asynchronously fetch a checkpoint using the given configuration.
|
| 419 |
+
|
| 420 |
+
Args:
|
| 421 |
+
config: Configuration specifying which checkpoint to retrieve.
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
The requested checkpoint, or `None` if not found.
|
| 425 |
+
"""
|
| 426 |
+
if value := await self.aget_tuple(config):
|
| 427 |
+
return value.checkpoint
|
| 428 |
+
|
| 429 |
+
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
| 430 |
+
"""Asynchronously fetch a checkpoint tuple using the given configuration.
|
| 431 |
+
|
| 432 |
+
Args:
|
| 433 |
+
config: Configuration specifying which checkpoint to retrieve.
|
| 434 |
+
|
| 435 |
+
Returns:
|
| 436 |
+
The requested checkpoint tuple, or `None` if not found.
|
| 437 |
+
|
| 438 |
+
Raises:
|
| 439 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 440 |
+
"""
|
| 441 |
+
raise NotImplementedError
|
| 442 |
+
|
| 443 |
+
async def alist(
|
| 444 |
+
self,
|
| 445 |
+
config: RunnableConfig | None,
|
| 446 |
+
*,
|
| 447 |
+
filter: dict[str, Any] | None = None,
|
| 448 |
+
before: RunnableConfig | None = None,
|
| 449 |
+
limit: int | None = None,
|
| 450 |
+
) -> AsyncIterator[CheckpointTuple]:
|
| 451 |
+
"""Asynchronously list checkpoints that match the given criteria.
|
| 452 |
+
|
| 453 |
+
Args:
|
| 454 |
+
config: Base configuration for filtering checkpoints.
|
| 455 |
+
filter: Additional filtering criteria for metadata.
|
| 456 |
+
before: List checkpoints created before this configuration.
|
| 457 |
+
limit: Maximum number of checkpoints to return.
|
| 458 |
+
|
| 459 |
+
Returns:
|
| 460 |
+
Async iterator of matching checkpoint tuples.
|
| 461 |
+
|
| 462 |
+
Raises:
|
| 463 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 464 |
+
"""
|
| 465 |
+
raise NotImplementedError
|
| 466 |
+
yield
|
| 467 |
+
|
| 468 |
+
async def aput(
|
| 469 |
+
self,
|
| 470 |
+
config: RunnableConfig,
|
| 471 |
+
checkpoint: Checkpoint,
|
| 472 |
+
metadata: CheckpointMetadata,
|
| 473 |
+
new_versions: ChannelVersions,
|
| 474 |
+
) -> RunnableConfig:
|
| 475 |
+
"""Asynchronously store a checkpoint with its configuration and metadata.
|
| 476 |
+
|
| 477 |
+
Args:
|
| 478 |
+
config: Configuration for the checkpoint.
|
| 479 |
+
checkpoint: The checkpoint to store.
|
| 480 |
+
metadata: Additional metadata for the checkpoint.
|
| 481 |
+
new_versions: New channel versions as of this write.
|
| 482 |
+
|
| 483 |
+
Returns:
|
| 484 |
+
RunnableConfig: Updated configuration after storing the checkpoint.
|
| 485 |
+
|
| 486 |
+
Raises:
|
| 487 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 488 |
+
"""
|
| 489 |
+
raise NotImplementedError
|
| 490 |
+
|
| 491 |
+
async def aput_writes(
|
| 492 |
+
self,
|
| 493 |
+
config: RunnableConfig,
|
| 494 |
+
writes: Sequence[tuple[str, Any]],
|
| 495 |
+
task_id: str,
|
| 496 |
+
task_path: str = "",
|
| 497 |
+
) -> None:
|
| 498 |
+
"""Asynchronously store intermediate writes linked to a checkpoint.
|
| 499 |
+
|
| 500 |
+
Args:
|
| 501 |
+
config: Configuration of the related checkpoint.
|
| 502 |
+
writes: List of writes to store.
|
| 503 |
+
task_id: Identifier for the task creating the writes.
|
| 504 |
+
task_path: Path of the task creating the writes.
|
| 505 |
+
|
| 506 |
+
Raises:
|
| 507 |
+
NotImplementedError: Implement this method in your custom checkpoint saver.
|
| 508 |
+
"""
|
| 509 |
+
raise NotImplementedError
|
| 510 |
+
|
| 511 |
+
async def adelete_thread(
|
| 512 |
+
self,
|
| 513 |
+
thread_id: str,
|
| 514 |
+
) -> None:
|
| 515 |
+
"""Delete all checkpoints and writes associated with a specific thread ID.
|
| 516 |
+
|
| 517 |
+
Args:
|
| 518 |
+
thread_id: The thread ID whose checkpoints should be deleted.
|
| 519 |
+
"""
|
| 520 |
+
raise NotImplementedError
|
| 521 |
+
|
| 522 |
+
async def adelete_for_runs(
|
| 523 |
+
self,
|
| 524 |
+
run_ids: Sequence[str],
|
| 525 |
+
) -> None:
|
| 526 |
+
"""Asynchronously delete all checkpoints and writes for the given run IDs.
|
| 527 |
+
|
| 528 |
+
Args:
|
| 529 |
+
run_ids: The run IDs whose checkpoints should be deleted.
|
| 530 |
+
|
| 531 |
+
!!! warning "DeltaChannel"
|
| 532 |
+
|
| 533 |
+
See `delete_for_runs` — deleting rows a still-live thread's
|
| 534 |
+
`DeltaChannel` reconstruction depends on (writes between the
|
| 535 |
+
head and its nearest `_DeltaSnapshot` ancestor) will silently
|
| 536 |
+
corrupt that channel's state.
|
| 537 |
+
"""
|
| 538 |
+
raise NotImplementedError
|
| 539 |
+
|
| 540 |
+
async def acopy_thread(
|
| 541 |
+
self,
|
| 542 |
+
source_thread_id: str,
|
| 543 |
+
target_thread_id: str,
|
| 544 |
+
) -> None:
|
| 545 |
+
"""Asynchronously copy all checkpoints and writes from one thread to another.
|
| 546 |
+
|
| 547 |
+
Args:
|
| 548 |
+
source_thread_id: The thread ID to copy from.
|
| 549 |
+
target_thread_id: The thread ID to copy to.
|
| 550 |
+
|
| 551 |
+
!!! warning "DeltaChannel"
|
| 552 |
+
|
| 553 |
+
See `copy_thread` — the copy must carry the complete parent
|
| 554 |
+
chain (or at least back to a `_DeltaSnapshot` ancestor for every
|
| 555 |
+
`DeltaChannel`) so the target thread can reconstruct delta
|
| 556 |
+
state.
|
| 557 |
+
"""
|
| 558 |
+
raise NotImplementedError
|
| 559 |
+
|
| 560 |
+
async def aprune(
|
| 561 |
+
self,
|
| 562 |
+
thread_ids: Sequence[str],
|
| 563 |
+
*,
|
| 564 |
+
strategy: str = "keep_latest",
|
| 565 |
+
) -> None:
|
| 566 |
+
"""Asynchronously prune checkpoints for the given threads.
|
| 567 |
+
|
| 568 |
+
Args:
|
| 569 |
+
thread_ids: The thread IDs to prune.
|
| 570 |
+
strategy: The pruning strategy. `"keep_latest"` retains only the most
|
| 571 |
+
recent checkpoint per namespace. `"delete"` removes all checkpoints.
|
| 572 |
+
|
| 573 |
+
!!! warning "DeltaChannel"
|
| 574 |
+
|
| 575 |
+
See `prune` for the full `DeltaChannel` caveat. In short:
|
| 576 |
+
`"keep_latest"` must not drop ancestor checkpoints / writes that
|
| 577 |
+
sit between the kept checkpoint and the nearest `_DeltaSnapshot`
|
| 578 |
+
ancestor, or delta channels will silently reconstruct as empty.
|
| 579 |
+
"""
|
| 580 |
+
raise NotImplementedError
|
| 581 |
+
|
| 582 |
+
def get_delta_channel_history(
|
| 583 |
+
self, *, config: RunnableConfig, channels: Sequence[str]
|
| 584 |
+
) -> Mapping[str, DeltaChannelHistory]:
|
| 585 |
+
"""Walk the parent chain returning per-channel writes + seed.
|
| 586 |
+
|
| 587 |
+
!!! warning "Beta"
|
| 588 |
+
|
| 589 |
+
This method is part of the `DeltaChannel` support surface and is
|
| 590 |
+
in beta. The signature, return shape (`DeltaChannelHistory`), and
|
| 591 |
+
interaction with `_DeltaSnapshot` blobs may change. Override at
|
| 592 |
+
your own risk; the default implementation will continue to work
|
| 593 |
+
against the public `BaseCheckpointSaver` contract.
|
| 594 |
+
|
| 595 |
+
For each requested channel, walks ancestors of the checkpoint
|
| 596 |
+
identified by `config` (following `parent_config`) and accumulates
|
| 597 |
+
`pending_writes` for that channel. The walk terminates per-channel
|
| 598 |
+
at the nearest ancestor whose `channel_values[ch]` is populated;
|
| 599 |
+
that value is returned as `seed`. If the walk reaches the root
|
| 600 |
+
without finding a stored value, `seed` is omitted from that
|
| 601 |
+
channel's entry — the consumer treats the absence as "start
|
| 602 |
+
empty."
|
| 603 |
+
|
| 604 |
+
Walks the **parent chain** (not `list(before=...)`): for forked
|
| 605 |
+
threads, only on-path ancestors contribute.
|
| 606 |
+
|
| 607 |
+
The default implementation walks `get_tuple` + `parent_config`
|
| 608 |
+
once for all channels — each ancestor visited once, not once per
|
| 609 |
+
channel. Savers with direct storage access (`InMemorySaver`,
|
| 610 |
+
`PostgresSaver`) override for performance; the return contract is
|
| 611 |
+
fixed here.
|
| 612 |
+
|
| 613 |
+
Args:
|
| 614 |
+
config: Configuration identifying the target checkpoint.
|
| 615 |
+
channels: Channel names to walk for. Empty → empty mapping.
|
| 616 |
+
|
| 617 |
+
Returns:
|
| 618 |
+
Per-channel `DeltaChannelHistory` for every name in `channels`.
|
| 619 |
+
"""
|
| 620 |
+
if not channels:
|
| 621 |
+
return {}
|
| 622 |
+
collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
|
| 623 |
+
seed_by_ch: dict[str, Any] = {}
|
| 624 |
+
remaining: set[str] = set(channels)
|
| 625 |
+
target_tuple = self.get_tuple(config)
|
| 626 |
+
cursor_config: RunnableConfig | None = (
|
| 627 |
+
target_tuple.parent_config if target_tuple else None
|
| 628 |
+
)
|
| 629 |
+
while cursor_config is not None and remaining:
|
| 630 |
+
tup = self.get_tuple(cursor_config)
|
| 631 |
+
if tup is None:
|
| 632 |
+
break
|
| 633 |
+
if tup.pending_writes:
|
| 634 |
+
for write in reversed(tup.pending_writes):
|
| 635 |
+
ch = write[1]
|
| 636 |
+
if ch in remaining:
|
| 637 |
+
collected_by_ch[ch].append(write)
|
| 638 |
+
for ch in list(remaining):
|
| 639 |
+
if ch in tup.checkpoint["channel_values"]:
|
| 640 |
+
seed_by_ch[ch] = tup.checkpoint["channel_values"][ch]
|
| 641 |
+
remaining.discard(ch)
|
| 642 |
+
cursor_config = tup.parent_config
|
| 643 |
+
result: dict[str, DeltaChannelHistory] = {}
|
| 644 |
+
for ch in channels:
|
| 645 |
+
entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))}
|
| 646 |
+
if ch in seed_by_ch:
|
| 647 |
+
entry["seed"] = seed_by_ch[ch]
|
| 648 |
+
result[ch] = entry
|
| 649 |
+
return result
|
| 650 |
+
|
| 651 |
+
async def aget_delta_channel_history(
|
| 652 |
+
self, *, config: RunnableConfig, channels: Sequence[str]
|
| 653 |
+
) -> Mapping[str, DeltaChannelHistory]:
|
| 654 |
+
"""Async version of `get_delta_channel_history`.
|
| 655 |
+
|
| 656 |
+
!!! warning "Beta"
|
| 657 |
+
|
| 658 |
+
This method is part of the `DeltaChannel` support surface and is
|
| 659 |
+
in beta. See `get_delta_channel_history` for caveats.
|
| 660 |
+
"""
|
| 661 |
+
if not channels:
|
| 662 |
+
return {}
|
| 663 |
+
collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
|
| 664 |
+
seed_by_ch: dict[str, Any] = {}
|
| 665 |
+
remaining: set[str] = set(channels)
|
| 666 |
+
target_tuple = await self.aget_tuple(config)
|
| 667 |
+
cursor_config: RunnableConfig | None = (
|
| 668 |
+
target_tuple.parent_config if target_tuple else None
|
| 669 |
+
)
|
| 670 |
+
while cursor_config is not None and remaining:
|
| 671 |
+
tup = await self.aget_tuple(cursor_config)
|
| 672 |
+
if tup is None:
|
| 673 |
+
break
|
| 674 |
+
if tup.pending_writes:
|
| 675 |
+
for write in reversed(tup.pending_writes):
|
| 676 |
+
ch = write[1]
|
| 677 |
+
if ch in remaining:
|
| 678 |
+
collected_by_ch[ch].append(write)
|
| 679 |
+
for ch in list(remaining):
|
| 680 |
+
if ch in tup.checkpoint["channel_values"]:
|
| 681 |
+
seed_by_ch[ch] = tup.checkpoint["channel_values"][ch]
|
| 682 |
+
remaining.discard(ch)
|
| 683 |
+
cursor_config = tup.parent_config
|
| 684 |
+
result: dict[str, DeltaChannelHistory] = {}
|
| 685 |
+
for ch in channels:
|
| 686 |
+
entry: DeltaChannelHistory = {"writes": list(reversed(collected_by_ch[ch]))}
|
| 687 |
+
if ch in seed_by_ch:
|
| 688 |
+
entry["seed"] = seed_by_ch[ch]
|
| 689 |
+
result[ch] = entry
|
| 690 |
+
return result
|
| 691 |
+
|
| 692 |
+
def get_next_version(self, current: V | None, channel: None) -> V:
|
| 693 |
+
"""Generate the next version ID for a channel.
|
| 694 |
+
|
| 695 |
+
Default is to use integer versions, incrementing by `1`.
|
| 696 |
+
|
| 697 |
+
If you override, you can use `str`/`int`/`float` versions, as long as they are monotonically increasing.
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
current: The current version identifier (`int`, `float`, or `str`).
|
| 701 |
+
channel: Deprecated argument, kept for backwards compatibility.
|
| 702 |
+
|
| 703 |
+
Returns:
|
| 704 |
+
V: The next version identifier, which must be increasing.
|
| 705 |
+
"""
|
| 706 |
+
if isinstance(current, str):
|
| 707 |
+
raise NotImplementedError
|
| 708 |
+
elif current is None:
|
| 709 |
+
return 1
|
| 710 |
+
else:
|
| 711 |
+
return current + 1
|
| 712 |
+
|
| 713 |
+
def with_allowlist(
|
| 714 |
+
self, extra_allowlist: Collection[tuple[str, ...]]
|
| 715 |
+
) -> BaseCheckpointSaver[V]:
|
| 716 |
+
"""Return a shallow clone with a derived msgpack allowlist."""
|
| 717 |
+
serde = _with_msgpack_allowlist(self.serde, extra_allowlist)
|
| 718 |
+
if serde is self.serde:
|
| 719 |
+
return self
|
| 720 |
+
clone = copy.copy(self)
|
| 721 |
+
clone.serde = maybe_add_typed_methods(serde)
|
| 722 |
+
return clone
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _with_msgpack_allowlist(
|
| 726 |
+
serde: SerializerProtocol, extra_allowlist: Collection[tuple[str, ...]]
|
| 727 |
+
) -> SerializerProtocol:
|
| 728 |
+
if isinstance(serde, JsonPlusSerializer):
|
| 729 |
+
return serde.with_msgpack_allowlist(extra_allowlist)
|
| 730 |
+
if isinstance(serde, EncryptedSerializer):
|
| 731 |
+
inner = serde.serde
|
| 732 |
+
if isinstance(inner, JsonPlusSerializer):
|
| 733 |
+
updated_inner = inner.with_msgpack_allowlist(extra_allowlist)
|
| 734 |
+
if updated_inner is inner:
|
| 735 |
+
return serde
|
| 736 |
+
return EncryptedSerializer(serde.cipher, updated_inner)
|
| 737 |
+
logger.warning(
|
| 738 |
+
"Serializer %s does not support msgpack allowlist. "
|
| 739 |
+
"Strict msgpack deserialization will not be enforced.",
|
| 740 |
+
type(serde).__name__,
|
| 741 |
+
)
|
| 742 |
+
return serde
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
class EmptyChannelError(Exception):
|
| 746 |
+
"""Raised when attempting to get the value of a channel that hasn't been updated
|
| 747 |
+
for the first time yet."""
|
| 748 |
+
|
| 749 |
+
pass
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def get_checkpoint_id(config: RunnableConfig) -> str | None:
|
| 753 |
+
"""Get checkpoint ID."""
|
| 754 |
+
return config["configurable"].get("checkpoint_id")
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def get_checkpoint_metadata(
|
| 758 |
+
config: RunnableConfig, metadata: CheckpointMetadata
|
| 759 |
+
) -> CheckpointMetadata:
|
| 760 |
+
"""Get checkpoint metadata in a backwards-compatible manner."""
|
| 761 |
+
metadata = {
|
| 762 |
+
k: v.replace("\u0000", "") if isinstance(v, str) else v
|
| 763 |
+
for k, v in metadata.items()
|
| 764 |
+
}
|
| 765 |
+
for obj in (config.get("metadata"), config.get("configurable")):
|
| 766 |
+
if not obj:
|
| 767 |
+
continue
|
| 768 |
+
for key, v in obj.items():
|
| 769 |
+
if key in metadata or key in EXCLUDED_METADATA_KEYS or key.startswith("__"):
|
| 770 |
+
continue
|
| 771 |
+
elif isinstance(v, str):
|
| 772 |
+
metadata[key] = v.replace("\u0000", "")
|
| 773 |
+
elif isinstance(v, (int, bool, float)):
|
| 774 |
+
metadata[key] = v
|
| 775 |
+
return metadata
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
def get_serializable_checkpoint_metadata(
|
| 779 |
+
config: RunnableConfig, metadata: CheckpointMetadata
|
| 780 |
+
) -> CheckpointMetadata:
|
| 781 |
+
"""Get checkpoint metadata in a backwards-compatible manner."""
|
| 782 |
+
checkpoint_metadata = get_checkpoint_metadata(config, metadata)
|
| 783 |
+
if "writes" in checkpoint_metadata:
|
| 784 |
+
checkpoint_metadata.pop("writes")
|
| 785 |
+
return checkpoint_metadata
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
"""
|
| 789 |
+
Mapping from error type to error index.
|
| 790 |
+
Regular writes just map to their index in the list of writes being saved.
|
| 791 |
+
Special writes (e.g. errors) map to negative indices, to avoid those writes from
|
| 792 |
+
conflicting with regular writes.
|
| 793 |
+
Each Checkpointer implementation should use this mapping in put_writes.
|
| 794 |
+
"""
|
| 795 |
+
WRITES_IDX_MAP = {ERROR: -1, SCHEDULED: -2, INTERRUPT: -3, RESUME: -4}
|
| 796 |
+
|
| 797 |
+
EXCLUDED_METADATA_KEYS = {
|
| 798 |
+
"thread_id",
|
| 799 |
+
"checkpoint_id",
|
| 800 |
+
"checkpoint_ns",
|
| 801 |
+
"checkpoint_map",
|
| 802 |
+
"langgraph_step",
|
| 803 |
+
"langgraph_node",
|
| 804 |
+
"langgraph_triggers",
|
| 805 |
+
"langgraph_path",
|
| 806 |
+
"langgraph_checkpoint_ns",
|
| 807 |
+
}
|
| 808 |
+
|
| 809 |
+
# --- below are deprecated utilities used by past versions of LangGraph ---
|
| 810 |
+
|
| 811 |
+
LATEST_VERSION = 2
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def empty_checkpoint() -> Checkpoint:
|
| 815 |
+
from datetime import datetime, timezone
|
| 816 |
+
|
| 817 |
+
return Checkpoint(
|
| 818 |
+
v=LATEST_VERSION,
|
| 819 |
+
id=str(uuid6(clock_seq=-2)),
|
| 820 |
+
ts=datetime.now(timezone.utc).isoformat(),
|
| 821 |
+
channel_values={},
|
| 822 |
+
channel_versions={},
|
| 823 |
+
versions_seen={},
|
| 824 |
+
pending_sends=[],
|
| 825 |
+
updated_channels=None,
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def create_checkpoint(
|
| 830 |
+
checkpoint: Checkpoint,
|
| 831 |
+
channels: Mapping[str, ChannelProtocol] | None,
|
| 832 |
+
step: int,
|
| 833 |
+
*,
|
| 834 |
+
id: str | None = None,
|
| 835 |
+
) -> Checkpoint:
|
| 836 |
+
"""Create a checkpoint for the given channels."""
|
| 837 |
+
from datetime import datetime, timezone
|
| 838 |
+
|
| 839 |
+
ts = datetime.now(timezone.utc).isoformat()
|
| 840 |
+
if channels is None:
|
| 841 |
+
values = checkpoint["channel_values"]
|
| 842 |
+
else:
|
| 843 |
+
values = {}
|
| 844 |
+
for k, v in channels.items():
|
| 845 |
+
if k not in checkpoint["channel_versions"]:
|
| 846 |
+
continue
|
| 847 |
+
try:
|
| 848 |
+
values[k] = v.checkpoint()
|
| 849 |
+
except EmptyChannelError:
|
| 850 |
+
pass
|
| 851 |
+
return Checkpoint(
|
| 852 |
+
v=LATEST_VERSION,
|
| 853 |
+
ts=ts,
|
| 854 |
+
id=id or str(uuid6(clock_seq=step)),
|
| 855 |
+
channel_values=values,
|
| 856 |
+
channel_versions=checkpoint["channel_versions"],
|
| 857 |
+
versions_seen=checkpoint["versions_seen"],
|
| 858 |
+
pending_sends=checkpoint.get("pending_sends", []),
|
| 859 |
+
updated_channels=None,
|
| 860 |
+
)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (33.5 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/__pycache__/id.cpython-311.pyc
ADDED
|
Binary file (4.96 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/id.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adapted from
|
| 2 |
+
https://github.com/oittaa/uuid6-python/blob/main/src/uuid6/__init__.py#L95
|
| 3 |
+
Bundled in to avoid install issues with uuid6 package
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import random
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
|
| 12 |
+
_last_v6_timestamp = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class UUID(uuid.UUID):
|
| 16 |
+
r"""UUID draft version objects"""
|
| 17 |
+
|
| 18 |
+
__slots__ = ()
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
hex: str | None = None,
|
| 23 |
+
bytes: bytes | None = None,
|
| 24 |
+
bytes_le: bytes | None = None,
|
| 25 |
+
fields: tuple[int, int, int, int, int, int] | None = None,
|
| 26 |
+
int: int | None = None,
|
| 27 |
+
version: int | None = None,
|
| 28 |
+
*,
|
| 29 |
+
is_safe: uuid.SafeUUID = uuid.SafeUUID.unknown,
|
| 30 |
+
) -> None:
|
| 31 |
+
r"""Create a UUID."""
|
| 32 |
+
|
| 33 |
+
if int is None or [hex, bytes, bytes_le, fields].count(None) != 4:
|
| 34 |
+
return super().__init__(
|
| 35 |
+
hex=hex,
|
| 36 |
+
bytes=bytes,
|
| 37 |
+
bytes_le=bytes_le,
|
| 38 |
+
fields=fields,
|
| 39 |
+
int=int,
|
| 40 |
+
version=version,
|
| 41 |
+
is_safe=is_safe,
|
| 42 |
+
)
|
| 43 |
+
if not 0 <= int < 1 << 128:
|
| 44 |
+
raise ValueError("int is out of range (need a 128-bit value)")
|
| 45 |
+
if version is not None:
|
| 46 |
+
if not 6 <= version <= 8:
|
| 47 |
+
raise ValueError("illegal version number")
|
| 48 |
+
# Set the variant to RFC 4122.
|
| 49 |
+
int &= ~(0xC000 << 48)
|
| 50 |
+
int |= 0x8000 << 48
|
| 51 |
+
# Set the version number.
|
| 52 |
+
int &= ~(0xF000 << 64)
|
| 53 |
+
int |= version << 76
|
| 54 |
+
super().__init__(int=int, is_safe=is_safe)
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def subsec(self) -> int:
|
| 58 |
+
return ((self.int >> 64) & 0x0FFF) << 8 | ((self.int >> 54) & 0xFF)
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def time(self) -> int:
|
| 62 |
+
if self.version == 6:
|
| 63 |
+
return (
|
| 64 |
+
(self.time_low << 28)
|
| 65 |
+
| (self.time_mid << 12)
|
| 66 |
+
| (self.time_hi_version & 0x0FFF)
|
| 67 |
+
)
|
| 68 |
+
if self.version == 7:
|
| 69 |
+
return self.int >> 80
|
| 70 |
+
if self.version == 8:
|
| 71 |
+
return (self.int >> 80) * 10**6 + _subsec_decode(self.subsec)
|
| 72 |
+
return super().time
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _subsec_decode(value: int) -> int:
|
| 76 |
+
return -(-value * 10**6 // 2**20)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID:
|
| 80 |
+
r"""UUID version 6 is a field-compatible version of UUIDv1, reordered for
|
| 81 |
+
improved DB locality. It is expected that UUIDv6 will primarily be
|
| 82 |
+
used in contexts where there are existing v1 UUIDs. Systems that do
|
| 83 |
+
not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead.
|
| 84 |
+
|
| 85 |
+
If 'node' is not given, a random 48-bit number is chosen.
|
| 86 |
+
|
| 87 |
+
If 'clock_seq' is given, it is used as the sequence number;
|
| 88 |
+
otherwise a random 14-bit sequence number is chosen."""
|
| 89 |
+
|
| 90 |
+
global _last_v6_timestamp
|
| 91 |
+
|
| 92 |
+
nanoseconds = time.time_ns()
|
| 93 |
+
# 0x01b21dd213814000 is the number of 100-ns intervals between the
|
| 94 |
+
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
|
| 95 |
+
timestamp = nanoseconds // 100 + 0x01B21DD213814000
|
| 96 |
+
if _last_v6_timestamp is not None and timestamp <= _last_v6_timestamp:
|
| 97 |
+
timestamp = _last_v6_timestamp + 1
|
| 98 |
+
_last_v6_timestamp = timestamp
|
| 99 |
+
if clock_seq is None:
|
| 100 |
+
clock_seq = random.getrandbits(14) # instead of stable storage
|
| 101 |
+
if node is None:
|
| 102 |
+
node = random.getrandbits(48)
|
| 103 |
+
time_high_and_time_mid = (timestamp >> 12) & 0xFFFFFFFFFFFF
|
| 104 |
+
time_low_and_version = timestamp & 0x0FFF
|
| 105 |
+
uuid_int = time_high_and_time_mid << 80
|
| 106 |
+
uuid_int |= time_low_and_version << 64
|
| 107 |
+
uuid_int |= (clock_seq & 0x3FFF) << 48
|
| 108 |
+
uuid_int |= node & 0xFFFFFFFFFFFF
|
| 109 |
+
return UUID(int=uuid_int, version=6)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/base/py.typed
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__init__.py
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import pickle
|
| 6 |
+
import random
|
| 7 |
+
import shutil
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from collections.abc import AsyncIterator, Iterator, Mapping, Sequence
|
| 10 |
+
from contextlib import AbstractAsyncContextManager, AbstractContextManager, ExitStack
|
| 11 |
+
from types import TracebackType
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
from langchain_core.runnables import RunnableConfig
|
| 15 |
+
|
| 16 |
+
from langgraph.checkpoint.base import (
|
| 17 |
+
WRITES_IDX_MAP,
|
| 18 |
+
BaseCheckpointSaver,
|
| 19 |
+
ChannelVersions,
|
| 20 |
+
Checkpoint,
|
| 21 |
+
CheckpointMetadata,
|
| 22 |
+
CheckpointTuple,
|
| 23 |
+
DeltaChannelHistory,
|
| 24 |
+
PendingWrite,
|
| 25 |
+
SerializerProtocol,
|
| 26 |
+
get_checkpoint_id,
|
| 27 |
+
get_checkpoint_metadata,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InMemorySaver(
|
| 34 |
+
BaseCheckpointSaver[str], AbstractContextManager, AbstractAsyncContextManager
|
| 35 |
+
):
|
| 36 |
+
"""An in-memory checkpoint saver.
|
| 37 |
+
|
| 38 |
+
This checkpoint saver stores checkpoints in memory using a `defaultdict`.
|
| 39 |
+
|
| 40 |
+
Note:
|
| 41 |
+
Only use `InMemorySaver` for debugging or testing purposes.
|
| 42 |
+
For production use cases we recommend installing [langgraph-checkpoint-postgres](https://pypi.org/project/langgraph-checkpoint-postgres/) and using `PostgresSaver` / `AsyncPostgresSaver`.
|
| 43 |
+
|
| 44 |
+
If you are using LangSmith Deployment, no checkpointer needs to be specified. The correct managed checkpointer will be used automatically.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
serde: The serializer to use for serializing and deserializing checkpoints.
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
```python
|
| 51 |
+
import asyncio
|
| 52 |
+
|
| 53 |
+
from langgraph.checkpoint.memory import InMemorySaver
|
| 54 |
+
from langgraph.graph import StateGraph
|
| 55 |
+
|
| 56 |
+
builder = StateGraph(int)
|
| 57 |
+
builder.add_node("add_one", lambda x: x + 1)
|
| 58 |
+
builder.set_entry_point("add_one")
|
| 59 |
+
builder.set_finish_point("add_one")
|
| 60 |
+
|
| 61 |
+
memory = InMemorySaver()
|
| 62 |
+
graph = builder.compile(checkpointer=memory)
|
| 63 |
+
coro = graph.ainvoke(1, {"configurable": {"thread_id": "thread-1"}})
|
| 64 |
+
asyncio.run(coro) # Output: 2
|
| 65 |
+
```
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
# thread ID -> checkpoint NS -> checkpoint ID -> checkpoint mapping
|
| 69 |
+
storage: defaultdict[
|
| 70 |
+
str,
|
| 71 |
+
dict[str, dict[str, tuple[tuple[str, bytes], tuple[str, bytes], str | None]]],
|
| 72 |
+
]
|
| 73 |
+
# (thread ID, checkpoint NS, checkpoint ID) -> (task ID, write idx)
|
| 74 |
+
writes: defaultdict[
|
| 75 |
+
tuple[str, str, str],
|
| 76 |
+
dict[tuple[str, int], tuple[str, str, tuple[str, bytes], str]],
|
| 77 |
+
]
|
| 78 |
+
blobs: dict[
|
| 79 |
+
tuple[
|
| 80 |
+
str, str, str, str | int | float
|
| 81 |
+
], # thread id, checkpoint ns, channel, version
|
| 82 |
+
tuple[str, bytes],
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
*,
|
| 88 |
+
serde: SerializerProtocol | None = None,
|
| 89 |
+
factory: type[defaultdict] = defaultdict,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__(serde=serde)
|
| 92 |
+
self.storage = factory(lambda: defaultdict(dict))
|
| 93 |
+
self.writes = factory(dict)
|
| 94 |
+
self.blobs = factory()
|
| 95 |
+
self.stack = ExitStack()
|
| 96 |
+
if factory is not defaultdict:
|
| 97 |
+
self.stack.enter_context(self.storage) # type: ignore[arg-type]
|
| 98 |
+
self.stack.enter_context(self.writes) # type: ignore[arg-type]
|
| 99 |
+
self.stack.enter_context(self.blobs) # type: ignore[arg-type]
|
| 100 |
+
|
| 101 |
+
def __enter__(self) -> InMemorySaver:
|
| 102 |
+
self.stack.__enter__()
|
| 103 |
+
return self
|
| 104 |
+
|
| 105 |
+
def __exit__(
|
| 106 |
+
self,
|
| 107 |
+
exc_type: type[BaseException] | None,
|
| 108 |
+
exc_value: BaseException | None,
|
| 109 |
+
traceback: TracebackType | None,
|
| 110 |
+
) -> bool | None:
|
| 111 |
+
return self.stack.__exit__(exc_type, exc_value, traceback)
|
| 112 |
+
|
| 113 |
+
async def __aenter__(self) -> InMemorySaver:
|
| 114 |
+
self.stack.__enter__()
|
| 115 |
+
return self
|
| 116 |
+
|
| 117 |
+
async def __aexit__(
|
| 118 |
+
self,
|
| 119 |
+
__exc_type: type[BaseException] | None,
|
| 120 |
+
__exc_value: BaseException | None,
|
| 121 |
+
__traceback: TracebackType | None,
|
| 122 |
+
) -> bool | None:
|
| 123 |
+
return self.stack.__exit__(__exc_type, __exc_value, __traceback)
|
| 124 |
+
|
| 125 |
+
def _load_blobs(
|
| 126 |
+
self,
|
| 127 |
+
thread_id: str,
|
| 128 |
+
checkpoint_ns: str,
|
| 129 |
+
versions: ChannelVersions,
|
| 130 |
+
) -> dict[str, Any]:
|
| 131 |
+
result: dict[str, Any] = {}
|
| 132 |
+
for k, ver in versions.items():
|
| 133 |
+
kk = (thread_id, checkpoint_ns, k, ver)
|
| 134 |
+
if kk not in self.blobs:
|
| 135 |
+
continue
|
| 136 |
+
vv = self.blobs[kk]
|
| 137 |
+
if vv[0] == "empty":
|
| 138 |
+
continue
|
| 139 |
+
result[k] = self.serde.loads_typed(vv)
|
| 140 |
+
return result
|
| 141 |
+
|
| 142 |
+
def get_delta_channel_history(
|
| 143 |
+
self, *, config: RunnableConfig, channels: Sequence[str]
|
| 144 |
+
) -> Mapping[str, DeltaChannelHistory]:
|
| 145 |
+
"""Override: walk the parent chain ONCE for all requested channels.
|
| 146 |
+
|
| 147 |
+
Each channel terminates independently at the nearest ancestor
|
| 148 |
+
whose stored blob is non-empty. Other channels keep walking until
|
| 149 |
+
they find their own terminator or hit the root.
|
| 150 |
+
|
| 151 |
+
Pre-delta plain-value blobs subsume their ancestor's pending
|
| 152 |
+
writes (the value already includes them); `_DeltaSnapshot` blobs
|
| 153 |
+
do not (snapshot is the value AT that ancestor, prior to its own
|
| 154 |
+
pending writes that produce the child).
|
| 155 |
+
"""
|
| 156 |
+
if not channels:
|
| 157 |
+
return {}
|
| 158 |
+
# Imported lazily to avoid a hard checkpoint→serde-types coupling at
|
| 159 |
+
# module import; only this override needs the runtime check.
|
| 160 |
+
from langgraph.checkpoint.serde.types import _DeltaSnapshot
|
| 161 |
+
|
| 162 |
+
thread_id = config["configurable"]["thread_id"]
|
| 163 |
+
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
|
| 164 |
+
checkpoint_id = config["configurable"].get("checkpoint_id", "")
|
| 165 |
+
ns_storage = self.storage.get(thread_id, {}).get(checkpoint_ns, {})
|
| 166 |
+
|
| 167 |
+
chain: list[str] = []
|
| 168 |
+
target_entry = ns_storage.get(checkpoint_id)
|
| 169 |
+
current: str | None = target_entry[2] if target_entry is not None else None
|
| 170 |
+
while current is not None:
|
| 171 |
+
entry = ns_storage.get(current)
|
| 172 |
+
if entry is None:
|
| 173 |
+
break
|
| 174 |
+
chain.append(current)
|
| 175 |
+
_, _, parent = entry
|
| 176 |
+
current = parent
|
| 177 |
+
|
| 178 |
+
collected_by_ch: dict[str, list[PendingWrite]] = {c: [] for c in channels}
|
| 179 |
+
seed_by_ch: dict[str, Any] = {}
|
| 180 |
+
remaining: set[str] = set(channels)
|
| 181 |
+
|
| 182 |
+
for cp_id in chain:
|
| 183 |
+
if not remaining:
|
| 184 |
+
break
|
| 185 |
+
entry = ns_storage.get(cp_id)
|
| 186 |
+
ckpt = self.serde.loads_typed(entry[0]) if entry is not None else None
|
| 187 |
+
|
| 188 |
+
terminated_here: set[str] = set()
|
| 189 |
+
blob_value_by_ch: dict[str, Any] = {}
|
| 190 |
+
if ckpt is not None:
|
| 191 |
+
versions = ckpt.get("channel_versions", {})
|
| 192 |
+
for ch in remaining:
|
| 193 |
+
ver = versions.get(ch)
|
| 194 |
+
if ver is None:
|
| 195 |
+
continue
|
| 196 |
+
blob_entry = self.blobs.get((thread_id, checkpoint_ns, ch, ver))
|
| 197 |
+
if blob_entry is None or blob_entry[0] == "empty":
|
| 198 |
+
continue
|
| 199 |
+
blob_value_by_ch[ch] = self.serde.loads_typed(blob_entry)
|
| 200 |
+
terminated_here.add(ch)
|
| 201 |
+
|
| 202 |
+
step_writes = self.writes.get((thread_id, checkpoint_ns, cp_id), {})
|
| 203 |
+
for (_task_id, _idx), (tid, ch, serialized, _) in sorted(
|
| 204 |
+
step_writes.items(), reverse=True
|
| 205 |
+
):
|
| 206 |
+
if ch not in remaining:
|
| 207 |
+
continue
|
| 208 |
+
blob_value = blob_value_by_ch.get(ch)
|
| 209 |
+
if blob_value is not None and not isinstance(
|
| 210 |
+
blob_value, _DeltaSnapshot
|
| 211 |
+
):
|
| 212 |
+
continue
|
| 213 |
+
collected_by_ch[ch].append(
|
| 214 |
+
(tid, ch, self.serde.loads_typed(serialized))
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
for ch in terminated_here:
|
| 218 |
+
seed_by_ch[ch] = blob_value_by_ch[ch]
|
| 219 |
+
remaining.discard(ch)
|
| 220 |
+
|
| 221 |
+
result: dict[str, DeltaChannelHistory] = {}
|
| 222 |
+
for ch in channels:
|
| 223 |
+
entry_h: DeltaChannelHistory = {
|
| 224 |
+
"writes": list(reversed(collected_by_ch[ch]))
|
| 225 |
+
}
|
| 226 |
+
if ch in seed_by_ch:
|
| 227 |
+
entry_h["seed"] = seed_by_ch[ch]
|
| 228 |
+
result[ch] = entry_h
|
| 229 |
+
return result
|
| 230 |
+
|
| 231 |
+
async def aget_delta_channel_history(
|
| 232 |
+
self, *, config: RunnableConfig, channels: Sequence[str]
|
| 233 |
+
) -> Mapping[str, DeltaChannelHistory]:
|
| 234 |
+
return self.get_delta_channel_history(config=config, channels=channels)
|
| 235 |
+
|
| 236 |
+
def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
| 237 |
+
"""Get a checkpoint tuple from the in-memory storage.
|
| 238 |
+
|
| 239 |
+
This method retrieves a checkpoint tuple from the in-memory storage based on the
|
| 240 |
+
provided config. If the config contains a `checkpoint_id` key, the checkpoint with
|
| 241 |
+
the matching thread ID and timestamp is retrieved. Otherwise, the latest checkpoint
|
| 242 |
+
for the given thread ID is retrieved.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
config: The config to use for retrieving the checkpoint.
|
| 246 |
+
|
| 247 |
+
Returns:
|
| 248 |
+
The retrieved checkpoint tuple, or None if no matching checkpoint was found.
|
| 249 |
+
"""
|
| 250 |
+
thread_id: str = config["configurable"]["thread_id"]
|
| 251 |
+
checkpoint_ns: str = config["configurable"].get("checkpoint_ns", "")
|
| 252 |
+
if checkpoint_id := get_checkpoint_id(config):
|
| 253 |
+
if saved := self.storage[thread_id][checkpoint_ns].get(checkpoint_id):
|
| 254 |
+
checkpoint, metadata, parent_checkpoint_id = saved
|
| 255 |
+
writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values()
|
| 256 |
+
checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint)
|
| 257 |
+
return CheckpointTuple(
|
| 258 |
+
config=config,
|
| 259 |
+
checkpoint={
|
| 260 |
+
**checkpoint_,
|
| 261 |
+
"channel_values": self._load_blobs(
|
| 262 |
+
thread_id, checkpoint_ns, checkpoint_["channel_versions"]
|
| 263 |
+
),
|
| 264 |
+
},
|
| 265 |
+
metadata=self.serde.loads_typed(metadata),
|
| 266 |
+
pending_writes=[
|
| 267 |
+
(id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
|
| 268 |
+
],
|
| 269 |
+
parent_config=(
|
| 270 |
+
{
|
| 271 |
+
"configurable": {
|
| 272 |
+
"thread_id": thread_id,
|
| 273 |
+
"checkpoint_ns": checkpoint_ns,
|
| 274 |
+
"checkpoint_id": parent_checkpoint_id,
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
if parent_checkpoint_id
|
| 278 |
+
else None
|
| 279 |
+
),
|
| 280 |
+
)
|
| 281 |
+
else:
|
| 282 |
+
if checkpoints := self.storage[thread_id][checkpoint_ns]:
|
| 283 |
+
checkpoint_id = max(checkpoints.keys())
|
| 284 |
+
checkpoint, metadata, parent_checkpoint_id = checkpoints[checkpoint_id]
|
| 285 |
+
writes = self.writes[(thread_id, checkpoint_ns, checkpoint_id)].values()
|
| 286 |
+
checkpoint_ = self.serde.loads_typed(checkpoint)
|
| 287 |
+
return CheckpointTuple(
|
| 288 |
+
config={
|
| 289 |
+
"configurable": {
|
| 290 |
+
"thread_id": thread_id,
|
| 291 |
+
"checkpoint_ns": checkpoint_ns,
|
| 292 |
+
"checkpoint_id": checkpoint_id,
|
| 293 |
+
}
|
| 294 |
+
},
|
| 295 |
+
checkpoint={
|
| 296 |
+
**checkpoint_,
|
| 297 |
+
"channel_values": self._load_blobs(
|
| 298 |
+
thread_id, checkpoint_ns, checkpoint_["channel_versions"]
|
| 299 |
+
),
|
| 300 |
+
},
|
| 301 |
+
metadata=self.serde.loads_typed(metadata),
|
| 302 |
+
pending_writes=[
|
| 303 |
+
(id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
|
| 304 |
+
],
|
| 305 |
+
parent_config=(
|
| 306 |
+
{
|
| 307 |
+
"configurable": {
|
| 308 |
+
"thread_id": thread_id,
|
| 309 |
+
"checkpoint_ns": checkpoint_ns,
|
| 310 |
+
"checkpoint_id": parent_checkpoint_id,
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
if parent_checkpoint_id
|
| 314 |
+
else None
|
| 315 |
+
),
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
def list(
|
| 319 |
+
self,
|
| 320 |
+
config: RunnableConfig | None,
|
| 321 |
+
*,
|
| 322 |
+
filter: dict[str, Any] | None = None,
|
| 323 |
+
before: RunnableConfig | None = None,
|
| 324 |
+
limit: int | None = None,
|
| 325 |
+
) -> Iterator[CheckpointTuple]:
|
| 326 |
+
"""List checkpoints from the in-memory storage.
|
| 327 |
+
|
| 328 |
+
This method retrieves a list of checkpoint tuples from the in-memory storage based
|
| 329 |
+
on the provided criteria.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
config: Base configuration for filtering checkpoints.
|
| 333 |
+
filter: Additional filtering criteria for metadata.
|
| 334 |
+
before: List checkpoints created before this configuration.
|
| 335 |
+
limit: Maximum number of checkpoints to return.
|
| 336 |
+
|
| 337 |
+
Yields:
|
| 338 |
+
An iterator of matching checkpoint tuples.
|
| 339 |
+
"""
|
| 340 |
+
thread_ids = (config["configurable"]["thread_id"],) if config else self.storage
|
| 341 |
+
config_checkpoint_ns = (
|
| 342 |
+
config["configurable"].get("checkpoint_ns") if config else None
|
| 343 |
+
)
|
| 344 |
+
config_checkpoint_id = get_checkpoint_id(config) if config else None
|
| 345 |
+
for thread_id in thread_ids:
|
| 346 |
+
for checkpoint_ns in self.storage[thread_id].keys():
|
| 347 |
+
if (
|
| 348 |
+
config_checkpoint_ns is not None
|
| 349 |
+
and checkpoint_ns != config_checkpoint_ns
|
| 350 |
+
):
|
| 351 |
+
continue
|
| 352 |
+
|
| 353 |
+
for checkpoint_id, (
|
| 354 |
+
checkpoint,
|
| 355 |
+
metadata_b,
|
| 356 |
+
parent_checkpoint_id,
|
| 357 |
+
) in sorted(
|
| 358 |
+
self.storage[thread_id][checkpoint_ns].items(),
|
| 359 |
+
key=lambda x: x[0],
|
| 360 |
+
reverse=True,
|
| 361 |
+
):
|
| 362 |
+
# filter by checkpoint ID from config
|
| 363 |
+
if config_checkpoint_id and checkpoint_id != config_checkpoint_id:
|
| 364 |
+
continue
|
| 365 |
+
|
| 366 |
+
# filter by checkpoint ID from `before` config
|
| 367 |
+
if (
|
| 368 |
+
before
|
| 369 |
+
and (before_checkpoint_id := get_checkpoint_id(before))
|
| 370 |
+
and checkpoint_id >= before_checkpoint_id
|
| 371 |
+
):
|
| 372 |
+
continue
|
| 373 |
+
|
| 374 |
+
# filter by metadata
|
| 375 |
+
metadata = self.serde.loads_typed(metadata_b)
|
| 376 |
+
if filter and not all(
|
| 377 |
+
query_value == metadata.get(query_key)
|
| 378 |
+
for query_key, query_value in filter.items()
|
| 379 |
+
):
|
| 380 |
+
continue
|
| 381 |
+
|
| 382 |
+
# limit search results
|
| 383 |
+
if limit is not None and limit <= 0:
|
| 384 |
+
break
|
| 385 |
+
elif limit is not None:
|
| 386 |
+
limit -= 1
|
| 387 |
+
|
| 388 |
+
writes = self.writes[
|
| 389 |
+
(thread_id, checkpoint_ns, checkpoint_id)
|
| 390 |
+
].values()
|
| 391 |
+
|
| 392 |
+
checkpoint_: Checkpoint = self.serde.loads_typed(checkpoint)
|
| 393 |
+
|
| 394 |
+
yield CheckpointTuple(
|
| 395 |
+
config={
|
| 396 |
+
"configurable": {
|
| 397 |
+
"thread_id": thread_id,
|
| 398 |
+
"checkpoint_ns": checkpoint_ns,
|
| 399 |
+
"checkpoint_id": checkpoint_id,
|
| 400 |
+
}
|
| 401 |
+
},
|
| 402 |
+
checkpoint={
|
| 403 |
+
**checkpoint_,
|
| 404 |
+
"channel_values": self._load_blobs(
|
| 405 |
+
thread_id,
|
| 406 |
+
checkpoint_ns,
|
| 407 |
+
checkpoint_["channel_versions"],
|
| 408 |
+
),
|
| 409 |
+
},
|
| 410 |
+
metadata=metadata,
|
| 411 |
+
parent_config=(
|
| 412 |
+
{
|
| 413 |
+
"configurable": {
|
| 414 |
+
"thread_id": thread_id,
|
| 415 |
+
"checkpoint_ns": checkpoint_ns,
|
| 416 |
+
"checkpoint_id": parent_checkpoint_id,
|
| 417 |
+
}
|
| 418 |
+
}
|
| 419 |
+
if parent_checkpoint_id
|
| 420 |
+
else None
|
| 421 |
+
),
|
| 422 |
+
pending_writes=[
|
| 423 |
+
(id, c, self.serde.loads_typed(v)) for id, c, v, _ in writes
|
| 424 |
+
],
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
def put(
|
| 428 |
+
self,
|
| 429 |
+
config: RunnableConfig,
|
| 430 |
+
checkpoint: Checkpoint,
|
| 431 |
+
metadata: CheckpointMetadata,
|
| 432 |
+
new_versions: ChannelVersions,
|
| 433 |
+
) -> RunnableConfig:
|
| 434 |
+
"""Save a checkpoint to the in-memory storage.
|
| 435 |
+
|
| 436 |
+
This method saves a checkpoint to the in-memory storage. The checkpoint is associated
|
| 437 |
+
with the provided config.
|
| 438 |
+
|
| 439 |
+
Args:
|
| 440 |
+
config: The config to associate with the checkpoint.
|
| 441 |
+
checkpoint: The checkpoint to save.
|
| 442 |
+
metadata: Additional metadata to save with the checkpoint.
|
| 443 |
+
new_versions: New versions as of this write
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
RunnableConfig: The updated config containing the saved checkpoint's timestamp.
|
| 447 |
+
"""
|
| 448 |
+
c = checkpoint.copy()
|
| 449 |
+
thread_id = config["configurable"]["thread_id"]
|
| 450 |
+
checkpoint_ns = config["configurable"]["checkpoint_ns"]
|
| 451 |
+
values: dict[str, Any] = c.pop("channel_values") # type: ignore[misc]
|
| 452 |
+
for k, v in new_versions.items():
|
| 453 |
+
self.blobs[(thread_id, checkpoint_ns, k, v)] = (
|
| 454 |
+
self.serde.dumps_typed(values[k]) if k in values else ("empty", b"")
|
| 455 |
+
)
|
| 456 |
+
self.storage[thread_id][checkpoint_ns].update(
|
| 457 |
+
{
|
| 458 |
+
checkpoint["id"]: (
|
| 459 |
+
self.serde.dumps_typed(c),
|
| 460 |
+
self.serde.dumps_typed(get_checkpoint_metadata(config, metadata)),
|
| 461 |
+
config["configurable"].get("checkpoint_id"), # parent
|
| 462 |
+
)
|
| 463 |
+
}
|
| 464 |
+
)
|
| 465 |
+
return {
|
| 466 |
+
"configurable": {
|
| 467 |
+
"thread_id": thread_id,
|
| 468 |
+
"checkpoint_ns": checkpoint_ns,
|
| 469 |
+
"checkpoint_id": checkpoint["id"],
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
def put_writes(
|
| 474 |
+
self,
|
| 475 |
+
config: RunnableConfig,
|
| 476 |
+
writes: Sequence[tuple[str, Any]],
|
| 477 |
+
task_id: str,
|
| 478 |
+
task_path: str = "",
|
| 479 |
+
) -> None:
|
| 480 |
+
"""Save a list of writes to the in-memory storage.
|
| 481 |
+
|
| 482 |
+
This method saves a list of writes to the in-memory storage. The writes are associated
|
| 483 |
+
with the provided config.
|
| 484 |
+
|
| 485 |
+
Args:
|
| 486 |
+
config: The config to associate with the writes.
|
| 487 |
+
writes: The writes to save.
|
| 488 |
+
task_id: Identifier for the task creating the writes.
|
| 489 |
+
task_path: Path of the task creating the writes.
|
| 490 |
+
|
| 491 |
+
Returns:
|
| 492 |
+
RunnableConfig: The updated config containing the saved writes' timestamp.
|
| 493 |
+
"""
|
| 494 |
+
thread_id = config["configurable"]["thread_id"]
|
| 495 |
+
checkpoint_ns = config["configurable"].get("checkpoint_ns", "")
|
| 496 |
+
checkpoint_id = config["configurable"]["checkpoint_id"]
|
| 497 |
+
outer_key = (thread_id, checkpoint_ns, checkpoint_id)
|
| 498 |
+
outer_writes_ = self.writes.get(outer_key)
|
| 499 |
+
for idx, (c, v) in enumerate(writes):
|
| 500 |
+
inner_key = (task_id, WRITES_IDX_MAP.get(c, idx))
|
| 501 |
+
if inner_key[1] >= 0 and outer_writes_ and inner_key in outer_writes_:
|
| 502 |
+
continue
|
| 503 |
+
|
| 504 |
+
self.writes[outer_key][inner_key] = (
|
| 505 |
+
task_id,
|
| 506 |
+
c,
|
| 507 |
+
self.serde.dumps_typed(v),
|
| 508 |
+
task_path,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
def delete_thread(self, thread_id: str) -> None:
|
| 512 |
+
"""Delete all checkpoints and writes associated with a thread ID.
|
| 513 |
+
|
| 514 |
+
Args:
|
| 515 |
+
thread_id: The thread ID to delete.
|
| 516 |
+
|
| 517 |
+
Returns:
|
| 518 |
+
None
|
| 519 |
+
"""
|
| 520 |
+
if thread_id in self.storage:
|
| 521 |
+
del self.storage[thread_id]
|
| 522 |
+
for k in list(self.writes.keys()):
|
| 523 |
+
if k[0] == thread_id:
|
| 524 |
+
del self.writes[k]
|
| 525 |
+
for k in list(self.blobs.keys()):
|
| 526 |
+
if k[0] == thread_id:
|
| 527 |
+
del self.blobs[k]
|
| 528 |
+
|
| 529 |
+
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
| 530 |
+
"""Asynchronous version of `get_tuple`.
|
| 531 |
+
|
| 532 |
+
This method is an asynchronous wrapper around `get_tuple` that runs the synchronous
|
| 533 |
+
method in a separate thread using asyncio.
|
| 534 |
+
|
| 535 |
+
Args:
|
| 536 |
+
config: The config to use for retrieving the checkpoint.
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
The retrieved checkpoint tuple, or None if no matching checkpoint was found.
|
| 540 |
+
"""
|
| 541 |
+
return self.get_tuple(config)
|
| 542 |
+
|
| 543 |
+
async def alist(
|
| 544 |
+
self,
|
| 545 |
+
config: RunnableConfig | None,
|
| 546 |
+
*,
|
| 547 |
+
filter: dict[str, Any] | None = None,
|
| 548 |
+
before: RunnableConfig | None = None,
|
| 549 |
+
limit: int | None = None,
|
| 550 |
+
) -> AsyncIterator[CheckpointTuple]:
|
| 551 |
+
"""Asynchronous version of `list`.
|
| 552 |
+
|
| 553 |
+
This method is an asynchronous wrapper around `list` that runs the synchronous
|
| 554 |
+
method in a separate thread using asyncio.
|
| 555 |
+
|
| 556 |
+
Args:
|
| 557 |
+
config: The config to use for listing the checkpoints.
|
| 558 |
+
|
| 559 |
+
Yields:
|
| 560 |
+
An asynchronous iterator of checkpoint tuples.
|
| 561 |
+
"""
|
| 562 |
+
for item in self.list(config, filter=filter, before=before, limit=limit):
|
| 563 |
+
yield item
|
| 564 |
+
|
| 565 |
+
async def aput(
|
| 566 |
+
self,
|
| 567 |
+
config: RunnableConfig,
|
| 568 |
+
checkpoint: Checkpoint,
|
| 569 |
+
metadata: CheckpointMetadata,
|
| 570 |
+
new_versions: ChannelVersions,
|
| 571 |
+
) -> RunnableConfig:
|
| 572 |
+
"""Asynchronous version of `put`.
|
| 573 |
+
|
| 574 |
+
Args:
|
| 575 |
+
config: The config to associate with the checkpoint.
|
| 576 |
+
checkpoint: The checkpoint to save.
|
| 577 |
+
metadata: Additional metadata to save with the checkpoint.
|
| 578 |
+
new_versions: New versions as of this write
|
| 579 |
+
|
| 580 |
+
Returns:
|
| 581 |
+
RunnableConfig: The updated config containing the saved checkpoint's timestamp.
|
| 582 |
+
"""
|
| 583 |
+
return self.put(config, checkpoint, metadata, new_versions)
|
| 584 |
+
|
| 585 |
+
async def aput_writes(
|
| 586 |
+
self,
|
| 587 |
+
config: RunnableConfig,
|
| 588 |
+
writes: Sequence[tuple[str, Any]],
|
| 589 |
+
task_id: str,
|
| 590 |
+
task_path: str = "",
|
| 591 |
+
) -> None:
|
| 592 |
+
"""Asynchronous version of `put_writes`.
|
| 593 |
+
|
| 594 |
+
This method is an asynchronous wrapper around `put_writes` that runs the synchronous
|
| 595 |
+
method in a separate thread using asyncio.
|
| 596 |
+
|
| 597 |
+
Args:
|
| 598 |
+
config: The config to associate with the writes.
|
| 599 |
+
writes: The writes to save, each as a (channel, value) pair.
|
| 600 |
+
task_id: Identifier for the task creating the writes.
|
| 601 |
+
task_path: Path of the task creating the writes.
|
| 602 |
+
|
| 603 |
+
Returns:
|
| 604 |
+
None
|
| 605 |
+
"""
|
| 606 |
+
return self.put_writes(config, writes, task_id, task_path)
|
| 607 |
+
|
| 608 |
+
async def adelete_thread(self, thread_id: str) -> None:
|
| 609 |
+
"""Delete all checkpoints and writes associated with a thread ID.
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
thread_id: The thread ID to delete.
|
| 613 |
+
|
| 614 |
+
Returns:
|
| 615 |
+
None
|
| 616 |
+
"""
|
| 617 |
+
return self.delete_thread(thread_id)
|
| 618 |
+
|
| 619 |
+
def get_next_version(self, current: str | None, channel: None) -> str:
|
| 620 |
+
if current is None:
|
| 621 |
+
current_v = 0
|
| 622 |
+
elif isinstance(current, int):
|
| 623 |
+
current_v = current
|
| 624 |
+
else:
|
| 625 |
+
current_v = int(current.split(".")[0])
|
| 626 |
+
next_v = current_v + 1
|
| 627 |
+
next_h = random.random()
|
| 628 |
+
return f"{next_v:032}.{next_h:016}"
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
MemorySaver = InMemorySaver # Kept for backwards compatibility
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class PersistentDict(defaultdict):
|
| 635 |
+
"""Persistent dictionary with an API compatible with shelve and anydbm.
|
| 636 |
+
|
| 637 |
+
The dict is kept in memory, so the dictionary operations run as fast as
|
| 638 |
+
a regular dictionary.
|
| 639 |
+
|
| 640 |
+
Write to disk is delayed until close or sync (similar to gdbm's fast mode).
|
| 641 |
+
|
| 642 |
+
Input file format is automatically discovered.
|
| 643 |
+
Output file format is selectable between pickle, json, and csv.
|
| 644 |
+
All three serialization formats are backed by fast C implementations.
|
| 645 |
+
|
| 646 |
+
Adapted from https://code.activestate.com/recipes/576642-persistent-dict-with-multiple-standard-file-format/
|
| 647 |
+
|
| 648 |
+
"""
|
| 649 |
+
|
| 650 |
+
def __init__(self, *args: Any, filename: str, **kwds: Any) -> None:
|
| 651 |
+
self.flag = "c" # r=readonly, c=create, or n=new
|
| 652 |
+
self.mode = None # None or an octal triple like 0644
|
| 653 |
+
self.format = "pickle" # 'csv', 'json', or 'pickle'
|
| 654 |
+
self.filename = filename
|
| 655 |
+
super().__init__(*args, **kwds)
|
| 656 |
+
|
| 657 |
+
def sync(self) -> None:
|
| 658 |
+
"Write dict to disk"
|
| 659 |
+
if self.flag == "r":
|
| 660 |
+
return
|
| 661 |
+
tempname = self.filename + ".tmp"
|
| 662 |
+
fileobj = open(tempname, "wb" if self.format == "pickle" else "w")
|
| 663 |
+
try:
|
| 664 |
+
self.dump(fileobj)
|
| 665 |
+
except Exception:
|
| 666 |
+
os.remove(tempname)
|
| 667 |
+
raise
|
| 668 |
+
finally:
|
| 669 |
+
fileobj.close()
|
| 670 |
+
shutil.move(tempname, self.filename) # atomic commit
|
| 671 |
+
if self.mode is not None:
|
| 672 |
+
os.chmod(self.filename, self.mode)
|
| 673 |
+
|
| 674 |
+
def close(self) -> None:
|
| 675 |
+
self.sync()
|
| 676 |
+
self.clear()
|
| 677 |
+
|
| 678 |
+
def __enter__(self) -> PersistentDict:
|
| 679 |
+
return self
|
| 680 |
+
|
| 681 |
+
def __exit__(self, *exc_info: Any) -> None:
|
| 682 |
+
self.close()
|
| 683 |
+
|
| 684 |
+
def dump(self, fileobj: Any) -> None:
|
| 685 |
+
if self.format == "pickle":
|
| 686 |
+
pickle.dump(dict(self), fileobj, 2)
|
| 687 |
+
else:
|
| 688 |
+
raise NotImplementedError("Unknown format: " + repr(self.format))
|
| 689 |
+
|
| 690 |
+
def load(self) -> None:
|
| 691 |
+
# try formats from most restrictive to least restrictive
|
| 692 |
+
if self.flag == "n":
|
| 693 |
+
return
|
| 694 |
+
with open(self.filename, "rb" if self.format == "pickle" else "r") as fileobj:
|
| 695 |
+
for loader in (pickle.load,):
|
| 696 |
+
fileobj.seek(0)
|
| 697 |
+
try:
|
| 698 |
+
return self.update(loader(fileobj))
|
| 699 |
+
except EOFError:
|
| 700 |
+
return
|
| 701 |
+
except Exception:
|
| 702 |
+
logger.error(f"Failed to load file: {fileobj.name}")
|
| 703 |
+
raise
|
| 704 |
+
raise ValueError("File not in a supported format")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (30.2 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/memory/py.typed
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__init__.py
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (214 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/_msgpack.cpython-311.pyc
ADDED
|
Binary file (2.63 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/base.cpython-311.pyc
ADDED
|
Binary file (4.33 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/encrypted.cpython-311.pyc
ADDED
|
Binary file (5.42 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/event_hooks.cpython-311.pyc
ADDED
|
Binary file (3.14 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/jsonplus.cpython-311.pyc
ADDED
|
Binary file (35.1 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/langgraph/checkpoint/serde/__pycache__/types.cpython-311.pyc
ADDED
|
Binary file (3.9 kB). View file
|
|
|