-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_saver.py
372 lines (350 loc) · 14.8 KB
/
redis_saver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""Implementation of a langgraph checkpoint saver using Redis."""
from contextlib import asynccontextmanager, contextmanager
from typing import Any, AsyncGenerator, Generator, Union, Optional
import redis
from redis.asyncio import Redis as AsyncRedis, ConnectionPool as AsyncConnectionPool
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint import BaseCheckpointSaver
from langgraph.serde.jsonplus import JsonPlusSerializer
from langgraph.checkpoint.base import Checkpoint, CheckpointMetadata, CheckpointTuple
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class JsonAndBinarySerializer(JsonPlusSerializer):
def _default(self, obj: Any) -> Any:
if isinstance(obj, (bytes, bytearray)):
return self._encode_constructor_args(
obj.__class__, method="fromhex", args=[obj.hex()]
)
return super()._default(obj)
def dumps(self, obj: Any) -> str:
try:
if isinstance(obj, (bytes, bytearray)):
return obj.hex()
return super().dumps(obj)
except Exception as e:
logger.error(f"Serialization error: {e}")
raise
def loads(self, s: str, is_binary: bool = False) -> Any:
try:
if is_binary:
return bytes.fromhex(s)
return super().loads(s)
except Exception as e:
logger.error(f"Deserialization error: {e}")
raise
def initialize_sync_pool(
host: str = "localhost", port: int = 6379, db: int = 0, **kwargs
) -> redis.ConnectionPool:
"""Initialize a synchronous Redis connection pool."""
try:
pool = redis.ConnectionPool(host=host, port=port, db=db, **kwargs)
logger.info(
f"Synchronous Redis pool initialized with host={host}, port={port}, db={db}"
)
return pool
except Exception as e:
logger.error(f"Error initializing sync pool: {e}")
raise
def initialize_async_pool(
url: str = "redis://localhost", **kwargs
) -> AsyncConnectionPool:
"""Initialize an asynchronous Redis connection pool."""
try:
pool = AsyncConnectionPool.from_url(url, **kwargs)
logger.info(f"Asynchronous Redis pool initialized with url={url}")
return pool
except Exception as e:
logger.error(f"Error initializing async pool: {e}")
raise
@contextmanager
def _get_sync_connection(
connection: Union[redis.Redis, redis.ConnectionPool, None]
) -> Generator[redis.Redis, None, None]:
conn = None
try:
if isinstance(connection, redis.Redis):
yield connection
elif isinstance(connection, redis.ConnectionPool):
conn = redis.Redis(connection_pool=connection)
yield conn
else:
raise ValueError("Invalid sync connection object.")
except redis.ConnectionError as e:
logger.error(f"Sync connection error: {e}")
raise
finally:
if conn:
conn.close()
@asynccontextmanager
async def _get_async_connection(
connection: Union[AsyncRedis, AsyncConnectionPool, None]
) -> AsyncGenerator[AsyncRedis, None]:
conn = None
try:
if isinstance(connection, AsyncRedis):
yield connection
elif isinstance(connection, AsyncConnectionPool):
conn = AsyncRedis(connection_pool=connection)
yield conn
else:
raise ValueError("Invalid async connection object.")
except redis.ConnectionError as e:
logger.error(f"Async connection error: {e}")
raise
finally:
if conn:
await conn.aclose()
class RedisSaver(BaseCheckpointSaver):
sync_connection: Optional[Union[redis.Redis, redis.ConnectionPool]] = None
async_connection: Optional[Union[AsyncRedis, AsyncConnectionPool]] = None
def __init__(
self,
sync_connection: Optional[Union[redis.Redis, redis.ConnectionPool]] = None,
async_connection: Optional[Union[AsyncRedis, AsyncConnectionPool]] = None,
):
super().__init__(serde=JsonAndBinarySerializer())
self.sync_connection = sync_connection
self.async_connection = async_connection
def put(
self,
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
) -> RunnableConfig:
thread_id = config["configurable"]["thread_id"]
parent_ts = config["configurable"].get("thread_ts")
key = f"checkpoint:{thread_id}:{checkpoint['ts']}"
try:
with _get_sync_connection(self.sync_connection) as conn:
conn.hset(
key,
mapping={
"checkpoint": self.serde.dumps(checkpoint),
"metadata": self.serde.dumps(metadata),
"parent_ts": parent_ts if parent_ts else "",
},
)
logger.info(
f"Checkpoint stored successfully for thread_id: {thread_id}, ts: {checkpoint['ts']}"
)
except Exception as e:
logger.error(f"Failed to put checkpoint: {e}")
raise
return {
"configurable": {
"thread_id": thread_id,
"thread_ts": checkpoint["ts"],
},
}
async def aput(
self,
config: RunnableConfig,
checkpoint: Checkpoint,
metadata: CheckpointMetadata,
) -> RunnableConfig:
thread_id = config["configurable"]["thread_id"]
parent_ts = config["configurable"].get("thread_ts")
key = f"checkpoint:{thread_id}:{checkpoint['ts']}"
try:
async with _get_async_connection(self.async_connection) as conn:
await conn.hset(
key,
mapping={
"checkpoint": self.serde.dumps(checkpoint),
"metadata": self.serde.dumps(metadata),
"parent_ts": parent_ts if parent_ts else "",
},
)
logger.info(
f"Checkpoint stored successfully for thread_id: {thread_id}, ts: {checkpoint['ts']}"
)
except Exception as e:
logger.error(f"Failed to aput checkpoint: {e}")
raise
return {
"configurable": {
"thread_id": thread_id,
"thread_ts": checkpoint["ts"],
},
}
def get_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
thread_id = config["configurable"]["thread_id"]
thread_ts = config["configurable"].get("thread_ts", None)
try:
with _get_sync_connection(self.sync_connection) as conn:
if thread_ts:
key = f"checkpoint:{thread_id}:{thread_ts}"
else:
all_keys = conn.keys(f"checkpoint:{thread_id}:*")
if not all_keys:
logger.info(f"No checkpoints found for thread_id: {thread_id}")
return None
latest_key = max(all_keys, key=lambda k: k.decode().split(":")[-1])
key = latest_key.decode()
checkpoint_data = conn.hgetall(key)
if not checkpoint_data:
logger.info(f"No valid checkpoint data found for key: {key}")
return None
checkpoint = self.serde.loads(checkpoint_data[b"checkpoint"].decode())
metadata = self.serde.loads(checkpoint_data[b"metadata"].decode())
parent_ts = checkpoint_data.get(b"parent_ts", b"").decode()
parent_config = (
{"configurable": {"thread_id": thread_id, "thread_ts": parent_ts}}
if parent_ts
else None
)
logger.info(
f"Checkpoint retrieved successfully for thread_id: {thread_id}, ts: {thread_ts}"
)
return CheckpointTuple(
config=config,
checkpoint=checkpoint,
metadata=metadata,
parent_config=parent_config,
)
except Exception as e:
logger.error(f"Failed to get checkpoint tuple: {e}")
raise
async def aget_tuple(self, config: RunnableConfig) -> Optional[CheckpointTuple]:
thread_id = config["configurable"]["thread_id"]
thread_ts = config["configurable"].get("thread_ts", None)
try:
async with _get_async_connection(self.async_connection) as conn:
if thread_ts:
key = f"checkpoint:{thread_id}:{thread_ts}"
else:
all_keys = await conn.keys(f"checkpoint:{thread_id}:*")
if not all_keys:
logger.info(f"No checkpoints found for thread_id: {thread_id}")
return None
latest_key = max(all_keys, key=lambda k: k.decode().split(":")[-1])
key = latest_key.decode()
checkpoint_data = await conn.hgetall(key)
if not checkpoint_data:
logger.info(f"No valid checkpoint data found for key: {key}")
return None
checkpoint = self.serde.loads(checkpoint_data[b"checkpoint"].decode())
metadata = self.serde.loads(checkpoint_data[b"metadata"].decode())
parent_ts = checkpoint_data.get(b"parent_ts", b"").decode()
parent_config = (
{"configurable": {"thread_id": thread_id, "thread_ts": parent_ts}}
if parent_ts
else None
)
logger.info(
f"Checkpoint retrieved successfully for thread_id: {thread_id}, ts: {thread_ts}"
)
return CheckpointTuple(
config=config,
checkpoint=checkpoint,
metadata=metadata,
parent_config=parent_config,
)
except Exception as e:
logger.error(f"Failed to get checkpoint tuple: {e}")
raise
def list(
self,
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None,
) -> Generator[CheckpointTuple, None, None]:
thread_id = config["configurable"]["thread_id"] if config else "*"
pattern = f"checkpoint:{thread_id}:*"
try:
with _get_sync_connection(self.sync_connection) as conn:
keys = conn.keys(pattern)
if before:
keys = [
k
for k in keys
if k.decode().split(":")[-1] < before["configurable"]["thread_ts"]
]
keys = sorted(
keys, key=lambda k: k.decode().split(":")[-1], reverse=True
)
if limit:
keys = keys[:limit]
for key in keys:
data = conn.hgetall(key)
if data and "checkpoint" in data and "metadata" in data:
thread_ts = key.decode().split(":")[-1]
yield CheckpointTuple(
config={
"configurable": {
"thread_id": thread_id,
"thread_ts": thread_ts,
}
},
checkpoint=self.serde.loads(data["checkpoint"].decode()),
metadata=self.serde.loads(data["metadata"].decode()),
parent_config={
"configurable": {
"thread_id": thread_id,
"thread_ts": data.get("parent_ts", b"").decode(),
}
}
if data.get("parent_ts")
else None,
)
logger.info(
f"Checkpoint listed for thread_id: {thread_id}, ts: {thread_ts}"
)
except Exception as e:
logger.error(f"Failed to list checkpoints: {e}")
raise
async def alist(
self,
config: Optional[RunnableConfig],
*,
filter: Optional[dict[str, Any]] = None,
before: Optional[RunnableConfig] = None,
limit: Optional[int] = None,
) -> AsyncGenerator[CheckpointTuple, None]:
thread_id = config["configurable"]["thread_id"] if config else "*"
pattern = f"checkpoint:{thread_id}:*"
try:
async with _get_async_connection(self.async_connection) as conn:
keys = await conn.keys(pattern)
if before:
keys = [
k
for k in keys
if k.decode().split(":")[-1] < before["configurable"]["thread_ts"]
]
keys = sorted(
keys, key=lambda k: k.decode().split(":")[-1], reverse=True
)
if limit:
keys = keys[:limit]
for key in keys:
data = await conn.hgetall(key)
if data and "checkpoint" in data and "metadata" in data:
thread_ts = key.decode().split(":")[-1]
yield CheckpointTuple(
config={
"configurable": {
"thread_id": thread_id,
"thread_ts": thread_ts,
}
},
checkpoint=self.serde.loads(data["checkpoint"].decode()),
metadata=self.serde.loads(data["metadata"].decode()),
parent_config={
"configurable": {
"thread_id": thread_id,
"thread_ts": data.get("parent_ts", b"").decode(),
}
}
if data.get("parent_ts")
else None,
)
logger.info(
f"Checkpoint listed for thread_id: {thread_id}, ts: {thread_ts}"
)
except Exception as e:
logger.error(f"Failed to list checkpoints: {e}")
raise