zer0dex 0.0.9__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.
zer0dex/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.9"
zer0dex/cli.py ADDED
@@ -0,0 +1,317 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ zer0dex CLI — Dual-layer memory for AI agents.
4
+
5
+ Commands:
6
+ zer0dex init Initialize a new zer0dex memory store
7
+ zer0dex seed Seed vector store from markdown files
8
+ zer0dex serve Start the memory server
9
+ zer0dex query Query memories from the command line
10
+ zer0dex status Check server health and memory count
11
+ zer0dex add Add a memory manually
12
+ """
13
+ import argparse
14
+ import json
15
+ import subprocess
16
+ import sys
17
+ import urllib.request
18
+ import urllib.error
19
+ from pathlib import Path
20
+
21
+
22
+ DEFAULT_PORT = 18420
23
+ DEFAULT_COLLECTION = "zer0dex"
24
+ DEFAULT_CHROMA_PATH = ".zer0dex"
25
+ DEFAULT_LLM_MODEL = "mistral:7b"
26
+ DEFAULT_EMBED_MODEL = "nomic-embed-text"
27
+ DEFAULT_OLLAMA_URL = "http://localhost:11434"
28
+ DEFAULT_USER_ID = "agent"
29
+
30
+ CONFIG_FILE = ".zer0dex.json"
31
+
32
+
33
+ def load_config():
34
+ """Load config from .zer0dex.json if it exists."""
35
+ p = Path(CONFIG_FILE)
36
+ if p.exists():
37
+ return json.loads(p.read_text())
38
+ return {}
39
+
40
+
41
+ def save_config(config):
42
+ """Save config to .zer0dex.json."""
43
+ Path(CONFIG_FILE).write_text(json.dumps(config, indent=2) + "\n")
44
+
45
+
46
+ def cmd_init(args):
47
+ """Initialize a new zer0dex memory store."""
48
+ config = {
49
+ "collection": args.collection or DEFAULT_COLLECTION,
50
+ "chroma_path": args.chroma_path or DEFAULT_CHROMA_PATH,
51
+ "port": args.port or DEFAULT_PORT,
52
+ "user_id": args.user_id or DEFAULT_USER_ID,
53
+ "llm_model": DEFAULT_LLM_MODEL,
54
+ "embed_model": DEFAULT_EMBED_MODEL,
55
+ "ollama_url": DEFAULT_OLLAMA_URL,
56
+ }
57
+ save_config(config)
58
+ Path(config["chroma_path"]).mkdir(parents=True, exist_ok=True)
59
+
60
+ print(f"✅ zer0dex initialized")
61
+ print(f" Collection: {config['collection']}")
62
+ print(f" Storage: {config['chroma_path']}")
63
+ print(f" Config: {CONFIG_FILE}")
64
+ print(f"\nNext: zer0dex seed --source your-docs/")
65
+
66
+
67
+ def cmd_seed(args):
68
+ """Seed the vector store from files."""
69
+ config = load_config()
70
+ # Import here to avoid slow startup for other commands
71
+ from zer0dex.seed import collect_files, chunk_markdown
72
+
73
+ try:
74
+ from mem0 import Memory
75
+ except ImportError:
76
+ print("Error: mem0 not installed. Run: pip install mem0ai")
77
+ sys.exit(1)
78
+
79
+ mem_config = {
80
+ "llm": {"provider": "ollama", "config": {"model": config.get("llm_model", DEFAULT_LLM_MODEL), "ollama_base_url": config.get("ollama_url", DEFAULT_OLLAMA_URL)}},
81
+ "embedder": {"provider": "ollama", "config": {"model": config.get("embed_model", DEFAULT_EMBED_MODEL), "ollama_base_url": config.get("ollama_url", DEFAULT_OLLAMA_URL)}},
82
+ "vector_store": {"provider": "chroma", "config": {"collection_name": config.get("collection", DEFAULT_COLLECTION), "path": config.get("chroma_path", DEFAULT_CHROMA_PATH)}},
83
+ }
84
+
85
+ files = collect_files(args.source)
86
+ if not files:
87
+ print("No files found. Use --source <path>")
88
+ sys.exit(1)
89
+
90
+ print(f"Found {len(files)} file(s)")
91
+ all_chunks = []
92
+ for f in files:
93
+ text = f.read_text(encoding="utf-8")
94
+ chunks = chunk_markdown(text)
95
+ all_chunks.extend(chunks)
96
+ print(f" {f.name}: {len(chunks)} chunks")
97
+
98
+ if args.dry_run:
99
+ print(f"\n[DRY RUN] Would seed {len(all_chunks)} chunks. Exiting.")
100
+ return
101
+
102
+ print(f"\nLoading mem0...")
103
+ memory = Memory.from_config(mem_config)
104
+ user_id = config.get("user_id", DEFAULT_USER_ID)
105
+
106
+ total = 0
107
+ for i, chunk in enumerate(all_chunks, 1):
108
+ print(f" Seeding {i}/{len(all_chunks)}...", end=" ", flush=True)
109
+ result = memory.add(chunk, user_id=user_id)
110
+ n = len(result.get("results", []))
111
+ total += n
112
+ print(f"({n} memories)")
113
+
114
+ all_mem = memory.get_all(user_id=user_id)
115
+ final = len(all_mem.get("results", []))
116
+ print(f"\n✅ Seeded {total} memories. Total in store: {final}")
117
+
118
+
119
+ def cmd_check(args):
120
+ """Validate prerequisites before init or seed."""
121
+ config = load_config()
122
+ ollama_url = config.get("ollama_url", DEFAULT_OLLAMA_URL)
123
+ llm_model = config.get("llm_model", DEFAULT_LLM_MODEL)
124
+ embed_model = config.get("embed_model", DEFAULT_EMBED_MODEL)
125
+ all_ok = True
126
+
127
+ # 1. Ollama running
128
+ try:
129
+ resp = urllib.request.urlopen(f"{ollama_url}/api/tags", timeout=5)
130
+ tags_data = json.loads(resp.read())
131
+ print(f"✅ Ollama is running at {ollama_url}")
132
+
133
+ # 2. Required models present
134
+ available = [m.get("name", "") for m in tags_data.get("models", [])]
135
+ for model in [embed_model, llm_model]:
136
+ # Match by prefix (e.g. "mistral:7b" matches "mistral:7b-instruct")
137
+ found = any(m == model or m.startswith(model.split(":")[0] + ":") for m in available)
138
+ if found:
139
+ print(f"✅ Model present: {model}")
140
+ else:
141
+ print(f"❌ Model missing: {model} (run: ollama pull {model})")
142
+ all_ok = False
143
+
144
+ except urllib.error.URLError:
145
+ print(f"❌ Ollama not reachable at {ollama_url} (run: ollama serve)")
146
+ print(f"❌ Model check skipped: {embed_model}")
147
+ print(f"❌ Model check skipped: {llm_model}")
148
+ all_ok = False
149
+
150
+ # 3. mem0ai importable
151
+ try:
152
+ import mem0 # noqa: F401
153
+ print("✅ mem0ai is importable")
154
+ except ImportError:
155
+ print("❌ mem0ai not installed (run: pip install mem0ai)")
156
+ all_ok = False
157
+
158
+ # 4. chromadb importable
159
+ try:
160
+ import chromadb # noqa: F401
161
+ print("✅ chromadb is importable")
162
+ except ImportError:
163
+ print("❌ chromadb not installed (run: pip install chromadb)")
164
+ all_ok = False
165
+
166
+ if not all_ok:
167
+ sys.exit(1)
168
+
169
+
170
+ def cmd_serve(args):
171
+ """Start the memory server."""
172
+ config = load_config()
173
+ port = args.port or config.get("port", DEFAULT_PORT)
174
+
175
+ # Build server args
176
+ server_args = [
177
+ sys.executable, "-m", "zer0dex.server",
178
+ "--port", str(port),
179
+ "--collection", config.get("collection", DEFAULT_COLLECTION),
180
+ "--chroma-path", config.get("chroma_path", DEFAULT_CHROMA_PATH),
181
+ "--user-id", config.get("user_id", DEFAULT_USER_ID),
182
+ "--llm-model", config.get("llm_model", DEFAULT_LLM_MODEL),
183
+ "--embed-model", config.get("embed_model", DEFAULT_EMBED_MODEL),
184
+ "--ollama-url", config.get("ollama_url", DEFAULT_OLLAMA_URL),
185
+ ]
186
+
187
+ if args.background:
188
+ proc = subprocess.Popen(server_args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
189
+ print(f"✅ zer0dex server started (PID {proc.pid}, port {port})")
190
+ else:
191
+ subprocess.run(server_args)
192
+
193
+
194
+ def cmd_query(args):
195
+ """Query the running server."""
196
+ config = load_config()
197
+ port = args.port or config.get("port", DEFAULT_PORT)
198
+ url = f"http://127.0.0.1:{port}/query"
199
+ data = json.dumps({"text": args.text, "limit": args.limit}).encode()
200
+
201
+ try:
202
+ req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
203
+ resp = urllib.request.urlopen(req, timeout=5)
204
+ result = json.loads(resp.read())
205
+ memories = result.get("memories", [])
206
+ if not memories:
207
+ print("No relevant memories found.")
208
+ return
209
+ for m in memories:
210
+ score = m.get("score", 0)
211
+ text = m.get("text", "")
212
+ print(f" [{score:.3f}] {text}")
213
+ except urllib.error.URLError:
214
+ print(f"Error: zer0dex server not running on port {port}. Run: zer0dex serve")
215
+ sys.exit(1)
216
+
217
+
218
+ def cmd_status(args):
219
+ """Check server health."""
220
+ config = load_config()
221
+ port = args.port or config.get("port", DEFAULT_PORT)
222
+ url = f"http://127.0.0.1:{port}/health"
223
+
224
+ try:
225
+ resp = urllib.request.urlopen(url, timeout=3)
226
+ result = json.loads(resp.read())
227
+ print(f"✅ zer0dex running on port {port}")
228
+ print(f" Memories: {result.get('count', '?')}")
229
+ print(f" Status: {result.get('status', '?')}")
230
+ except urllib.error.URLError:
231
+ print(f"❌ zer0dex not running on port {port}")
232
+ sys.exit(1)
233
+
234
+
235
+ def cmd_add(args):
236
+ """Add a memory via the server."""
237
+ config = load_config()
238
+ port = args.port or config.get("port", DEFAULT_PORT)
239
+ url = f"http://127.0.0.1:{port}/add"
240
+ data = json.dumps({"text": args.text}).encode()
241
+
242
+ try:
243
+ req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
244
+ resp = urllib.request.urlopen(req, timeout=30)
245
+ result = json.loads(resp.read())
246
+ count = result.get("count", 0)
247
+ memories = result.get("memories", [])
248
+ print(f"✅ Added {count} memory(ies):")
249
+ for m in memories:
250
+ print(f" • {m}")
251
+ except urllib.error.URLError:
252
+ print(f"Error: zer0dex server not running on port {port}. Run: zer0dex serve")
253
+ sys.exit(1)
254
+
255
+
256
+ def main():
257
+ parser = argparse.ArgumentParser(
258
+ prog="zer0dex",
259
+ description="Dual-layer memory for AI agents. 91% recall, 70ms, $0/month.",
260
+ )
261
+ sub = parser.add_subparsers(dest="command")
262
+
263
+ # check
264
+ sub.add_parser("check", help="Validate prerequisites (Ollama, models, mem0ai, chromadb)")
265
+
266
+ # init
267
+ p_init = sub.add_parser("init", help="Initialize a new memory store")
268
+ p_init.add_argument("--collection", help="Collection name")
269
+ p_init.add_argument("--chroma-path", help="ChromaDB storage path")
270
+ p_init.add_argument("--port", type=int, help="Server port")
271
+ p_init.add_argument("--user-id", help="User ID for memories")
272
+
273
+ # seed
274
+ p_seed = sub.add_parser("seed", help="Seed from markdown files")
275
+ p_seed.add_argument("--source", action="append", required=True, help="Source file or directory")
276
+ p_seed.add_argument("--dry-run", action="store_true", help="Show what would be seeded")
277
+ p_seed.add_argument("--port", type=int)
278
+
279
+ # serve
280
+ p_serve = sub.add_parser("serve", help="Start memory server")
281
+ p_serve.add_argument("--port", type=int, help="Server port")
282
+ p_serve.add_argument("--background", "-b", action="store_true", help="Run in background")
283
+
284
+ # query
285
+ p_query = sub.add_parser("query", help="Query memories")
286
+ p_query.add_argument("text", help="Query text")
287
+ p_query.add_argument("--limit", type=int, default=5, help="Max results")
288
+ p_query.add_argument("--port", type=int)
289
+
290
+ # status
291
+ p_status = sub.add_parser("status", help="Check server health")
292
+ p_status.add_argument("--port", type=int)
293
+
294
+ # add
295
+ p_add = sub.add_parser("add", help="Add a memory")
296
+ p_add.add_argument("text", help="Memory text")
297
+ p_add.add_argument("--port", type=int)
298
+
299
+ args = parser.parse_args()
300
+ if not args.command:
301
+ parser.print_help()
302
+ sys.exit(1)
303
+
304
+ commands = {
305
+ "check": cmd_check,
306
+ "init": cmd_init,
307
+ "seed": cmd_seed,
308
+ "serve": cmd_serve,
309
+ "query": cmd_query,
310
+ "status": cmd_status,
311
+ "add": cmd_add,
312
+ }
313
+ commands[args.command](args)
314
+
315
+
316
+ if __name__ == "__main__":
317
+ main()
zer0dex/seed.py ADDED
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Seed mem0 vector store from markdown files.
4
+ Reads files, splits into chunks, and feeds to mem0 for extraction + embedding.
5
+
6
+ Usage:
7
+ python seed.py --source MEMORY.md --source memory/ [--collection my_agent] [--chroma-path ./.mem0_chroma]
8
+ """
9
+ import argparse
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from mem0 import Memory
15
+
16
+
17
+ def build_config(args):
18
+ return {
19
+ "llm": {
20
+ "provider": "ollama",
21
+ "config": {
22
+ "model": args.llm_model,
23
+ "ollama_base_url": args.ollama_url,
24
+ },
25
+ },
26
+ "embedder": {
27
+ "provider": "ollama",
28
+ "config": {
29
+ "model": args.embed_model,
30
+ "ollama_base_url": args.ollama_url,
31
+ },
32
+ },
33
+ "vector_store": {
34
+ "provider": "chroma",
35
+ "config": {
36
+ "collection_name": args.collection,
37
+ "path": args.chroma_path,
38
+ },
39
+ },
40
+ }
41
+
42
+
43
+ def collect_files(sources):
44
+ """Collect all .md files from source paths (files or directories)."""
45
+ files = []
46
+ for source in sources:
47
+ p = Path(source)
48
+ if p.is_file():
49
+ files.append(p)
50
+ elif p.is_dir():
51
+ files.extend(sorted(p.glob("**/*.md")))
52
+ else:
53
+ print(f"Warning: {source} not found, skipping", file=sys.stderr)
54
+ return files
55
+
56
+
57
+ def chunk_markdown(text, max_chunk=2000):
58
+ """Split markdown text into chunks at section boundaries."""
59
+ sections = []
60
+ current = []
61
+ for line in text.split("\n"):
62
+ if line.startswith("## ") and current:
63
+ sections.append("\n".join(current))
64
+ current = [line]
65
+ else:
66
+ current.append(line)
67
+ if current:
68
+ sections.append("\n".join(current))
69
+
70
+ # Further split large sections
71
+ chunks = []
72
+ for section in sections:
73
+ if len(section) <= max_chunk:
74
+ chunks.append(section)
75
+ else:
76
+ words = section.split()
77
+ chunk = []
78
+ length = 0
79
+ for word in words:
80
+ if length + len(word) + 1 > max_chunk and chunk:
81
+ chunks.append(" ".join(chunk))
82
+ chunk = [word]
83
+ length = len(word)
84
+ else:
85
+ chunk.append(word)
86
+ length += len(word) + 1
87
+ if chunk:
88
+ chunks.append(" ".join(chunk))
89
+ return [c for c in chunks if c.strip()]
90
+
91
+
92
+ def main():
93
+ parser = argparse.ArgumentParser(description="Seed zer0dex vector store")
94
+ parser.add_argument("--source", action="append", required=True, help="Source file or directory (can specify multiple)")
95
+ parser.add_argument("--collection", default="zer0dex", help="ChromaDB collection name")
96
+ parser.add_argument("--chroma-path", default=".zer0dex", help="ChromaDB storage path")
97
+ parser.add_argument("--user-id", default="agent", help="mem0 user ID")
98
+ parser.add_argument("--llm-model", default="mistral:7b", help="Ollama LLM model for extraction")
99
+ parser.add_argument("--embed-model", default="nomic-embed-text", help="Ollama embedding model")
100
+ parser.add_argument("--ollama-url", default="http://localhost:11434", help="Ollama base URL")
101
+ parser.add_argument("--dry-run", action="store_true", help="Show what would be seeded without writing")
102
+ args = parser.parse_args()
103
+
104
+ files = collect_files(args.source)
105
+ if not files:
106
+ print("No files found to seed.")
107
+ sys.exit(1)
108
+
109
+ print(f"Found {len(files)} file(s) to seed:")
110
+ for f in files:
111
+ print(f" {f}")
112
+
113
+ all_chunks = []
114
+ for f in files:
115
+ text = f.read_text(encoding="utf-8")
116
+ chunks = chunk_markdown(text)
117
+ all_chunks.extend(chunks)
118
+ print(f" {f.name}: {len(chunks)} chunks")
119
+
120
+ print(f"\nTotal: {len(all_chunks)} chunks")
121
+
122
+ if args.dry_run:
123
+ print("\n[DRY RUN] Would seed the above chunks. Exiting.")
124
+ sys.exit(0)
125
+
126
+ config = build_config(args)
127
+ print(f"\nLoading mem0 (collection: {args.collection})...")
128
+ memory = Memory.from_config(config)
129
+
130
+ total_extracted = 0
131
+ for i, chunk in enumerate(all_chunks, 1):
132
+ print(f" Seeding chunk {i}/{len(all_chunks)}...", end=" ", flush=True)
133
+ result = memory.add(chunk, user_id=args.user_id)
134
+ extracted = len(result.get("results", []))
135
+ total_extracted += extracted
136
+ print(f"({extracted} memories extracted)")
137
+
138
+ all_mem = memory.get_all(user_id=args.user_id)
139
+ final_count = len(all_mem.get("results", []))
140
+ print(f"\nDone. {total_extracted} memories extracted. Total in store: {final_count}")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
zer0dex/server.py ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ zer0dex Memory Server
4
+ Keeps mem0 loaded in memory, responds to queries in ~70ms avg.
5
+
6
+ Endpoints:
7
+ POST /query {"text": "...", "limit": 5} → {"memories": [...]}
8
+ POST /add {"text": "..."} → {"count": N}
9
+ GET /health → {"status": "ok", "count": N}
10
+
11
+ Usage:
12
+ python server.py [--port 18420] [--collection my_agent] [--chroma-path ./.mem0_chroma]
13
+ """
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from http.server import HTTPServer, BaseHTTPRequestHandler
18
+
19
+ from mem0 import Memory
20
+
21
+
22
+ def build_config(args):
23
+ return {
24
+ "llm": {
25
+ "provider": "ollama",
26
+ "config": {
27
+ "model": args.llm_model,
28
+ "ollama_base_url": args.ollama_url,
29
+ },
30
+ },
31
+ "embedder": {
32
+ "provider": "ollama",
33
+ "config": {
34
+ "model": args.embed_model,
35
+ "ollama_base_url": args.ollama_url,
36
+ },
37
+ },
38
+ "vector_store": {
39
+ "provider": "chroma",
40
+ "config": {
41
+ "collection_name": args.collection,
42
+ "path": args.chroma_path,
43
+ },
44
+ },
45
+ }
46
+
47
+
48
+ class Mem0Handler(BaseHTTPRequestHandler):
49
+ memory = None
50
+ user_id = None
51
+ min_score = 0.3
52
+
53
+ def log_message(self, format, *args):
54
+ pass # suppress request logging
55
+
56
+ def _send_json(self, data, status=200):
57
+ body = json.dumps(data).encode()
58
+ self.send_response(status)
59
+ self.send_header("Content-Type", "application/json")
60
+ self.send_header("Content-Length", str(len(body)))
61
+ self.end_headers()
62
+ self.wfile.write(body)
63
+
64
+ def _read_body(self):
65
+ content_length = int(self.headers.get("Content-Length", 0))
66
+ raw = self.rfile.read(content_length)
67
+ try:
68
+ return json.loads(raw) if raw else {}
69
+ except json.JSONDecodeError:
70
+ return None
71
+
72
+ def do_GET(self):
73
+ if self.path == "/health":
74
+ all_mem = self.memory.get_all(user_id=self.user_id)
75
+ count = len(all_mem.get("results", []))
76
+ self._send_json({"status": "ok", "count": count})
77
+ else:
78
+ self._send_json({"error": "not found"}, 404)
79
+
80
+ def do_POST(self):
81
+ data = self._read_body()
82
+ if data is None:
83
+ self._send_json({"error": "invalid json"}, 400)
84
+ return
85
+
86
+ if self.path == "/query":
87
+ text = data.get("text", "")
88
+ limit = data.get("limit", 5)
89
+ min_score = data.get("min_score", self.min_score)
90
+ if not text or len(text.strip()) < 3:
91
+ self._send_json({"memories": []})
92
+ return
93
+
94
+ results = self.memory.search(text, user_id=self.user_id, limit=limit)
95
+ memories = []
96
+ for mem in results.get("results", []):
97
+ score = mem.get("score", 0)
98
+ if score > min_score:
99
+ memories.append({
100
+ "text": mem.get("memory", ""),
101
+ "score": round(score, 3),
102
+ })
103
+ self._send_json({"memories": memories})
104
+
105
+ elif self.path == "/add":
106
+ text = data.get("text", "")
107
+ if not text:
108
+ self._send_json({"error": "no text"}, 400)
109
+ return
110
+ result = self.memory.add(text, user_id=self.user_id)
111
+ extracted = result.get("results", [])
112
+ self._send_json({
113
+ "count": len(extracted),
114
+ "memories": [m.get("memory", "") for m in extracted],
115
+ })
116
+
117
+ else:
118
+ self._send_json({"error": "not found"}, 404)
119
+
120
+
121
+ def main():
122
+ parser = argparse.ArgumentParser(description="zer0dex Memory Server")
123
+ parser.add_argument("--port", type=int, default=18420, help="Server port (default: 18420)")
124
+ parser.add_argument("--collection", default="zer0dex", help="ChromaDB collection name")
125
+ parser.add_argument("--chroma-path", default=".zer0dex", help="ChromaDB storage path")
126
+ parser.add_argument("--user-id", default="agent", help="mem0 user ID")
127
+ parser.add_argument("--llm-model", default="mistral:7b", help="Ollama LLM model for extraction")
128
+ parser.add_argument("--embed-model", default="nomic-embed-text", help="Ollama embedding model")
129
+ parser.add_argument("--ollama-url", default="http://localhost:11434", help="Ollama base URL")
130
+ parser.add_argument("--min-score", type=float, default=0.3, help="Minimum relevance score")
131
+ args = parser.parse_args()
132
+
133
+ config = build_config(args)
134
+ print(f"Loading mem0 (collection: {args.collection})...", flush=True)
135
+ memory = Memory.from_config(config)
136
+ all_mem = memory.get_all(user_id=args.user_id)
137
+ count = len(all_mem.get("results", []))
138
+ print(f"Ready — {count} memories, serving on port {args.port}", flush=True)
139
+
140
+ Mem0Handler.memory = memory
141
+ Mem0Handler.user_id = args.user_id
142
+ Mem0Handler.min_score = args.min_score
143
+
144
+ server = HTTPServer(("127.0.0.1", args.port), Mem0Handler)
145
+ try:
146
+ server.serve_forever()
147
+ except KeyboardInterrupt:
148
+ print("\nServer stopped.")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
@@ -0,0 +1,237 @@
1
+ Metadata-Version: 2.4
2
+ Name: zer0dex
3
+ Version: 0.0.9
4
+ Summary: Dual-layer memory for AI agents. Compressed index + vector store. 91% recall, 70ms, $0/month.
5
+ Author-email: Rolando Bosch <rbosch@hermes-labs.ai>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/roli-lpci/zer0dex
8
+ Project-URL: Documentation, https://hermes-labs.ai/zer0dex
9
+ Project-URL: Repository, https://github.com/roli-lpci/zer0dex
10
+ Project-URL: Issues, https://github.com/roli-lpci/zer0dex/issues
11
+ Keywords: rag,memory,ai-agents,llm,vector-store,mem0
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: mem0ai>=0.1.0
21
+ Requires-Dist: chromadb>=1.0.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=7.0; extra == "dev"
24
+ Dynamic: license-file
25
+
26
+ # zer0dex
27
+
28
+ **A token-efficient memory architecture for persistent AI agents.**
29
+
30
+ zer0dex combines a compressed human-readable index with a local vector store to give AI agents long-term memory that outperforms both flat files and traditional RAG.
31
+
32
+ ## Results (n=97)
33
+
34
+ | Architecture | Recall | ≥75% Pass Rate | Cross-Reference |
35
+ |---|---|---|---|
36
+ | Flat File Only | 52.2% | 41% | 70.0% |
37
+ | Full RAG | 80.3% | 77% | 37.5% |
38
+ | **zer0dex** | **91.2%** | **87%** | **80.0%** |
39
+
40
+ **Zero losses** in head-to-head comparison. 70ms latency. $0/month (fully local).
41
+
42
+ ## The Problem
43
+
44
+ Persistent AI agents need memory across sessions. Current approaches all have gaps:
45
+
46
+ - **Flat files** (MEMORY.md, etc.) — cheap on tokens but poor retrieval. The agent has to "know what it knows."
47
+ - **Full RAG** (vector store only) — good retrieval but poor cross-referencing. Facts are "floating" with no structure.
48
+ - **MemGPT/Letta** — powerful but complex. The LLM manages its own memory paging, adding latency and cost.
49
+
50
+ ## The Architecture
51
+
52
+ zer0dex uses two layers:
53
+
54
+ ### Layer 1: Compressed Index (MEMORY.md)
55
+
56
+ A human-readable markdown file (~3KB) that acts as a **semantic table of contents**. It tells the agent *what categories of knowledge exist* without storing full details.
57
+
58
+ ```markdown
59
+ ## Products
60
+ - **Little Canary** — prompt injection detection, 99% on TensorTrust
61
+ - mem0 topics: Little Canary, prompt injection, HERM
62
+ ```
63
+
64
+ This index is always in context (~782 tokens). It provides **navigational scaffolding** — the agent knows where knowledge lives.
65
+
66
+ ### Layer 2: Vector Store (mem0 + chromadb)
67
+
68
+ A semantic fact store containing extracted details from daily logs, conversations, and curated notes. Queried via embedding similarity on every inbound message.
69
+
70
+ ### The Hook: Automatic Pre-Message Injection
71
+
72
+ A lightweight HTTP server keeps the vector store warm in memory. Every inbound message triggers a semantic query (70ms), and the top 5 relevant memories are injected into the agent's context automatically. No judgment call. No forgetting.
73
+
74
+ ```
75
+ User: "How's the Suy Sideguy deployment going?"
76
+ ↓
77
+ Hook queries mem0 → finds: "Suy: watching PID 76977, qwen3:4b judge"
78
+ ↓
79
+ Agent sees: [message] + [Suy context from mem0] + [MEMORY.md index]
80
+ ↓
81
+ Agent responds with specific details it otherwise wouldn't have
82
+ ```
83
+
84
+ ## Why It Works
85
+
86
+ The compressed index solves the **cross-reference problem**. When a user asks "How does X relate to Y?", vector similarity finds X *or* Y, rarely both. But the compressed index contains cross-domain pointers — it's like a hyperlinked table of contents. The LLM uses the index to bridge domains that vector similarity alone can't connect.
87
+
88
+ | Query Type | Full RAG | zer0dex | Gap |
89
+ |---|---|---|---|
90
+ | Direct recall | 84.3% | 92.1% | +7.8pp |
91
+ | Cross-reference | 37.5% | 80.0% | **+42.5pp** |
92
+ | Negative (rejection) | 100% | 100% | 0pp |
93
+
94
+ ## Quick Start
95
+
96
+ ### Requirements
97
+
98
+ - Python 3.11+
99
+ - [Ollama](https://ollama.ai) with `nomic-embed-text` and `mistral:7b`
100
+ - 8GB+ RAM
101
+
102
+ ### Install
103
+
104
+ ```bash
105
+ pip install zer0dex
106
+
107
+ # Pull embedding + extraction models
108
+ ollama pull nomic-embed-text
109
+ ollama pull mistral:7b
110
+ ```
111
+
112
+ ### 1. Create Your Compressed Index
113
+
114
+ Create a `MEMORY.md` file — a compressed summary of what your agent knows:
115
+
116
+ ```markdown
117
+ # Agent Memory Index
118
+
119
+ ## User
120
+ - Name: Alice
121
+ - Role: ML Engineer
122
+ - Topics in mem0: Alice, preferences, projects
123
+
124
+ ## Projects
125
+ - **ProjectX** — NLP pipeline, deadline March 15
126
+ - Topics in mem0: ProjectX, NLP, deadlines
127
+ ```
128
+
129
+ ### 2. Initialize and Seed
130
+
131
+ ```bash
132
+ zer0dex init
133
+ zer0dex check # validate Ollama, models, deps
134
+ zer0dex seed --source MEMORY.md --source memory/
135
+ ```
136
+
137
+ ### 3. Start the Memory Server
138
+
139
+ ```bash
140
+ zer0dex serve
141
+ ```
142
+
143
+ ### 4. Integrate with Your Agent
144
+
145
+ The server exposes a simple HTTP API:
146
+
147
+ ```bash
148
+ # Query
149
+ curl -X POST http://localhost:18420/query \
150
+ -H "Content-Type: application/json" \
151
+ -d '{"text": "What is ProjectX?", "limit": 5}'
152
+
153
+ # Add memory
154
+ curl -X POST http://localhost:18420/add \
155
+ -H "Content-Type: application/json" \
156
+ -d '{"text": "ProjectX deadline moved to March 20"}'
157
+
158
+ # Health check
159
+ curl http://localhost:18420/health
160
+ ```
161
+
162
+ For automatic injection, add a pre-message hook in your agent framework that queries the server before every LLM call.
163
+
164
+ ## Evaluation
165
+
166
+ Run the evaluation suite yourself:
167
+
168
+ ```bash
169
+ python eval/evaluate.py --memories 86 --test-cases 97
170
+ ```
171
+
172
+ See [eval/README.md](eval/README.md) for methodology and detailed results.
173
+
174
+ ## Architecture Diagram
175
+
176
+ ```
177
+ ┌─────────────────────────────────────────────────┐
178
+ │ Agent Context │
179
+ │ │
180
+ │ ┌──────────────┐ ┌───────────────────────┐ │
181
+ │ │ MEMORY.md │ │ mem0 Results (auto) │ │
182
+ │ │ (compressed │ │ [injected by hook] │ │
183
+ │ │ index) │ │ │ │
184
+ │ │ ~782 tokens │ │ ~104 tokens │ │
185
+ │ └──────────────┘ └───────────────────────┘ │
186
+ │ ↑ ↑ │
187
+ │ Always loaded Pre-message hook │
188
+ │ at session start queries on every msg │
189
+ └─────────────────────────────────────────────────┘
190
+ ↑
191
+ ┌─────────────────┐
192
+ │ mem0 HTTP Server │
193
+ │ (port 18420) │
194
+ │ 70ms avg query │
195
+ └─────────────────┘
196
+ ↑
197
+ ┌─────────────────┐
198
+ │ chromadb │
199
+ │ (local vector │
200
+ │ store) │
201
+ └─────────────────┘
202
+ ```
203
+
204
+ ## How It Compares
205
+
206
+ | Feature | Flat Files | Full RAG | MemGPT/Letta | **zer0dex** |
207
+ |---|---|---|---|---|
208
+ | Recall | 52% | 80% | ~80%* | **91%** |
209
+ | Cross-reference | 70% | 38% | Unknown | **80%** |
210
+ | Latency | 0ms | ~15ms | ~500ms+ | **70ms** |
211
+ | Token overhead | 782 | 104 | Variable | **886** |
212
+ | Cost/month | $0 | $0-50 | $0-50 | **$0** |
213
+ | Complexity | Trivial | Moderate | High | **Low** |
214
+ | Auto-retrieval | No | On-demand | LLM-managed | **Every message** |
215
+
216
+ *MemGPT recall estimated; no published head-to-head comparison available.
217
+
218
+ ## Citation
219
+
220
+ ```bibtex
221
+ @misc{bosch2026zer0dex,
222
+ title={zer0dex: Dual-Layer Memory Architecture for Persistent AI Agents},
223
+ author={Bosch, Rolando},
224
+ year={2026},
225
+ url={https://github.com/roli-lpci/zer0dex}
226
+ }
227
+ ```
228
+
229
+ ## License
230
+
231
+ Apache 2.0
232
+
233
+ ## Credits
234
+
235
+ Built by [Hermes Labs](https://hermes-labs.ai) as part of LPCI (Linguistically Persistent Cognitive Interface) research.
236
+
237
+ Uses [mem0](https://mem0.ai) for vector storage, [chromadb](https://www.trychroma.com/) for the vector database, and [Ollama](https://ollama.ai) for local embeddings/extraction.
@@ -0,0 +1,10 @@
1
+ zer0dex/__init__.py,sha256=46Yjk3fz9o8aTN8E95McnzpJcjGzVJmHmQqUZ5mXzfc,22
2
+ zer0dex/cli.py,sha256=wWyOcQu60MtWvwPkKAjeqEpWHkxNgLPqYn0BLWNsqEY,10991
3
+ zer0dex/seed.py,sha256=qnOV5Dn3nO6soE2hdRx1JFlZI9CjZpohMzfuUbLPzcc,4716
4
+ zer0dex/server.py,sha256=1gXDlyKEnpTjyjlkPLtWQlMbQx08H30YdrcroRPXKig,5219
5
+ zer0dex-0.0.9.dist-info/licenses/LICENSE,sha256=xcNAVv5LLZAq1leD0P4wml-gwMXv1ailOZTUgmBhMH4,821
6
+ zer0dex-0.0.9.dist-info/METADATA,sha256=E0Yx0AJ7yS1baUJXBCae1fd7gayPUmy-abanemUz9tE,8416
7
+ zer0dex-0.0.9.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ zer0dex-0.0.9.dist-info/entry_points.txt,sha256=2A_ECzzGAqwmPWfqAdqOZZadRP_of-XC93PSOnbj4dg,45
9
+ zer0dex-0.0.9.dist-info/top_level.txt,sha256=RgtEpBOViZQQRmksaxc-7Q5sONAViMWCJzeBbNC1E3Y,8
10
+ zer0dex-0.0.9.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zer0dex = zer0dex.cli:main
@@ -0,0 +1,19 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ Copyright 2026 Rolando Bosch / Hermes Labs
8
+
9
+ Licensed under the Apache License, Version 2.0 (the "License");
10
+ you may not use this file except in compliance with the License.
11
+ You may obtain a copy of the License at
12
+
13
+ http://www.apache.org/licenses/LICENSE-2.0
14
+
15
+ Unless required by applicable law or agreed to in writing, software
16
+ distributed under the License is distributed on an "AS IS" BASIS,
17
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ See the License for the specific language governing permissions and
19
+ limitations under the License.
@@ -0,0 +1 @@
1
+ zer0dex