-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpython_uteke.py
More file actions
643 lines (526 loc) Β· 19.3 KB
/
Copy pathpython_uteke.py
File metadata and controls
643 lines (526 loc) Β· 19.3 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
"""UtekeMemory β Python wrapper for the Uteke memory engine CLI.
Python wrapper for the uteke CLI binary. Wraps ``uteke`` via
subprocess calls with JSON output parsing. Covers **all** CLI commands
including namespace isolation, tag management, memory aging, and diagnostics.
Usage:
from python_uteke import UtekeMemory
mem = UtekeMemory()
mid = mem.remember("Deploy v2.1 to staging", tags=["deploy", "staging"])
results = mem.recall("deployment steps")
mem.forget(mid)
No external dependencies β stdlib only. Requires Python 3.8+.
"""
import json
import os
import subprocess
import tempfile
from typing import Any, Dict, List, Optional
class UtekeError(Exception):
"""Error from the Uteke CLI.
Attributes:
returncode: Exit code of the CLI process (``-1`` if unavailable).
"""
def __init__(self, message: str, returncode: int = -1) -> None:
super().__init__(message)
self.returncode = returncode
class UtekeMemory:
"""Python wrapper for Uteke memory engine β used by AI agents.
All methods invoke the ``uteke`` CLI binary with ``--json`` and parse
the structured output. The binary is resolved from ``$UTEKE_BIN`` env
var or ``$PATH``.
Args:
store_path: Path to the Uteke store directory.
Defaults to ``~/.uteke``.
namespace: Default namespace for multi-agent isolation.
Can be overridden per-method. Defaults to ``None``
(uses CLI default of ``"default"``).
"""
def __init__(
self,
store_path: str = "~/.uteke",
namespace: Optional[str] = None,
) -> None:
self.store_path = os.path.expanduser(store_path)
self._namespace = namespace
self._uteke_bin = os.environ.get("UTEKE_BIN", "uteke")
# ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββββββββ
def _ns_args(self, namespace: Optional[str]) -> List[str]:
"""Build namespace flag list.
Args:
namespace: Per-call namespace override. Falls back to the
instance-level ``_namespace`` if ``None``.
Returns:
``["--namespace", name]`` or ``[]``.
"""
ns = namespace if namespace is not None else self._namespace
return ["--namespace", ns] if ns else []
def _run(self, args: List[str]) -> str:
"""Run a uteke CLI command with ``--json`` and return stdout.
Args:
args: Command and flags to pass after the global options.
Returns:
Stripped stdout from the CLI process.
Raises:
UtekeError: If the CLI exits non-zero or times out (30 s).
"""
cmd = [self._uteke_bin, "--json", "--store", self.store_path] + args
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True,
timeout=30,
)
except subprocess.CalledProcessError as exc:
stderr = exc.stderr.strip() if exc.stderr else ""
raise UtekeError(
f"uteke {' '.join(args)} failed: {stderr}",
returncode=exc.returncode,
) from exc
except subprocess.TimeoutExpired as exc:
raise UtekeError(
f"uteke {' '.join(args)} timed out after 30s"
) from exc
return result.stdout.strip()
@staticmethod
def _parse_json(raw: str) -> Any:
"""Parse JSON string, raising UtekeError on failure.
Args:
raw: JSON text returned by the CLI.
Returns:
Parsed Python object (dict, list, β¦).
Raises:
UtekeError: On invalid JSON.
"""
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
raise UtekeError(f"Invalid JSON from uteke: {exc}") from exc
# ββ Core memories ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def remember(
self,
content: str,
tags: Optional[List[str]] = None,
namespace: Optional[str] = None,
) -> str:
"""Store a memory, return its ID.
Args:
content: The text to remember.
tags: Optional list of tag strings.
namespace: Namespace override.
Returns:
The UUID of the created memory.
"""
args = self._ns_args(namespace) + ["remember", content]
if tags:
args.extend(["--tags", ",".join(tags)])
data = self._parse_json(self._run(args))
return data["id"]
def recall(
self,
query: str,
limit: int = 5,
tags: Optional[List[str]] = None,
namespace: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Semantic search for relevant memories.
Args:
query: Natural-language query.
limit: Maximum results to return.
tags: Optional tag filter.
namespace: Namespace override.
Returns:
List of result dicts with ``memory`` and ``score`` keys.
"""
args = self._ns_args(namespace) + [
"recall", query, "--limit", str(limit),
]
if tags:
args.extend(["--tags", ",".join(tags)])
return self._parse_json(self._run(args))
def search(
self,
query: str,
limit: int = 10,
tags: Optional[List[str]] = None,
namespace: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Full-text keyword search.
Args:
query: Keywords to search for.
limit: Maximum results to return.
tags: Optional tag filter.
namespace: Namespace override.
Returns:
List of result dicts with ``memory`` and ``score`` keys.
"""
args = self._ns_args(namespace) + [
"search", query, "--limit", str(limit),
]
if tags:
args.extend(["--tags", ",".join(tags)])
return self._parse_json(self._run(args))
def list(
self,
tag: Optional[str] = None,
limit: int = 20,
offset: int = 0,
namespace: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""List memories with optional tag filter.
Args:
tag: Optional tag to filter by.
limit: Maximum results.
offset: Pagination offset.
namespace: Namespace override.
Returns:
List of memory dicts.
"""
args = self._ns_args(namespace) + [
"list", "--limit", str(limit), "--offset", str(offset),
]
if tag:
args.extend(["--tag", tag])
return self._parse_json(self._run(args))
def get(
self,
memory_id: str,
namespace: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Get a single memory by ID.
Args:
memory_id: UUID of the memory.
namespace: Namespace override.
Returns:
Memory dict, or ``None`` if not found.
"""
try:
return self._parse_json(
self._run(self._ns_args(namespace) + ["get", memory_id])
)
except UtekeError:
return None
def forget(
self,
memory_id: str,
namespace: Optional[str] = None,
) -> bool:
"""Delete a memory.
Args:
memory_id: UUID of the memory to delete.
namespace: Namespace override.
Returns:
``True`` if deletion succeeded.
"""
try:
data = self._parse_json(
self._run(
self._ns_args(namespace)
+ ["forget", "--confirm", memory_id]
)
)
return data.get("forgotten") == memory_id
except UtekeError:
return False
def stats(
self,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Get store statistics.
Args:
namespace: Namespace override.
Returns:
Dict with ``total_memories``, ``unique_tags``, ``db_size_bytes``, etc.
"""
return self._parse_json(
self._run(self._ns_args(namespace) + ["stats"])
)
# ββ Consolidate & Prune ββββββββββββββββββββββββββββββββββββββββββββββ
def consolidate(
self,
threshold: float = 0.90,
dry_run: bool = False,
namespace: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Find and optionally merge near-duplicate memories.
Args:
threshold: Similarity threshold (0.0β1.0). Defaults to ``0.90``.
dry_run: If ``True``, report candidates without merging.
namespace: Namespace override.
Returns:
List of merge-candidate dicts when ``dry_run`` is set,
or a summary dict otherwise.
"""
args = self._ns_args(namespace) + [
"consolidate", "--threshold", str(threshold),
]
if dry_run:
args.append("--dry-run")
return self._parse_json(self._run(args))
def prune(
self,
ttl_days: int = 30,
dry_run: bool = False,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Prune deprecated memories older than a TTL.
Args:
ttl_days: Age in days after which memories are deprecated.
Defaults to ``30``.
dry_run: If ``True``, report candidates without deleting.
namespace: Namespace override.
Returns:
Dict with ``pruned``, ``candidates``, etc.
"""
args = self._ns_args(namespace) + ["prune", "--ttl", str(ttl_days)]
if dry_run:
args.append("--dry-run")
return self._parse_json(self._run(args))
# ββ Namespace management ββββββββββββββββββββββββββββββββββββββββββββ
def namespace_list(self) -> List[Dict[str, Any]]:
"""List all namespaces with memory counts.
Returns:
List of dicts each containing at least ``name`` and
``memory_count``.
"""
return self._parse_json(self._run(["namespace", "list"]))
def namespace_switch(self, name: str) -> None:
"""Set the default namespace in the Uteke config.
Args:
name: Namespace name to set as default.
"""
self._run(["namespace", "switch", name])
def namespace_stats(self, name: str) -> Dict[str, Any]:
"""Show statistics for a specific namespace.
Args:
name: Namespace name.
Returns:
Stats dict for the requested namespace.
"""
return self._parse_json(self._run(["namespace", "stats", name]))
# ββ Tag management ββββββββββββββββββββββββββββββββββββββββββββββββββ
def tags_list(
self,
namespace: Optional[str] = None,
by_count: bool = False,
) -> List[Dict[str, Any]]:
"""List all tags with usage counts.
Args:
namespace: Namespace override.
by_count: Sort by count (descending) instead of alphabetical.
Returns:
List of tag dicts with ``tag`` and ``count`` keys.
"""
args = self._ns_args(namespace) + ["tags", "list"]
if by_count:
args.append("--by-count")
return self._parse_json(self._run(args))
def tags_rename(
self,
old: str,
new: str,
namespace: Optional[str] = None,
) -> int:
"""Rename a tag across all memories.
Args:
old: Current tag name.
new: New tag name.
namespace: Namespace override.
Returns:
Number of memories updated.
"""
data = self._parse_json(
self._run(
self._ns_args(namespace) + ["tags", "rename", old, new]
)
)
return int(data.get("renamed", data.get("count", 0)))
def tags_delete(
self,
tag: str,
namespace: Optional[str] = None,
) -> int:
"""Delete a tag from all memories.
Args:
tag: Tag name to delete.
namespace: Namespace override.
Returns:
Number of memories affected.
"""
data = self._parse_json(
self._run(
self._ns_args(namespace)
+ ["tags", "delete", "--confirm", tag]
)
)
return int(data.get("deleted", data.get("count", 0)))
# ββ Memory aging βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def aging_status(
self,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Show aging status: hot, warm, cold, never-accessed counts.
Args:
namespace: Namespace override.
Returns:
Dict with aging tier counts.
"""
return self._parse_json(
self._run(self._ns_args(namespace) + ["aging", "status"])
)
def aging_preview(
self,
namespace: Optional[str] = None,
days: int = 180,
) -> List[Dict[str, Any]]:
"""Preview memories eligible for cleanup (dry-run).
Args:
namespace: Namespace override.
days: Minimum age in days. Defaults to ``180``.
Returns:
List of memory dicts that would be cleaned up.
"""
return self._parse_json(
self._run(
self._ns_args(namespace)
+ ["aging", "preview", "--older-than-days", str(days)]
)
)
def aging_cleanup(
self,
namespace: Optional[str] = None,
days: int = 180,
) -> Dict[str, Any]:
"""Delete aged memories.
Args:
namespace: Namespace override.
days: Minimum age in days. Defaults to ``180``.
Returns:
Dict with ``deleted`` count and details.
"""
return self._parse_json(
self._run(
self._ns_args(namespace)
+ [
"aging", "cleanup",
"--older-than-days", str(days),
"--yes",
]
)
)
# ββ Diagnostics βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def doctor(self) -> Dict[str, Any]:
"""Check system health (DB, index, model, consistency).
Returns:
Health-check dict with ``ok``, ``checks``, etc.
"""
return self._parse_json(self._run(["doctor"]))
def verify(
self,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Verify DB and index consistency.
Args:
namespace: Namespace override.
Returns:
Dict with ``consistent`` (bool) and optional ``issues`` list.
"""
return self._parse_json(
self._run(self._ns_args(namespace) + ["verify"])
)
def repair(
self,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Repair index by rebuilding from SQLite.
Args:
namespace: Namespace override.
Returns:
Dict with ``repaired`` count and details.
"""
return self._parse_json(
self._run(self._ns_args(namespace) + ["repair"])
)
# ββ Import / Export βββββββββββββββββββββββββββββββββββββββββββββββββ
def export(
self,
path: str,
namespace: Optional[str] = None,
) -> None:
"""Export all memories to a JSONL file.
Writes portable JSONL (no embeddings) to *path*.
Args:
path: Destination file path.
namespace: Namespace override.
"""
self._run(self._ns_args(namespace) + ["export", path])
def import_from(
self,
path: str,
namespace: Optional[str] = None,
) -> Dict[str, Any]:
"""Import memories from a JSONL file (re-embeds content).
Args:
path: Source JSONL file path.
namespace: Namespace override.
Returns:
Dict with ``imported`` count and details.
"""
return self._parse_json(
self._run(self._ns_args(namespace) + ["import", path])
)
# ββ Standalone smoke test βββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
with tempfile.TemporaryDirectory(prefix="uteke_smoke_") as tmpdir:
mem = UtekeMemory(store_path=tmpdir)
print(f"Store: {tmpdir}")
# remember
mid = mem.remember(
"Hello from Python wrapper", tags=["test", "smoke"]
)
print(f"Remembered: {mid}")
# recall
results = mem.recall("hello python")
print(f"Recall results: {len(results)}")
# search (with tags)
results = mem.search("Python", tags=["test"])
print(f"Search results (tag=test): {len(results)}")
# list
items = mem.list(tag="smoke")
print(f"List (tag=smoke): {len(items)}")
# get
got = mem.get(mid)
print(f"Get: {got['content'] if got else 'NOT FOUND'}")
# stats
s = mem.stats()
print(f"Stats: {s['total_memories']} memories")
# tags_list
tags = mem.tags_list()
print(f"Tags: {[t.get('tag', t) for t in tags]}")
# doctor
doc = mem.doctor()
statuses = {c["status"] for c in doc.get("checks", [])}
print(f"Doctor: all ok = {statuses == {'Ok'}}")
# forget
ok = mem.forget(mid)
print(f"Forget: {ok}")
assert ok, "forget should return True"
# stats after forget
s = mem.stats()
assert s["total_memories"] == 0, (
f"Expected 0 memories after forget, got {s['total_memories']}"
)
print(f"Stats after forget: {s['total_memories']} memories")
# namespace support β remember in an isolated namespace
mem_ns = UtekeMemory(store_path=tmpdir, namespace="smoke-ns")
mid_ns = mem_ns.remember("Namespace isolated memory", tags=["ns"])
print(f"Remembered in namespace: {mid_ns}")
results_ns = mem_ns.recall("namespace")
print(f"Recall in namespace: {len(results_ns)}")
stats_ns = mem_ns.stats()
print(f"Namespace stats: {stats_ns['total_memories']} memories")
ok_ns = mem_ns.forget(mid_ns)
print(f"Forget in namespace: {ok_ns}")
assert ok_ns, "forget in namespace should return True"
print("β Smoke test passed")