oliviadb-langgraph 0.1.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- oliviadb_langgraph-0.1.1/PKG-INFO +68 -0
- oliviadb_langgraph-0.1.1/README.md +55 -0
- oliviadb_langgraph-0.1.1/pyproject.toml +20 -0
- oliviadb_langgraph-0.1.1/setup.cfg +4 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph/__init__.py +19 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph/saver.py +249 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph/store.py +117 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph.egg-info/PKG-INFO +68 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph.egg-info/SOURCES.txt +11 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph.egg-info/dependency_links.txt +1 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph.egg-info/requires.txt +6 -0
- oliviadb_langgraph-0.1.1/src/oliviadb_langgraph.egg-info/top_level.txt +1 -0
- oliviadb_langgraph-0.1.1/tests/test_langgraph.py +115 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: oliviadb-langgraph
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: LangGraph checkpointer and store backed by OliviaDB
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: oliviadb>=0.1.0
|
|
9
|
+
Requires-Dist: langgraph<2,>=1.2
|
|
10
|
+
Requires-Dist: langgraph-checkpoint<5,>=4.3
|
|
11
|
+
Provides-Extra: test
|
|
12
|
+
Requires-Dist: langgraph-checkpoint-conformance==0.0.2; extra == "test"
|
|
13
|
+
|
|
14
|
+
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
|
15
|
+
# oliviadb-langgraph
|
|
16
|
+
|
|
17
|
+
[LangGraph](https://www.langchain.com/langgraph) persistence in [OliviaDB](https://olivia-db.com/):
|
|
18
|
+
a checkpointer (`OliviaDBSaver`: thread state, channel blobs, pending writes) and a store
|
|
19
|
+
(`OliviaDBStore`: long-term memories with TTL, filters and ranked search). Tested with
|
|
20
|
+
langgraph 1.2.24 and langgraph-checkpoint 4.3.2 (all five base capabilities of
|
|
21
|
+
langgraph-checkpoint-conformance).
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install oliviadb-langgraph
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Python 3.10 or later.
|
|
30
|
+
|
|
31
|
+
## Example
|
|
32
|
+
|
|
33
|
+
A server from the core image (`docker run -d -p 8443:8443 -v oliviadb-data:/data
|
|
34
|
+
ghcr.io/oliviadb/oliviadb`), its API key in `OLIVIADB_API_KEY` and its certificate in
|
|
35
|
+
`oliviadb-ca.pem` (`docker cp <container>:/data/tls/server.pem oliviadb-ca.pem`):
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from typing import TypedDict
|
|
40
|
+
|
|
41
|
+
from langgraph.graph import END, START, StateGraph
|
|
42
|
+
from oliviadb import OliviaDbClient
|
|
43
|
+
from oliviadb_langgraph import OliviaDBSaver, OliviaDBStore
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class State(TypedDict):
|
|
47
|
+
text: str
|
|
48
|
+
reply: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
client = OliviaDbClient("https://localhost:8443", api_key=os.environ["OLIVIADB_API_KEY"], ca_file="oliviadb-ca.pem")
|
|
52
|
+
graph = StateGraph(State)
|
|
53
|
+
graph.add_node("echo", lambda state: {"reply": state["text"]})
|
|
54
|
+
graph.add_edge(START, "echo")
|
|
55
|
+
graph.add_edge("echo", END)
|
|
56
|
+
app = graph.compile(
|
|
57
|
+
checkpointer=OliviaDBSaver(client, root=("langgraph", "support")),
|
|
58
|
+
store=OliviaDBStore(client, root=("langgraph", "support", "store")),
|
|
59
|
+
)
|
|
60
|
+
print(app.invoke({"text": "hello"}, {"configurable": {"thread_id": "demo"}})["reply"])
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Links
|
|
64
|
+
|
|
65
|
+
* Documentation: <https://docs.olivia-db.com/>
|
|
66
|
+
* Repository: <https://github.com/OliviaDB/oliviadb-python> (`adapters/langgraph`)
|
|
67
|
+
|
|
68
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
|
2
|
+
# oliviadb-langgraph
|
|
3
|
+
|
|
4
|
+
[LangGraph](https://www.langchain.com/langgraph) persistence in [OliviaDB](https://olivia-db.com/):
|
|
5
|
+
a checkpointer (`OliviaDBSaver`: thread state, channel blobs, pending writes) and a store
|
|
6
|
+
(`OliviaDBStore`: long-term memories with TTL, filters and ranked search). Tested with
|
|
7
|
+
langgraph 1.2.24 and langgraph-checkpoint 4.3.2 (all five base capabilities of
|
|
8
|
+
langgraph-checkpoint-conformance).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pip install oliviadb-langgraph
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Python 3.10 or later.
|
|
17
|
+
|
|
18
|
+
## Example
|
|
19
|
+
|
|
20
|
+
A server from the core image (`docker run -d -p 8443:8443 -v oliviadb-data:/data
|
|
21
|
+
ghcr.io/oliviadb/oliviadb`), its API key in `OLIVIADB_API_KEY` and its certificate in
|
|
22
|
+
`oliviadb-ca.pem` (`docker cp <container>:/data/tls/server.pem oliviadb-ca.pem`):
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import os
|
|
26
|
+
from typing import TypedDict
|
|
27
|
+
|
|
28
|
+
from langgraph.graph import END, START, StateGraph
|
|
29
|
+
from oliviadb import OliviaDbClient
|
|
30
|
+
from oliviadb_langgraph import OliviaDBSaver, OliviaDBStore
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class State(TypedDict):
|
|
34
|
+
text: str
|
|
35
|
+
reply: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
client = OliviaDbClient("https://localhost:8443", api_key=os.environ["OLIVIADB_API_KEY"], ca_file="oliviadb-ca.pem")
|
|
39
|
+
graph = StateGraph(State)
|
|
40
|
+
graph.add_node("echo", lambda state: {"reply": state["text"]})
|
|
41
|
+
graph.add_edge(START, "echo")
|
|
42
|
+
graph.add_edge("echo", END)
|
|
43
|
+
app = graph.compile(
|
|
44
|
+
checkpointer=OliviaDBSaver(client, root=("langgraph", "support")),
|
|
45
|
+
store=OliviaDBStore(client, root=("langgraph", "support", "store")),
|
|
46
|
+
)
|
|
47
|
+
print(app.invoke({"text": "hello"}, {"configurable": {"thread_id": "demo"}})["reply"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Links
|
|
51
|
+
|
|
52
|
+
* Documentation: <https://docs.olivia-db.com/>
|
|
53
|
+
* Repository: <https://github.com/OliviaDB/oliviadb-python> (`adapters/langgraph`)
|
|
54
|
+
|
|
55
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
[build-system]
|
|
3
|
+
requires = ["setuptools>=68"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
name = "oliviadb-langgraph"
|
|
8
|
+
version = "0.1.1"
|
|
9
|
+
description = "LangGraph checkpointer and store backed by OliviaDB"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
# Built and tested against langgraph 1.2.24, langgraph-checkpoint 4.3.2.
|
|
14
|
+
dependencies = ["oliviadb>=0.1.0", "langgraph>=1.2,<2", "langgraph-checkpoint>=4.3,<5"]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
test = ["langgraph-checkpoint-conformance==0.0.2"]
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.packages.find]
|
|
20
|
+
where = ["src"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""LangGraph persistence on OliviaDB: a checkpointer (`OliviaDBSaver`, langgraph-checkpoint's
|
|
3
|
+
`BaseCheckpointSaver`) and a long-term memory store (`OliviaDBStore`, langgraph's `BaseStore`),
|
|
4
|
+
both over OliviaDB's agent state (`/v1/state`), so graph state and memories live in OliviaDB with
|
|
5
|
+
its access control, sealing and audit.
|
|
6
|
+
|
|
7
|
+
from oliviadb import OliviaDbClient
|
|
8
|
+
from oliviadb_langgraph import OliviaDBSaver, OliviaDBStore
|
|
9
|
+
oliviadb = OliviaDbClient("https://oliviadb.example:8443", token=...)
|
|
10
|
+
graph = builder.compile(checkpointer=OliviaDBSaver(oliviadb), store=OliviaDBStore(oliviadb))
|
|
11
|
+
|
|
12
|
+
Interfaces as published in langgraph-checkpoint 4.3.2 and langgraph 1.2.24 (checked by
|
|
13
|
+
the langgraph-checkpoint-conformance 0.0.2 suite and this package's tests).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .saver import OliviaDBSaver
|
|
17
|
+
from .store import OliviaDBStore
|
|
18
|
+
|
|
19
|
+
__all__ = ["OliviaDBSaver", "OliviaDBStore"]
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""LangGraph checkpointer on OliviaDB agent state.
|
|
3
|
+
|
|
4
|
+
Layout under the namespace root (default ["langgraph", "default"]):
|
|
5
|
+
ckpt/<thread>/<ns> key = checkpoint id -> checkpoint (without channel values), metadata, parent
|
|
6
|
+
blobs/<thread>/<ns> key = [channel, version] -> one channel value (stored once per version)
|
|
7
|
+
writes/<thread>/<ns>/<checkpoint id> key = [task id, index] -> a pending write
|
|
8
|
+
Serialized values are the checkpointer's serde output (type, bytes), base64 in JSON.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import base64
|
|
15
|
+
import json
|
|
16
|
+
from collections.abc import AsyncIterator, Iterator, Sequence
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from langchain_core.runnables import RunnableConfig
|
|
20
|
+
from langgraph.checkpoint.base import (
|
|
21
|
+
WRITES_IDX_MAP,
|
|
22
|
+
BaseCheckpointSaver,
|
|
23
|
+
ChannelVersions,
|
|
24
|
+
Checkpoint,
|
|
25
|
+
CheckpointMetadata,
|
|
26
|
+
CheckpointTuple,
|
|
27
|
+
get_checkpoint_id,
|
|
28
|
+
get_checkpoint_metadata,
|
|
29
|
+
writes_sort_key,
|
|
30
|
+
)
|
|
31
|
+
from oliviadb import OliviaDbClient, OliviaDbError
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _ns(ns: str) -> str:
|
|
35
|
+
# Namespace components must be non-empty: "" (the root graph) is "-", others "~ns".
|
|
36
|
+
return "-" if ns == "" else "~" + ns
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unns(s: str) -> str:
|
|
40
|
+
return "" if s == "-" else s[1:]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class OliviaDBSaver(BaseCheckpointSaver[str]):
|
|
44
|
+
"""Checkpoints of LangGraph threads in OliviaDB."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, client: OliviaDbClient, *, root: Sequence[str] = ("langgraph", "default"), serde: Any = None):
|
|
47
|
+
super().__init__(serde=serde)
|
|
48
|
+
self.c = client
|
|
49
|
+
self.root = list(root)
|
|
50
|
+
|
|
51
|
+
# ---- encoding ----------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
def _dump(self, v: Any) -> dict:
|
|
54
|
+
t, b = self.serde.dumps_typed(v)
|
|
55
|
+
return {"t": t, "d": base64.b64encode(b).decode()}
|
|
56
|
+
|
|
57
|
+
def _load(self, d: dict) -> Any:
|
|
58
|
+
return self.serde.loads_typed((d["t"], base64.b64decode(d["d"])))
|
|
59
|
+
|
|
60
|
+
def _p(self, kind: str, *rest: str) -> list[str]:
|
|
61
|
+
return [*self.root, kind, *rest]
|
|
62
|
+
|
|
63
|
+
def _blobs(self, thread: str, ns: str, versions: ChannelVersions) -> dict[str, Any]:
|
|
64
|
+
out: dict[str, Any] = {}
|
|
65
|
+
for ch, ver in versions.items():
|
|
66
|
+
it = self.c.state_get(self._p("blobs", thread, _ns(ns)), json.dumps([ch, str(ver)]))
|
|
67
|
+
if it is None or it["value"].get("empty"):
|
|
68
|
+
continue
|
|
69
|
+
out[ch] = self._load(it["value"])
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
def _writes(self, thread: str, ns: str, cid: str) -> list[tuple[str, str, Any]]:
|
|
73
|
+
items = self._all(self._p("writes", thread, _ns(ns), cid))
|
|
74
|
+
ws = [i["value"] for i in items]
|
|
75
|
+
ws.sort(key=lambda w: writes_sort_key(w["task_path"], w["task_id"], w["idx"]))
|
|
76
|
+
return [(w["task_id"], w["channel"], self._load(w["v"])) for w in ws]
|
|
77
|
+
|
|
78
|
+
def _all(self, namespace: list[str], reverse: bool = False) -> list[dict]:
|
|
79
|
+
out, after = [], None
|
|
80
|
+
while True:
|
|
81
|
+
page = self.c.state_list(namespace, after=after, limit=500, reverse=reverse)
|
|
82
|
+
out.extend(page)
|
|
83
|
+
if len(page) < 500:
|
|
84
|
+
return out
|
|
85
|
+
after = page[-1]["key"]
|
|
86
|
+
|
|
87
|
+
def _tuple(self, thread: str, ns: str, item: dict, config: RunnableConfig | None = None) -> CheckpointTuple:
|
|
88
|
+
v = item["value"]
|
|
89
|
+
cid = item["key"]
|
|
90
|
+
ck: Checkpoint = self._load(v["c"])
|
|
91
|
+
parent = v.get("parent")
|
|
92
|
+
return CheckpointTuple(
|
|
93
|
+
config=config or {"configurable": {"thread_id": thread, "checkpoint_ns": ns, "checkpoint_id": cid}},
|
|
94
|
+
checkpoint={**ck, "channel_values": self._blobs(thread, ns, ck["channel_versions"])},
|
|
95
|
+
metadata=self._load(v["m"]),
|
|
96
|
+
parent_config={"configurable": {"thread_id": thread, "checkpoint_ns": ns, "checkpoint_id": parent}}
|
|
97
|
+
if parent
|
|
98
|
+
else None,
|
|
99
|
+
pending_writes=self._writes(thread, ns, cid),
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# ---- BaseCheckpointSaver -----------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
def get_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
|
105
|
+
thread = config["configurable"]["thread_id"]
|
|
106
|
+
ns = config["configurable"].get("checkpoint_ns", "")
|
|
107
|
+
cid = get_checkpoint_id(config)
|
|
108
|
+
if cid:
|
|
109
|
+
it = self.c.state_get(self._p("ckpt", thread, _ns(ns)), cid)
|
|
110
|
+
return self._tuple(thread, ns, it, config) if it else None
|
|
111
|
+
last = self.c.state_list(self._p("ckpt", thread, _ns(ns)), limit=1, reverse=True)
|
|
112
|
+
return self._tuple(thread, ns, last[0]) if last else None
|
|
113
|
+
|
|
114
|
+
def list(
|
|
115
|
+
self,
|
|
116
|
+
config: RunnableConfig | None,
|
|
117
|
+
*,
|
|
118
|
+
filter: dict[str, Any] | None = None,
|
|
119
|
+
before: RunnableConfig | None = None,
|
|
120
|
+
limit: int | None = None,
|
|
121
|
+
) -> Iterator[CheckpointTuple]:
|
|
122
|
+
if config:
|
|
123
|
+
threads = [config["configurable"]["thread_id"]]
|
|
124
|
+
else:
|
|
125
|
+
threads = sorted(
|
|
126
|
+
{
|
|
127
|
+
n[len(self.root) + 1]
|
|
128
|
+
for n in self.c.state_namespaces(prefix=self._p("ckpt"), max_depth=len(self.root) + 2, limit=100000)
|
|
129
|
+
}
|
|
130
|
+
)
|
|
131
|
+
want_ns = config["configurable"].get("checkpoint_ns") if config else None
|
|
132
|
+
want_id = get_checkpoint_id(config) if config else None
|
|
133
|
+
before_id = get_checkpoint_id(before) if before else None
|
|
134
|
+
for thread in threads:
|
|
135
|
+
spaces = [n[-1] for n in self.c.state_namespaces(prefix=self._p("ckpt", thread), limit=100000)]
|
|
136
|
+
for enc in spaces:
|
|
137
|
+
ns = _unns(enc)
|
|
138
|
+
if want_ns is not None and ns != want_ns:
|
|
139
|
+
continue
|
|
140
|
+
for item in self._all(self._p("ckpt", thread, enc), reverse=True):
|
|
141
|
+
cid = item["key"]
|
|
142
|
+
if want_id and cid != want_id:
|
|
143
|
+
continue
|
|
144
|
+
if before_id and cid >= before_id:
|
|
145
|
+
continue
|
|
146
|
+
if filter:
|
|
147
|
+
md = self._load(item["value"]["m"])
|
|
148
|
+
if not all(md.get(k) == v for k, v in filter.items()):
|
|
149
|
+
continue
|
|
150
|
+
if limit is not None:
|
|
151
|
+
if limit <= 0:
|
|
152
|
+
return
|
|
153
|
+
limit -= 1
|
|
154
|
+
yield self._tuple(thread, ns, item)
|
|
155
|
+
|
|
156
|
+
def put(
|
|
157
|
+
self,
|
|
158
|
+
config: RunnableConfig,
|
|
159
|
+
checkpoint: Checkpoint,
|
|
160
|
+
metadata: CheckpointMetadata,
|
|
161
|
+
new_versions: ChannelVersions,
|
|
162
|
+
) -> RunnableConfig:
|
|
163
|
+
c = checkpoint.copy()
|
|
164
|
+
thread = config["configurable"]["thread_id"]
|
|
165
|
+
ns = config["configurable"]["checkpoint_ns"]
|
|
166
|
+
values: dict[str, Any] = c.pop("channel_values") # type: ignore[misc]
|
|
167
|
+
for ch, ver in new_versions.items():
|
|
168
|
+
v = self._dump(values[ch]) if ch in values else {"empty": True}
|
|
169
|
+
self.c.state_put(self._p("blobs", thread, _ns(ns)), json.dumps([ch, str(ver)]), v, index=False)
|
|
170
|
+
self.c.state_put(
|
|
171
|
+
self._p("ckpt", thread, _ns(ns)),
|
|
172
|
+
checkpoint["id"],
|
|
173
|
+
{
|
|
174
|
+
"c": self._dump(c),
|
|
175
|
+
"m": self._dump(get_checkpoint_metadata(config, metadata)),
|
|
176
|
+
"parent": config["configurable"].get("checkpoint_id"),
|
|
177
|
+
},
|
|
178
|
+
index=False,
|
|
179
|
+
)
|
|
180
|
+
return {"configurable": {"thread_id": thread, "checkpoint_ns": ns, "checkpoint_id": checkpoint["id"]}}
|
|
181
|
+
|
|
182
|
+
def put_writes(
|
|
183
|
+
self, config: RunnableConfig, writes: Sequence[tuple[str, Any]], task_id: str, task_path: str = ""
|
|
184
|
+
) -> None:
|
|
185
|
+
thread = config["configurable"]["thread_id"]
|
|
186
|
+
ns = config["configurable"].get("checkpoint_ns", "")
|
|
187
|
+
cid = config["configurable"]["checkpoint_id"]
|
|
188
|
+
where = self._p("writes", thread, _ns(ns), cid)
|
|
189
|
+
for idx, (ch, v) in enumerate(writes):
|
|
190
|
+
i = WRITES_IDX_MAP.get(ch, idx)
|
|
191
|
+
rec = {"task_id": task_id, "idx": i, "channel": ch, "v": self._dump(v), "task_path": task_path}
|
|
192
|
+
try:
|
|
193
|
+
# Regular writes are written once (a retried task keeps the first); special
|
|
194
|
+
# channels (negative index) are replaced.
|
|
195
|
+
self.c.state_put(
|
|
196
|
+
where, json.dumps([task_id, i]), rec, index=False, expected_version=0 if i >= 0 else None
|
|
197
|
+
)
|
|
198
|
+
except OliviaDbError as e:
|
|
199
|
+
if e.status != 409:
|
|
200
|
+
raise
|
|
201
|
+
|
|
202
|
+
def delete_thread(self, thread_id: str) -> None:
|
|
203
|
+
for kind in ("ckpt", "blobs", "writes"):
|
|
204
|
+
self.c.state_delete(self._p(kind, thread_id), prefix=True)
|
|
205
|
+
|
|
206
|
+
def get_next_version(self, current: str | None, channel: None) -> str:
|
|
207
|
+
import random
|
|
208
|
+
|
|
209
|
+
if current is None:
|
|
210
|
+
v = 0
|
|
211
|
+
elif isinstance(current, int):
|
|
212
|
+
v = current
|
|
213
|
+
else:
|
|
214
|
+
v = int(str(current).split(".")[0])
|
|
215
|
+
return f"{v + 1:032}.{random.random():016}"
|
|
216
|
+
|
|
217
|
+
# ---- async: the client is synchronous, calls run on a worker thread ------------------
|
|
218
|
+
|
|
219
|
+
async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None:
|
|
220
|
+
return await asyncio.to_thread(self.get_tuple, config)
|
|
221
|
+
|
|
222
|
+
async def alist(
|
|
223
|
+
self,
|
|
224
|
+
config: RunnableConfig | None,
|
|
225
|
+
*,
|
|
226
|
+
filter: dict[str, Any] | None = None,
|
|
227
|
+
before: RunnableConfig | None = None,
|
|
228
|
+
limit: int | None = None,
|
|
229
|
+
) -> AsyncIterator[CheckpointTuple]:
|
|
230
|
+
items = await asyncio.to_thread(lambda: list(self.list(config, filter=filter, before=before, limit=limit)))
|
|
231
|
+
for i in items:
|
|
232
|
+
yield i
|
|
233
|
+
|
|
234
|
+
async def aput(
|
|
235
|
+
self,
|
|
236
|
+
config: RunnableConfig,
|
|
237
|
+
checkpoint: Checkpoint,
|
|
238
|
+
metadata: CheckpointMetadata,
|
|
239
|
+
new_versions: ChannelVersions,
|
|
240
|
+
) -> RunnableConfig:
|
|
241
|
+
return await asyncio.to_thread(self.put, config, checkpoint, metadata, new_versions)
|
|
242
|
+
|
|
243
|
+
async def aput_writes(
|
|
244
|
+
self, config: RunnableConfig, writes: Sequence[tuple[str, Any]], task_id: str, task_path: str = ""
|
|
245
|
+
) -> None:
|
|
246
|
+
await asyncio.to_thread(self.put_writes, config, writes, task_id, task_path)
|
|
247
|
+
|
|
248
|
+
async def adelete_thread(self, thread_id: str) -> None:
|
|
249
|
+
await asyncio.to_thread(self.delete_thread, thread_id)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""LangGraph long-term memory store (BaseStore) on OliviaDB agent state.
|
|
3
|
+
|
|
4
|
+
Namespaces map to OliviaDB namespace paths under a root (default ["langgraph-store"]); values
|
|
5
|
+
are stored as JSON with LangGraph's `index` choice (fields to embed, or False), TTL in
|
|
6
|
+
minutes, filters and ranked search done by OliviaDB (BM25 and the server's embedder).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
|
|
15
|
+
from langgraph.store.base import (
|
|
16
|
+
BaseStore,
|
|
17
|
+
GetOp,
|
|
18
|
+
Item,
|
|
19
|
+
ListNamespacesOp,
|
|
20
|
+
MatchCondition,
|
|
21
|
+
Op,
|
|
22
|
+
PutOp,
|
|
23
|
+
Result,
|
|
24
|
+
SearchItem,
|
|
25
|
+
SearchOp,
|
|
26
|
+
)
|
|
27
|
+
from oliviadb import OliviaDbClient
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _dt(ms: int) -> datetime:
|
|
31
|
+
return datetime.fromtimestamp(ms / 1000, tz=timezone.utc)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _matches(cond: MatchCondition, ns: tuple[str, ...]) -> bool:
|
|
35
|
+
p = tuple(cond.path)
|
|
36
|
+
if len(ns) < len(p):
|
|
37
|
+
return False
|
|
38
|
+
part = ns[: len(p)] if cond.match_type == "prefix" else ns[len(ns) - len(p) :]
|
|
39
|
+
return all(a == "*" or a == b for a, b in zip(p, part, strict=False))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class OliviaDBStore(BaseStore):
|
|
43
|
+
"""Long-term memory for LangGraph agents, kept in OliviaDB."""
|
|
44
|
+
|
|
45
|
+
supports_ttl = True
|
|
46
|
+
|
|
47
|
+
def __init__(self, client: OliviaDbClient, *, root: Sequence[str] = ("langgraph-store",)):
|
|
48
|
+
self.c = client
|
|
49
|
+
self.root = list(root)
|
|
50
|
+
|
|
51
|
+
def _path(self, ns: Sequence[str]) -> list[str]:
|
|
52
|
+
return self.root + list(ns)
|
|
53
|
+
|
|
54
|
+
def _rel(self, ns: Sequence[str]) -> tuple[str, ...]:
|
|
55
|
+
return tuple(ns[len(self.root) :])
|
|
56
|
+
|
|
57
|
+
def batch(self, ops: Iterable[Op]) -> list[Result]:
|
|
58
|
+
out: list[Result] = []
|
|
59
|
+
for op in ops:
|
|
60
|
+
if isinstance(op, GetOp):
|
|
61
|
+
it = self.c.state_get(self._path(op.namespace), op.key)
|
|
62
|
+
out.append(
|
|
63
|
+
Item(
|
|
64
|
+
value=it["value"],
|
|
65
|
+
key=it["key"],
|
|
66
|
+
namespace=self._rel(it["namespace"]),
|
|
67
|
+
created_at=_dt(it["created_ms"]),
|
|
68
|
+
updated_at=_dt(it["updated_ms"]),
|
|
69
|
+
)
|
|
70
|
+
if it
|
|
71
|
+
else None
|
|
72
|
+
)
|
|
73
|
+
elif isinstance(op, PutOp):
|
|
74
|
+
if op.value is None:
|
|
75
|
+
self.c.state_delete(self._path(op.namespace), op.key)
|
|
76
|
+
else:
|
|
77
|
+
ttl = None if op.ttl is None else int(op.ttl * 60_000)
|
|
78
|
+
index = False if op.index is False else (list(op.index) if op.index else None)
|
|
79
|
+
self.c.state_put(self._path(op.namespace), op.key, dict(op.value), ttl_ms=ttl, index=index)
|
|
80
|
+
out.append(None)
|
|
81
|
+
elif isinstance(op, SearchOp):
|
|
82
|
+
items = self.c.state_search(
|
|
83
|
+
self._path(op.namespace_prefix), query=op.query, filter=op.filter, limit=op.limit, offset=op.offset
|
|
84
|
+
)
|
|
85
|
+
out.append(
|
|
86
|
+
[
|
|
87
|
+
SearchItem(
|
|
88
|
+
namespace=self._rel(i["namespace"]),
|
|
89
|
+
key=i["key"],
|
|
90
|
+
value=i["value"],
|
|
91
|
+
created_at=_dt(i["created_ms"]),
|
|
92
|
+
updated_at=_dt(i["updated_ms"]),
|
|
93
|
+
score=i.get("score"),
|
|
94
|
+
)
|
|
95
|
+
for i in items
|
|
96
|
+
]
|
|
97
|
+
)
|
|
98
|
+
elif isinstance(op, ListNamespacesOp):
|
|
99
|
+
all_ns = [self._rel(n) for n in self.c.state_namespaces(prefix=self.root, limit=1_000_000)]
|
|
100
|
+
res = []
|
|
101
|
+
seen = set()
|
|
102
|
+
for ns in all_ns:
|
|
103
|
+
if op.match_conditions and not all(_matches(c, ns) for c in op.match_conditions):
|
|
104
|
+
continue
|
|
105
|
+
n = ns[: op.max_depth] if op.max_depth is not None else ns
|
|
106
|
+
if n not in seen:
|
|
107
|
+
seen.add(n)
|
|
108
|
+
res.append(n)
|
|
109
|
+
res.sort()
|
|
110
|
+
out.append(res[op.offset : op.offset + op.limit])
|
|
111
|
+
else:
|
|
112
|
+
raise ValueError(f"unknown operation {op!r}")
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
async def abatch(self, ops: Iterable[Op]) -> list[Result]:
|
|
116
|
+
ops = list(ops)
|
|
117
|
+
return await asyncio.to_thread(self.batch, ops)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: oliviadb-langgraph
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: LangGraph checkpointer and store backed by OliviaDB
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: oliviadb>=0.1.0
|
|
9
|
+
Requires-Dist: langgraph<2,>=1.2
|
|
10
|
+
Requires-Dist: langgraph-checkpoint<5,>=4.3
|
|
11
|
+
Provides-Extra: test
|
|
12
|
+
Requires-Dist: langgraph-checkpoint-conformance==0.0.2; extra == "test"
|
|
13
|
+
|
|
14
|
+
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
|
15
|
+
# oliviadb-langgraph
|
|
16
|
+
|
|
17
|
+
[LangGraph](https://www.langchain.com/langgraph) persistence in [OliviaDB](https://olivia-db.com/):
|
|
18
|
+
a checkpointer (`OliviaDBSaver`: thread state, channel blobs, pending writes) and a store
|
|
19
|
+
(`OliviaDBStore`: long-term memories with TTL, filters and ranked search). Tested with
|
|
20
|
+
langgraph 1.2.24 and langgraph-checkpoint 4.3.2 (all five base capabilities of
|
|
21
|
+
langgraph-checkpoint-conformance).
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install oliviadb-langgraph
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Python 3.10 or later.
|
|
30
|
+
|
|
31
|
+
## Example
|
|
32
|
+
|
|
33
|
+
A server from the core image (`docker run -d -p 8443:8443 -v oliviadb-data:/data
|
|
34
|
+
ghcr.io/oliviadb/oliviadb`), its API key in `OLIVIADB_API_KEY` and its certificate in
|
|
35
|
+
`oliviadb-ca.pem` (`docker cp <container>:/data/tls/server.pem oliviadb-ca.pem`):
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import os
|
|
39
|
+
from typing import TypedDict
|
|
40
|
+
|
|
41
|
+
from langgraph.graph import END, START, StateGraph
|
|
42
|
+
from oliviadb import OliviaDbClient
|
|
43
|
+
from oliviadb_langgraph import OliviaDBSaver, OliviaDBStore
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class State(TypedDict):
|
|
47
|
+
text: str
|
|
48
|
+
reply: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
client = OliviaDbClient("https://localhost:8443", api_key=os.environ["OLIVIADB_API_KEY"], ca_file="oliviadb-ca.pem")
|
|
52
|
+
graph = StateGraph(State)
|
|
53
|
+
graph.add_node("echo", lambda state: {"reply": state["text"]})
|
|
54
|
+
graph.add_edge(START, "echo")
|
|
55
|
+
graph.add_edge("echo", END)
|
|
56
|
+
app = graph.compile(
|
|
57
|
+
checkpointer=OliviaDBSaver(client, root=("langgraph", "support")),
|
|
58
|
+
store=OliviaDBStore(client, root=("langgraph", "support", "store")),
|
|
59
|
+
)
|
|
60
|
+
print(app.invoke({"text": "hello"}, {"configurable": {"thread_id": "demo"}})["reply"])
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Links
|
|
64
|
+
|
|
65
|
+
* Documentation: <https://docs.olivia-db.com/>
|
|
66
|
+
* Repository: <https://github.com/OliviaDB/oliviadb-python> (`adapters/langgraph`)
|
|
67
|
+
|
|
68
|
+
Licence: Apache-2.0.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/oliviadb_langgraph/__init__.py
|
|
4
|
+
src/oliviadb_langgraph/saver.py
|
|
5
|
+
src/oliviadb_langgraph/store.py
|
|
6
|
+
src/oliviadb_langgraph.egg-info/PKG-INFO
|
|
7
|
+
src/oliviadb_langgraph.egg-info/SOURCES.txt
|
|
8
|
+
src/oliviadb_langgraph.egg-info/dependency_links.txt
|
|
9
|
+
src/oliviadb_langgraph.egg-info/requires.txt
|
|
10
|
+
src/oliviadb_langgraph.egg-info/top_level.txt
|
|
11
|
+
tests/test_langgraph.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
oliviadb_langgraph
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Against a real oliviadb-server (OLIVIADB_SERVER_URL, OLIVIADB_API_KEY): the published checkpointer
|
|
3
|
+
conformance suite, the store's operations, and the example agent across invocations."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
import unittest
|
|
10
|
+
import uuid
|
|
11
|
+
|
|
12
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
13
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "examples"))
|
|
14
|
+
|
|
15
|
+
URL = os.environ.get("OLIVIADB_SERVER_URL")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def client():
|
|
19
|
+
from oliviadb import OliviaDbClient
|
|
20
|
+
|
|
21
|
+
return OliviaDbClient(URL, api_key=os.environ["OLIVIADB_API_KEY"])
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@unittest.skipUnless(URL, "OLIVIADB_SERVER_URL not set")
|
|
25
|
+
class Conformance(unittest.TestCase):
|
|
26
|
+
def test_checkpointer_conformance(self):
|
|
27
|
+
from langgraph.checkpoint.conformance import checkpointer_test, validate
|
|
28
|
+
from oliviadb_langgraph import OliviaDBSaver
|
|
29
|
+
|
|
30
|
+
@checkpointer_test(name="OliviaDBSaver")
|
|
31
|
+
async def saver():
|
|
32
|
+
yield OliviaDBSaver(client(), root=("lgconf", uuid.uuid4().hex))
|
|
33
|
+
|
|
34
|
+
report = asyncio.run(validate(saver))
|
|
35
|
+
report.print_report()
|
|
36
|
+
self.assertTrue(report.passed_all_base())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@unittest.skipUnless(URL, "OLIVIADB_SERVER_URL not set")
|
|
40
|
+
class Store(unittest.TestCase):
|
|
41
|
+
def setUp(self):
|
|
42
|
+
from oliviadb_langgraph import OliviaDBStore
|
|
43
|
+
|
|
44
|
+
self.s = OliviaDBStore(client(), root=["lgstore", uuid.uuid4().hex])
|
|
45
|
+
|
|
46
|
+
def test_put_get_delete(self):
|
|
47
|
+
self.s.put(("users", "u1"), "prefs", {"theme": "dark", "lang": "de"})
|
|
48
|
+
it = self.s.get(("users", "u1"), "prefs")
|
|
49
|
+
self.assertEqual((it.namespace, it.key, it.value["lang"]), (("users", "u1"), "prefs", "de"))
|
|
50
|
+
self.s.put(("users", "u1"), "prefs", {"theme": "light"})
|
|
51
|
+
self.assertEqual(self.s.get(("users", "u1"), "prefs").value, {"theme": "light"})
|
|
52
|
+
self.s.delete(("users", "u1"), "prefs")
|
|
53
|
+
self.assertIsNone(self.s.get(("users", "u1"), "prefs"))
|
|
54
|
+
|
|
55
|
+
def test_search_and_filters(self):
|
|
56
|
+
self.s.put(("mem", "u1"), "a", {"text": "likes hiking in the Alps", "kind": "hobby", "n": 3})
|
|
57
|
+
self.s.put(("mem", "u1"), "b", {"text": "allergic to peanuts", "kind": "health", "n": 7})
|
|
58
|
+
self.s.put(("mem", "u2"), "c", {"text": "allergic to cats", "kind": "health", "n": 1})
|
|
59
|
+
hits = self.s.search(("mem",), query="peanut allergy", limit=1)
|
|
60
|
+
self.assertEqual(hits[0].key, "b")
|
|
61
|
+
self.assertIsNotNone(hits[0].score)
|
|
62
|
+
self.assertEqual({h.key for h in self.s.search(("mem",), filter={"kind": "health"})}, {"b", "c"})
|
|
63
|
+
self.assertEqual([h.key for h in self.s.search(("mem",), filter={"n": {"$gt": 5}})], ["b"])
|
|
64
|
+
self.assertEqual([h.key for h in self.s.search(("mem", "u2"))], ["c"])
|
|
65
|
+
|
|
66
|
+
def test_list_namespaces(self):
|
|
67
|
+
for ns in [("a", "b", "c"), ("a", "b", "d"), ("a", "x"), ("z",)]:
|
|
68
|
+
self.s.put(ns, "k", {"v": 1})
|
|
69
|
+
self.assertEqual(self.s.list_namespaces(prefix=("a",)), [("a", "b", "c"), ("a", "b", "d"), ("a", "x")])
|
|
70
|
+
self.assertEqual(self.s.list_namespaces(max_depth=2), [("a", "b"), ("a", "x"), ("z",)])
|
|
71
|
+
self.assertEqual(self.s.list_namespaces(suffix=("d",)), [("a", "b", "d")])
|
|
72
|
+
self.assertEqual(self.s.list_namespaces(prefix=("a", "*", "c")), [("a", "b", "c")])
|
|
73
|
+
|
|
74
|
+
def test_ttl(self):
|
|
75
|
+
self.s.put(("tmp",), "k", {"v": 1}, ttl=0.0001) # minutes: 6 ms
|
|
76
|
+
time.sleep(0.05)
|
|
77
|
+
self.assertIsNone(self.s.get(("tmp",), "k"))
|
|
78
|
+
|
|
79
|
+
def test_async(self):
|
|
80
|
+
async def go():
|
|
81
|
+
await self.s.aput(("as",), "k", {"v": 2})
|
|
82
|
+
return await self.s.aget(("as",), "k")
|
|
83
|
+
|
|
84
|
+
self.assertEqual(asyncio.run(go()).value, {"v": 2})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@unittest.skipUnless(URL, "OLIVIADB_SERVER_URL not set")
|
|
88
|
+
class ExampleAgent(unittest.TestCase):
|
|
89
|
+
def test_state_and_memory_persist(self):
|
|
90
|
+
from support_agent import build
|
|
91
|
+
|
|
92
|
+
root = ("lgex", uuid.uuid4().hex)
|
|
93
|
+
app = build(client(), root)
|
|
94
|
+
cfg = {"configurable": {"thread_id": "t1"}}
|
|
95
|
+
self.assertEqual(
|
|
96
|
+
app.invoke({"user": "u1", "said": ["I live in Lisbon."]}, cfg)["reply"],
|
|
97
|
+
"Noted (1 messages in this thread).",
|
|
98
|
+
)
|
|
99
|
+
# A new graph object (a restarted process): the thread continues from OliviaDB.
|
|
100
|
+
app2 = build(client(), root)
|
|
101
|
+
self.assertEqual(
|
|
102
|
+
app2.invoke({"user": "u1", "said": ["hello"]}, cfg)["reply"], "Noted (2 messages in this thread)."
|
|
103
|
+
)
|
|
104
|
+
# Long-term memory crosses threads.
|
|
105
|
+
other = {"configurable": {"thread_id": "t2"}}
|
|
106
|
+
self.assertEqual(
|
|
107
|
+
app2.invoke({"user": "u1", "said": ["Where do I live?"]}, other)["reply"], "You live in Lisbon."
|
|
108
|
+
)
|
|
109
|
+
# Time travel: the first checkpoint of t1 is still there.
|
|
110
|
+
hist = list(app2.get_state_history(cfg))
|
|
111
|
+
self.assertGreaterEqual(len(hist), 4)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__":
|
|
115
|
+
unittest.main()
|