langgraph-store-antfly 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Antfly persistence for LangGraph long-term memory (not checkpoints)."""
2
+
3
+ from .store import AntflyStore
4
+
5
+ __all__ = ["AntflyStore"]
File without changes
@@ -0,0 +1,513 @@
1
+ """Persistent LangGraph memory with component-safe namespaces.
2
+
3
+ Batches execute sequentially in input order: later reads observe completed earlier
4
+ writes. A mixed batch is not a transaction. Cancellation does not roll back writes.
5
+ TTL is deliberately unsupported. Clients supplied by callers remain caller-owned.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import copy
12
+ import inspect
13
+ import json
14
+ import math
15
+ import operator
16
+ from collections.abc import Iterable
17
+ from datetime import UTC, datetime
18
+ from typing import Any
19
+ from urllib.parse import quote
20
+
21
+ from langchain_antfly._utils import hits, request, response_dict, run_async, write
22
+ from langgraph.store.base import (
23
+ BaseStore,
24
+ GetOp,
25
+ Item,
26
+ ListNamespacesOp,
27
+ PutOp,
28
+ SearchItem,
29
+ SearchOp,
30
+ validate_op_namespace,
31
+ )
32
+ from langgraph.store.base.embed import ensure_embeddings, get_text_at_path
33
+
34
+
35
+ def _encode(value: str) -> str:
36
+ return base64.urlsafe_b64encode(value.encode()).decode().rstrip("=")
37
+
38
+
39
+ def _prefix(namespace: tuple[str, ...]) -> str:
40
+ return "lg1/" + "".join(_encode(part) + "/" for part in namespace)
41
+
42
+
43
+ def _key(namespace: tuple[str, ...], key: str) -> str:
44
+ return _prefix(namespace) + "!" + _encode(key)
45
+
46
+
47
+ def _json(value: Any) -> Any:
48
+ return json.loads(json.dumps(value, allow_nan=False, ensure_ascii=False))
49
+
50
+
51
+ def _namespace(namespace: tuple[str, ...]) -> None:
52
+ from langgraph.store.base import InvalidNamespaceError
53
+
54
+ validate_op_namespace(GetOp(namespace, ""))
55
+ if not isinstance(namespace, tuple) or not namespace or namespace[0] == "langgraph":
56
+ raise InvalidNamespaceError("Use a nonempty tuple namespace whose root is not 'langgraph'")
57
+
58
+
59
+ def _equal(left: Any, right: Any) -> bool:
60
+ if isinstance(left, bool) or isinstance(right, bool):
61
+ return type(left) is type(right) and left == right
62
+ if isinstance(left, dict) and isinstance(right, dict):
63
+ return left.keys() == right.keys() and all(_equal(left[key], right[key]) for key in left)
64
+ if isinstance(left, list) and isinstance(right, list):
65
+ return len(left) == len(right) and all(_equal(a, b) for a, b in zip(left, right, strict=True))
66
+ return left == right
67
+
68
+
69
+ def _matches(value: dict[str, Any], filters: dict[str, Any] | None) -> bool:
70
+ for name, condition in (filters or {}).items():
71
+ actual: Any = value
72
+ for part in name.split("."):
73
+ if not isinstance(actual, dict) or part not in actual:
74
+ actual = None
75
+ break
76
+ actual = actual[part]
77
+ if not isinstance(condition, dict) or not any(str(k).startswith("$") for k in condition):
78
+ if not _equal(actual, condition):
79
+ return False
80
+ continue
81
+ for op, expected in condition.items():
82
+ if op not in {"$eq", "$ne", "$gt", "$gte", "$lt", "$lte"}:
83
+ raise ValueError(f"Unsupported memory filter operator: {op}")
84
+ try:
85
+ if op not in {"$eq", "$ne"} and (isinstance(actual, bool) or isinstance(expected, bool)):
86
+ return False
87
+ result = {
88
+ "$eq": _equal,
89
+ "$ne": lambda left, right: not _equal(left, right),
90
+ "$gt": operator.gt,
91
+ "$gte": operator.ge,
92
+ "$lt": operator.lt,
93
+ "$lte": operator.le,
94
+ }[op](actual, expected)
95
+ except TypeError:
96
+ result = False
97
+ if not result:
98
+ return False
99
+ return True
100
+
101
+
102
+ class _PreparedEmbeddings:
103
+ """Per-operation vectors prepared on the caller loop, consumed by a worker."""
104
+
105
+ def __init__(self, *, texts=None, vectors=None, query=None, query_vector=None):
106
+ self.texts, self.vectors = texts, vectors
107
+ self.query, self.query_vector = query, query_vector
108
+
109
+ def embed_documents(self, texts):
110
+ if texts != self.texts:
111
+ raise ValueError("Memory document inputs changed after async embedding preparation")
112
+ return self.vectors
113
+
114
+ def embed_query(self, query):
115
+ if query != self.query:
116
+ raise ValueError("Memory query changed after async embedding preparation")
117
+ return self.query_vector
118
+
119
+
120
+ class AntflyStore(BaseStore):
121
+ """LangGraph long-term memory backed by one Antfly table.
122
+
123
+ ``index`` follows LangGraph's IndexConfig: ``dims``, ``embed``, and optional
124
+ ``fields``. Constructors attach; ``create`` provisions a table/index. With no
125
+ index, enumeration and CRUD never load or call an embedding model.
126
+
127
+ Each configured field/array element is embedded separately and memory scores
128
+ use maximum cosine similarity. Namespaces that have ever stored multiple
129
+ vectors use an exact paginated scan with client-side pooling (O(namespace
130
+ records) per semantic search). Other namespaces retain native vector top-k.
131
+ Multifield markers are sticky after deletion/update to preserve correctness
132
+ across processes; they affect performance only, never returned memories.
133
+ Unlike InMemoryStore's optional scoreless remainder, semantic queries exclude
134
+ items with indexing disabled; get and no-query search still return them.
135
+ """
136
+
137
+ supports_ttl = False
138
+ ttl_config = None
139
+
140
+ def __init__(
141
+ self,
142
+ client: Any,
143
+ table: str,
144
+ *,
145
+ index: dict[str, Any] | None = None,
146
+ index_name: str = "memory_vectors",
147
+ page_size: int = 100,
148
+ ):
149
+ if not table or not 1 <= page_size <= 10000:
150
+ raise ValueError("table is required and page_size must be between 1 and 10000")
151
+ if not index_name or "." in index_name:
152
+ raise ValueError("index_name must be nonempty and contain no dots")
153
+ self.client, self.table = client, table
154
+ self.index_name, self.page_size = index_name, page_size
155
+ self.index = dict(index) if index is not None else None
156
+ self.embeddings = None
157
+ self._async_only = False
158
+ if index is not None:
159
+ unknown = set(index) - {"dims", "embed", "fields"}
160
+ if unknown:
161
+ raise ValueError(f"Unknown index options: {sorted(unknown)}")
162
+ if isinstance(index.get("dims"), bool) or not isinstance(index.get("dims"), int) or index["dims"] < 1:
163
+ raise ValueError("index.dims must be a positive integer")
164
+ fields = index.get("fields")
165
+ if fields is not None and (not isinstance(fields, list) or not all(isinstance(f, str) for f in fields)):
166
+ raise ValueError("index.fields must be None or a list of field-path strings")
167
+ self.index["fields"] = ["$"] if fields is None else list(fields)
168
+ embed = index.get("embed")
169
+ self._async_only = inspect.iscoroutinefunction(embed) or (
170
+ callable(embed) and inspect.iscoroutinefunction(embed.__call__)
171
+ )
172
+ self.embeddings = ensure_embeddings(embed)
173
+
174
+ @classmethod
175
+ def create(cls, client: Any, table: str, *, num_shards: int | None = None, **kwargs: Any) -> AntflyStore:
176
+ store = cls(client, table, **kwargs)
177
+ indexes = None
178
+ if store.index:
179
+ indexes = {
180
+ store.index_name: {
181
+ "type": "embeddings",
182
+ "external": True,
183
+ "dimension": store.index["dims"],
184
+ "distance_metric": "cosine",
185
+ }
186
+ }
187
+ client.create_table(table, indexes=indexes, num_shards=num_shards)
188
+ return store
189
+
190
+ def _get(self, namespace: tuple[str, ...], key: str) -> dict[str, Any] | None:
191
+ _namespace(namespace)
192
+ try:
193
+ row = response_dict(self.client.get(self.table, _key(namespace, key)))
194
+ except Exception as error:
195
+ if getattr(error, "status_code", None) == 404:
196
+ self.client.get_table(self.table)
197
+ return None
198
+ raise
199
+ if row.get("codec") != "langgraph-memory-v1":
200
+ raise ValueError("Unsupported Antfly memory codec")
201
+ return row
202
+
203
+ @staticmethod
204
+ def _item(row: dict[str, Any], score: float | None = None, *, search: bool = False) -> Item:
205
+ legacy = row.get("updated_at")
206
+ updated = datetime.fromisoformat(legacy) if isinstance(legacy, str) else legacy
207
+ if "updated_at_us" in row:
208
+ numeric = datetime.fromtimestamp(row["updated_at_us"] / 1_000_000, UTC)
209
+ # Keep the legacy ISO timestamp as a monotonic floor. New writes
210
+ # deliberately retain it, so migration needs no racy read/upsert.
211
+ updated = max(updated, numeric) if updated is not None else numeric
212
+ args = {
213
+ "namespace": tuple(row["namespace"]),
214
+ "key": row["key"],
215
+ "value": copy.deepcopy(row["value"]),
216
+ "created_at": row["created_at"],
217
+ "updated_at": updated,
218
+ }
219
+ return SearchItem(**args, score=score) if search else Item(**args)
220
+
221
+ def _validate_vector(self, vector: Any) -> list[float]:
222
+ assert self.index is not None
223
+ if (
224
+ not isinstance(vector, (list, tuple))
225
+ or len(vector) != self.index["dims"]
226
+ or not all(not isinstance(x, bool) and isinstance(x, (int, float)) for x in vector)
227
+ ):
228
+ raise ValueError("Memory embedding dimension or numeric values are invalid")
229
+ try:
230
+ values = [float(x) for x in vector]
231
+ except (ValueError, OverflowError) as error:
232
+ raise ValueError("Memory embedding values must be finite numbers") from error
233
+ if not all(math.isfinite(x) for x in values):
234
+ raise ValueError("Memory embedding values must be finite numbers")
235
+ if not any(values):
236
+ raise ValueError("Memory embedding vectors must be nonzero")
237
+ return values
238
+
239
+ def _vectors(self, texts: list[str]) -> list[list[float]]:
240
+ assert self.embeddings is not None and self.index is not None
241
+ if self._async_only:
242
+ raise ValueError("Async-only embedding callable requires AntflyStore.aput/abatch")
243
+ vectors = self.embeddings.embed_documents(texts)
244
+ if not isinstance(vectors, (list, tuple)) or len(vectors) != len(texts):
245
+ raise ValueError("Embedding provider returned the wrong number of vectors")
246
+ return [self._validate_vector(vector) for vector in vectors]
247
+
248
+ @staticmethod
249
+ def _cosine(left: list[float], right: list[float]) -> float:
250
+ # Scale before computing the norm so finite large/small vectors do not
251
+ # overflow/underflow. Never assume the provider returns unit vectors.
252
+ left_scale, right_scale = max(map(abs, left)), max(map(abs, right))
253
+ a, b = [x / left_scale for x in left], [x / right_scale for x in right]
254
+ score = math.fsum(x * y for x, y in zip(a, b, strict=True)) / (math.hypot(*a) * math.hypot(*b))
255
+ return max(-1.0, min(1.0, score))
256
+
257
+ @staticmethod
258
+ def _multifield_prefix(namespace: tuple[str, ...]) -> str:
259
+ return _prefix(namespace).replace("lg1/", "lgm1/", 1)
260
+
261
+ def _has_multifield(self, namespace: tuple[str, ...]) -> bool:
262
+ # Sticky markers survive process restarts and per-item field overrides.
263
+ # They are stored atomically with the parent, outside the memory keyspace.
264
+ return bool(hits(self.client.query(self.table, filter_prefix=self._multifield_prefix(namespace), limit=1)))
265
+
266
+ def _multifield_search(self, op: SearchOp, query_vector: list[float]) -> list[SearchItem]:
267
+ ranked = []
268
+ for row in self._rows(op.namespace_prefix):
269
+ if not row.get("indexed") or not _matches(row["value"], op.filter):
270
+ continue
271
+ vectors = row.get("field_vectors")
272
+ if not vectors:
273
+ raise ValueError("Stored memory predates per-field vectors; re-ingest it before multifield search")
274
+ score = max(self._cosine(query_vector, self._validate_vector(vector)) for vector in vectors)
275
+ ranked.append((score, row))
276
+ # Bound retained candidates while scanning every matching namespace
277
+ # page, so max-pooling is exact without loading the whole corpus.
278
+ ranked.sort(key=lambda item: (-item[0], tuple(item[1]["namespace"]), item[1]["key"]))
279
+ del ranked[op.offset + op.limit :]
280
+ return [self._item(row, score, search=True) for score, row in ranked[op.offset : op.offset + op.limit]]
281
+
282
+ def _prepare_put(self, op: PutOp) -> tuple[dict[str, Any] | None, list[str]]:
283
+ _namespace(op.namespace)
284
+ if op.ttl is not None:
285
+ raise NotImplementedError("AntflyStore does not support per-item TTL")
286
+ if op.value is None:
287
+ return None, []
288
+ if (
289
+ op.index is not None
290
+ and op.index is not False
291
+ and (not isinstance(op.index, list) or not all(isinstance(f, str) for f in op.index))
292
+ ):
293
+ raise ValueError("Per-item index must be False or a list of field-path strings")
294
+ value = _json(dict(op.value))
295
+ fields = op.index if isinstance(op.index, list) else (self.index or {}).get("fields", ["$"])
296
+ texts = (
297
+ [text for path in fields for text in get_text_at_path(value, path)]
298
+ if self.index is not None and op.index is not False
299
+ else []
300
+ )
301
+ return value, texts
302
+
303
+ def _put(self, op: PutOp) -> None:
304
+ value, texts = self._prepare_put(op)
305
+ key = _key(op.namespace, op.key)
306
+ if value is None:
307
+ write(self.client, self.table, deletes=[key])
308
+ return
309
+ row = {
310
+ "codec": "langgraph-memory-v1",
311
+ "namespace": list(op.namespace),
312
+ "key": op.key,
313
+ "value": value,
314
+ "indexed": False,
315
+ "field_vectors": [],
316
+ "vector_count": 0,
317
+ }
318
+ vector = None
319
+ if texts:
320
+ vectors = self._vectors(texts)
321
+ vector = vectors[0]
322
+ row["indexed"] = True
323
+ row["field_vectors"] = vectors
324
+ row["vector_count"] = len(vectors)
325
+ # Sample after inference, then preserve monotonic update time even if
326
+ # another writer commits while this request is waiting for transport.
327
+ timestamp = datetime.now(UTC)
328
+ now = timestamp.isoformat()
329
+ operations = [
330
+ {"op": "$setOnInsert", "path": "$.created_at", "value": now},
331
+ {
332
+ "op": "$max",
333
+ "path": "$.updated_at_us",
334
+ "value": int(timestamp.timestamp()) * 1_000_000 + timestamp.microsecond,
335
+ },
336
+ ]
337
+ operations.extend({"op": "$set", "path": "$." + name, "value": val} for name, val in row.items())
338
+ if self.index is not None:
339
+ operations.append({"op": "$set", "path": "$._embeddings." + self.index_name, "value": vector})
340
+ transforms = [{"key": key, "upsert": True, "operations": operations}]
341
+ if row["vector_count"] > 1:
342
+ transforms.append(
343
+ {
344
+ "key": self._multifield_prefix(op.namespace) + "!",
345
+ "upsert": True,
346
+ "operations": [{"op": "$set", "path": "$.multifield", "value": True}],
347
+ }
348
+ )
349
+ write(self.client, self.table, transforms=transforms)
350
+
351
+ def _rows(self, prefix: tuple[str, ...] = ()) -> Iterable[dict[str, Any]]:
352
+ cursor = snapshot = None
353
+ previous_key = None
354
+ while True:
355
+ args = {
356
+ "filter_prefix": _prefix(prefix),
357
+ "limit": self.page_size,
358
+ "order_by": [{"field": "_id", "desc": False}],
359
+ }
360
+ if cursor is not None:
361
+ args["search_after"] = cursor
362
+ args["remote_snapshot"] = snapshot
363
+ response = response_dict(
364
+ request(self.client, "POST", f"/db/v1/tables/{quote(self.table, safe='')}/query", json=args)
365
+ )
366
+ page = hits(response)
367
+ snapshot = response.get("responses", [response])[0].get("remote_snapshot", snapshot)
368
+ if not page:
369
+ return
370
+ for hit in page:
371
+ hit = response_dict(hit)
372
+ key = hit.get("_id")
373
+ if not isinstance(key, str) or previous_key is not None and key <= previous_key:
374
+ raise RuntimeError("Antfly memory pagination did not advance")
375
+ previous_key = key
376
+ row = hit.get("_source", {})
377
+ if row.get("codec") == "langgraph-memory-v1":
378
+ yield row
379
+ if len(page) < self.page_size:
380
+ return
381
+ cursor = response_dict(page[-1]).get("_sort")
382
+ if cursor is None:
383
+ raise RuntimeError("Antfly did not return the sort cursor required for memory pagination")
384
+
385
+ def _search(self, op: SearchOp) -> list[SearchItem]:
386
+ if op.limit < 0 or op.offset < 0:
387
+ raise ValueError("limit and offset must be nonnegative")
388
+ if op.limit == 0:
389
+ return []
390
+ if op.query is None:
391
+ results = []
392
+ matched = 0
393
+ for row in self._rows(op.namespace_prefix):
394
+ if _matches(row["value"], op.filter):
395
+ if matched >= op.offset:
396
+ results.append(self._item(row, search=True))
397
+ matched += 1
398
+ if len(results) >= op.limit:
399
+ break
400
+ return results
401
+ if self.index is None or self.embeddings is None:
402
+ raise ValueError("Semantic memory search requires index configuration")
403
+ if self._async_only:
404
+ raise ValueError("Async-only embedding callable requires AntflyStore.asearch/abatch")
405
+ query_vector = self._validate_vector(self.embeddings.embed_query(op.query))
406
+ if self._has_multifield(op.namespace_prefix):
407
+ return self._multifield_search(op, query_vector)
408
+ # Apply JSON comparison filters before vector candidate selection.
409
+ predicates = [{"term": {"path": "/indexed", "value": True}}]
410
+ exclusions = []
411
+ for name, condition in (op.filter or {}).items():
412
+ path = "/value/" + "/".join(p.replace("~", "~0").replace("/", "~1") for p in name.split("."))
413
+ if isinstance(condition, dict) and any(str(k).startswith("$") for k in condition):
414
+ for operator, expected in condition.items():
415
+ if operator == "$eq":
416
+ predicates.append({"term": {"path": path, "value": expected}})
417
+ elif operator == "$ne":
418
+ exclusions.append({"term": {"path": path, "value": expected}})
419
+ elif operator in {"$gt", "$gte", "$lt", "$lte"}:
420
+ predicates.append({"range": {path: {operator[1:]: expected}}})
421
+ else:
422
+ raise ValueError(f"Unsupported memory filter operator: {operator}")
423
+ else:
424
+ predicates.append({"term": {"path": path, "value": condition}})
425
+ result = self.client.query(
426
+ self.table,
427
+ embeddings={self.index_name: query_vector},
428
+ indexes=[self.index_name],
429
+ filter_prefix=_prefix(op.namespace_prefix),
430
+ filter_query={"conjuncts": predicates},
431
+ exclusion_query={"disjuncts": exclusions} if exclusions else None,
432
+ limit=op.limit + op.offset,
433
+ )
434
+ # A first multifield write can race the initial marker lookup. Since
435
+ # marker and parent commit atomically, checking again after native
436
+ # retrieval prevents returning only its representative field's score.
437
+ if self._has_multifield(op.namespace_prefix):
438
+ return self._multifield_search(op, query_vector)
439
+ selected = []
440
+ for hit in map(response_dict, hits(result)[op.offset : op.offset + op.limit]):
441
+ distance = hit.get("_distance")
442
+ if isinstance(distance, bool) or not isinstance(distance, (int, float)) or not math.isfinite(distance):
443
+ raise ValueError("Antfly memory search did not return a finite cosine distance")
444
+ selected.append(self._item(hit["_source"], 1.0 - distance, search=True))
445
+ return selected
446
+
447
+ def _list(self, op: ListNamespacesOp) -> list[tuple[str, ...]]:
448
+ if op.limit < 0 or op.offset < 0 or op.max_depth is not None and op.max_depth < 1:
449
+ raise ValueError("Invalid namespace listing pagination/depth")
450
+ namespaces = set()
451
+ for row in self._rows():
452
+ ns = tuple(row["namespace"])
453
+ matched = True
454
+ for condition in op.match_conditions or ():
455
+ path = condition.path
456
+ candidate = ns[: len(path)] if condition.match_type == "prefix" else ns[len(ns) - len(path) :]
457
+ if len(candidate) != len(path) or any(
458
+ a != "*" and a != b for a, b in zip(path, candidate, strict=True)
459
+ ):
460
+ matched = False
461
+ break
462
+ if matched:
463
+ namespaces.add(ns[: op.max_depth] if op.max_depth else ns)
464
+ return sorted(namespaces)[op.offset : op.offset + op.limit]
465
+
466
+ def batch(self, ops: Iterable[Any]) -> list[Any]:
467
+ """Execute operations sequentially, preserving order; not atomic as a group."""
468
+ operations = list(ops)
469
+ results = []
470
+ for op in operations:
471
+ validate_op_namespace(op)
472
+ if isinstance(op, PutOp):
473
+ self._put(op)
474
+ results.append(None)
475
+ elif isinstance(op, GetOp):
476
+ row = self._get(op.namespace, op.key)
477
+ results.append(None if row is None else self._item(row))
478
+ elif isinstance(op, SearchOp):
479
+ results.append(self._search(op))
480
+ elif isinstance(op, ListNamespacesOp):
481
+ results.append(self._list(op))
482
+ else:
483
+ raise TypeError(f"Unsupported memory operation: {type(op).__name__}")
484
+ return results
485
+
486
+ async def abatch(self, ops: Iterable[Any]) -> list[Any]:
487
+ """Prepare embeddings on the caller loop, then persist each op in order.
488
+
489
+ No worker waits for an event-loop callback or submits nested work to the
490
+ bounded persistence executor. Async-only providers can safely own loop-
491
+ bound clients/locks; synchronous methods reject those providers clearly.
492
+ """
493
+ results = []
494
+ for original in ops:
495
+ op = copy.deepcopy(original)
496
+ validate_op_namespace(op)
497
+ view = self
498
+ prepared = None
499
+ if self.embeddings is not None:
500
+ if isinstance(op, PutOp):
501
+ _, texts = self._prepare_put(op)
502
+ if texts:
503
+ vectors = await self.embeddings.aembed_documents(texts)
504
+ prepared = _PreparedEmbeddings(texts=texts, vectors=vectors)
505
+ elif isinstance(op, SearchOp) and op.query is not None and op.limit > 0 and op.offset >= 0:
506
+ vector = await self.embeddings.aembed_query(op.query)
507
+ prepared = _PreparedEmbeddings(query=op.query, query_vector=vector)
508
+ if prepared is not None:
509
+ view = copy.copy(self)
510
+ view.embeddings = prepared
511
+ view._async_only = False
512
+ results.extend(await run_async(view.batch, [op]))
513
+ return results
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.5
2
+ Name: langgraph-store-antfly
3
+ Version: 0.1.0
4
+ Summary: Persistent namespaced agent memory backed by Antfly
5
+ Project-URL: Homepage, https://github.com/antflydb/langchain-antfly
6
+ Project-URL: Repository, https://github.com/antflydb/langchain-antfly
7
+ Project-URL: Documentation, https://github.com/antflydb/langchain-antfly#readme
8
+ Project-URL: Changelog, https://github.com/antflydb/langchain-antfly/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/antflydb/langchain-antfly/issues
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,antfly,langgraph,memory,persistence
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: langchain-antfly==0.1.0
20
+ Requires-Dist: langchain-core<2,>=1.4.4
21
+ Requires-Dist: langgraph-checkpoint<5,>=4.3
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Antfly memory for LangGraph
25
+
26
+ Persistent, namespaced long-term memory for LangGraph agents using Antfly.
27
+ Supports sync/async operations, namespace enumeration, filtering and optional
28
+ semantic search. Python 3.11 or newer. Apache-2.0 licensed.
29
+
30
+ **Stable release:** `0.1.0`. Uses the matching stable `langchain-antfly` package
31
+ and published `antfly-sdk>=0.2.1,<0.3`. Antfly `0.3.0-rc.5` is the tested server
32
+ baseline. See the [server setup](https://github.com/antflydb/langchain-antfly#first-result).
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install langgraph-store-antfly==0.1.0
38
+ ```
39
+
40
+ This installs the Python adapters and their dependencies. It does not install or
41
+ start the Antfly server. Plain key/value memory needs no embedding model.
42
+
43
+ ## Remember a preference
44
+
45
+ ```python
46
+ import os
47
+
48
+ from antfly import AntflyClient
49
+ from langgraph_store_antfly import AntflyStore
50
+
51
+ with AntflyClient(
52
+ base_url=os.environ["ANTFLY_URL"], token=os.getenv("ANTFLY_TOKEN")
53
+ ) as client:
54
+ # Create once for this example; on later runs, attach instead.
55
+ store = AntflyStore.create(client=client, table="agent_preferences")
56
+ store.put(("users", "alice"), "drink", {"value": "tea"})
57
+
58
+ # A new instance reads the same persisted records.
59
+ attached = AntflyStore(client=client, table="agent_preferences")
60
+ print(attached.get(("users", "alice"), "drink").value)
61
+ assert attached.get(("users", "bob"), "drink") is None
62
+ ```
63
+
64
+ For cleanup, drop the example's dedicated table with
65
+ `client.drop_table("agent_preferences")` inside the client context. Select
66
+ namespaces from trusted application identity; namespaces separate records but
67
+ do not replace server authorization. Client lifetimes belong to the caller.
68
+
69
+ ## Use inside an agent
70
+
71
+ Pass the store to LangChain's `create_agent(store=...)` and access it in tools
72
+ through `ToolRuntime.store`. The
73
+ [two-user agent example](https://github.com/antflydb/langchain-antfly/blob/main/examples/agent_memory.py)
74
+ demonstrates that composition with trusted user context and sync/async execution.
75
+ Install the example's LangChain and chat-provider dependencies separately.
76
+
77
+ See the [memory recipes](https://github.com/antflydb/langchain-antfly/blob/main/docs/recipes.md)
78
+ for semantic indexing, search, and async operations, and the
79
+ [validation report](https://github.com/antflydb/langchain-antfly/blob/main/docs/validation-report.md)
80
+ for tested versions and restart/isolation evidence.
81
+
82
+ This is long-term memory storage. It does not implement a LangGraph execution
83
+ checkpointer or per-item TTL.
@@ -0,0 +1,7 @@
1
+ langgraph_store_antfly/__init__.py,sha256=vEFVh2GUWr3XGYlXQnrvst78VtQMzq044UzwX_4VfLY,134
2
+ langgraph_store_antfly/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ langgraph_store_antfly/store.py,sha256=xMRM-cXQDAa1dBB0o4U4sao2KeZnB9dfehp33VH3-n8,23604
4
+ langgraph_store_antfly-0.1.0.dist-info/METADATA,sha256=esfOojFEkLhYcawg9LGuDnqFp43me6JrqDFPkhGVFz8,3564
5
+ langgraph_store_antfly-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ langgraph_store_antfly-0.1.0.dist-info/licenses/LICENSE,sha256=5WrqbiubMLEAgyb2BN7kr6jIj0Sm3qfjcZWS7Zh7gMQ,11350
7
+ langgraph_store_antfly-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Antfly Contributors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.