waveflowdb-client 1.0.4__tar.gz → 1.0.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. waveflowdb_client-1.0.6/PKG-INFO +785 -0
  2. waveflowdb_client-1.0.6/README.md +747 -0
  3. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/pyproject.toml +1 -1
  4. waveflowdb_client-1.0.6/waveflowdb_client/__init__.py +107 -0
  5. waveflowdb_client-1.0.6/waveflowdb_client/client.py +2421 -0
  6. waveflowdb_client-1.0.6/waveflowdb_client/cloud_extractors.py +963 -0
  7. waveflowdb_client-1.0.6/waveflowdb_client/config.py +454 -0
  8. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/waveflowdb_client/exceptions.py +16 -0
  9. waveflowdb_client-1.0.6/waveflowdb_client/extractors.py +878 -0
  10. waveflowdb_client-1.0.6/waveflowdb_client/index.py +423 -0
  11. waveflowdb_client-1.0.6/waveflowdb_client/models.py +218 -0
  12. waveflowdb_client-1.0.6/waveflowdb_client/run_utils.py +836 -0
  13. waveflowdb_client-1.0.6/waveflowdb_client/utils.py +1449 -0
  14. waveflowdb_client-1.0.6/waveflowdb_client.egg-info/PKG-INFO +785 -0
  15. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/waveflowdb_client.egg-info/SOURCES.txt +5 -0
  16. waveflowdb_client-1.0.4/PKG-INFO +0 -1047
  17. waveflowdb_client-1.0.4/readme.md +0 -1009
  18. waveflowdb_client-1.0.4/waveflowdb_client/__init__.py +0 -53
  19. waveflowdb_client-1.0.4/waveflowdb_client/client.py +0 -976
  20. waveflowdb_client-1.0.4/waveflowdb_client/config.py +0 -142
  21. waveflowdb_client-1.0.4/waveflowdb_client/models.py +0 -184
  22. waveflowdb_client-1.0.4/waveflowdb_client/utils.py +0 -446
  23. waveflowdb_client-1.0.4/waveflowdb_client.egg-info/PKG-INFO +0 -1047
  24. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/LICENSE +0 -0
  25. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/setup.cfg +0 -0
  26. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/waveflowdb_client.egg-info/dependency_links.txt +0 -0
  27. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/waveflowdb_client.egg-info/requires.txt +0 -0
  28. {waveflowdb_client-1.0.4 → waveflowdb_client-1.0.6}/waveflowdb_client.egg-info/top_level.txt +0 -0
@@ -0,0 +1,785 @@
1
+ Metadata-Version: 2.4
2
+ Name: waveflowdb_client
3
+ Version: 1.0.6
4
+ Summary: VectorLake SDK — Deterministic backend engine powering agent workflows
5
+ Author-email: "agentanalytics.ai" <nitin@agentanalytics.ai>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 agentanalytics.ai
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://agentanalytics.ai
29
+ Project-URL: Documentation, https://www.agentanalytics.ai/docs/waveflow-db
30
+ Keywords: vector db,VECTOR QUERY LANGUAGE,waveflowdb,agentanalytics,VQL
31
+ Requires-Python: >=3.8
32
+ Description-Content-Type: text/markdown
33
+ License-File: LICENSE
34
+ Requires-Dist: requests
35
+ Requires-Dist: numpy
36
+ Requires-Dist: tqdm
37
+ Dynamic: license-file
38
+
39
+ # WaveflowDB SDK — VectorLake Python Client
40
+
41
+ A Python SDK for interacting with **WaveflowDB** and performing **VQL (Vector Query Language)** brace-based semantic retrieval.
42
+
43
+ This SDK provides:
44
+ - Full `Config` management via constructor args, environment variables, or `.env` file
45
+ - A Pinecone/Chroma-style high-level API (`VectorLake` / `Index`) alongside the full low-level `VectorLakeClient`
46
+ - Document ingestion — direct payload mode or batched filesystem mode
47
+ - Document deletion — remove documents from the index by filename
48
+ - Targeted insertion — insert documents at a controlled position in the corpus
49
+ - Intelligent document sync with MD5-based change detection
50
+ - Resumable batch uploads with checkpoint-based recovery (`RESUME=True`)
51
+ - Semantic search and top-matching-doc retrieval with hybrid filtering
52
+ - Namespace and document metadata queries
53
+ - **Custom per-file metadata** — attach your own fields via `files_meta` / `metadatas`, keyed by filename
54
+ - **Automatic filename sanitization** — messy source filenames are cleaned on disk before chunking
55
+ - Structured CSV + JSONL logging for performance, errors, and failed files
56
+ - Simple `{stem}_part{num}.txt` chunk naming for idempotent re-runs
57
+ - **Image & OCR extraction** — local (PyMuPDF + Tesseract) and cloud engines (AWS Textract, GCP Vision, Azure Doc Intelligence, Mathpix, LlamaParse)
58
+ - **Scale-out cluster** — `cluster_controller.py` + `cluster_api.py` for multi-node deployments
59
+
60
+ > **Note:** Parallel and sync processing modes have been removed. Sequential is the default and recommended mode. Streaming suits large OCR-heavy pipelines.
61
+
62
+ ---
63
+
64
+ ## Quick Start
65
+
66
+ ```bash
67
+ pip install waveflowdb_client python-dotenv
68
+ cp .env.example .env # fill in your credentials
69
+ # drop source files into ./upload
70
+ python run.py # ACTION = "add" by default
71
+ ```
72
+
73
+ Or, using the high-level API directly in code:
74
+
75
+ ```python
76
+ from vectorlake import VectorLake
77
+
78
+ vl = VectorLake(api_key="YOUR_API_KEY", user_id="you@company.com")
79
+
80
+ index = vl.Index("support_docs") # namespace — created on first add()
81
+ index.add(files=["faq.pdf", "policy.docx"])
82
+
83
+ results = index.query("what's the refund policy?", top_k=5)
84
+ index.delete(ids=["faq.pdf"])
85
+ ```
86
+
87
+ ---
88
+
89
+ ## Installation
90
+
91
+ ```bash
92
+ pip install waveflowdb_client
93
+ ```
94
+
95
+ Optional extras for richer file support:
96
+
97
+ ```bash
98
+ pip install PyPDF2 python-docx tqdm
99
+ ```
100
+
101
+ Optional extras for local OCR:
102
+
103
+ ```bash
104
+ pip install pymupdf pytesseract # requires Tesseract binary on PATH
105
+ ```
106
+
107
+ Optional extras for cloud OCR (install only the engine you use):
108
+
109
+ ```bash
110
+ pip install boto3 # AWS Textract
111
+ pip install google-cloud-vision # GCP Vision
112
+ pip install azure-ai-documentintelligence # Azure Document Intelligence
113
+ pip install requests # Mathpix + LlamaParse (REST APIs)
114
+ ```
115
+
116
+ ---
117
+
118
+ ## Configuration
119
+
120
+ All settings are read from the environment (or `.env`). Constructor arguments take priority.
121
+
122
+ **`.env` file:**
123
+
124
+ ```
125
+ VECTOR_LAKE_API_KEY=your_api_key_here
126
+ VECTOR_LAKE_HOST=https://waveflow-analytics.com
127
+ USER_ID=your@email.com
128
+ NAMESPACE=your_namespace
129
+ ```
130
+
131
+ **Constructor arguments:**
132
+
133
+ ```python
134
+ from waveflowdb_client import Config, VectorLakeClient
135
+
136
+ cfg = Config(
137
+ api_key="your_api_key_here",
138
+ host="https://waveflow-analytics.com",
139
+ vector_lake_path="/path/to/documents",
140
+ )
141
+ client = VectorLakeClient(cfg)
142
+ ```
143
+
144
+ ### Core environment variables
145
+
146
+ | Env var | Default | Description |
147
+ |---|---|---|
148
+ | `VECTOR_LAKE_API_KEY` | required | API key |
149
+ | `USER_ID` | required | Your user identifier |
150
+ | `NAMESPACE` | required | Target namespace / lake name |
151
+ | `VECTOR_LAKE_HOST` | `https://waveflow-analytics.com` | Server base URL |
152
+ | `VECTOR_LAKE_PATH` | `upload` | Directory containing source files |
153
+ | `VECTOR_LAKE_LOG_DIR` | `logs` | Directory for log files |
154
+ | `VECTOR_LAKE_MAX_FILES_PER_BATCH` | `100` | Max chunk files per upload batch |
155
+ | `VECTOR_LAKE_MAX_BATCH_SIZE_MB` | `1` | Max total batch size in MB |
156
+ | `VECTOR_LAKE_TIMEOUT` | `240` | HTTP request timeout in seconds |
157
+ | `VECTOR_LAKE_MAX_RETRIES` | `2` | Retry attempts on transient errors |
158
+ | `VECTOR_LAKE_ENABLE_OCR` | `true` | Enable local Tesseract OCR |
159
+ | `VECTOR_LAKE_OCR_LANG` | `eng` | Tesseract language code |
160
+ | `VECTOR_LAKE_STREAMING_MINIBATCH_FILES` | `10` | Chunks per streaming minibatch |
161
+ | `VECTOR_LAKE_STREAMING_MINIBATCH_SIZE_MB` | `2` | MB per streaming minibatch |
162
+
163
+ ---
164
+
165
+ ## High-Level API — `VectorLake` / `Index`
166
+
167
+ For most use cases you don't need the low-level client at all. `VectorLake` / `Index` is a thin, Pinecone/Chroma-shaped wrapper over `VectorLakeClient` — same retry, batching, chunking, sanitization, and OCR behaviour underneath.
168
+
169
+ ```python
170
+ from vectorlake import VectorLake
171
+
172
+ vl = VectorLake(api_key="YOUR_API_KEY", user_id="you@company.com")
173
+ index = vl.Index("support_docs")
174
+
175
+ index.add(files=["faq.pdf", "policy.docx"])
176
+ index.add() # every supported file in vector_lake_path
177
+ index.add(documents=["full text..."], ids=["a.txt"]) # in-memory, Chroma-style
178
+
179
+ results = index.query("refund policy", top_k=5)
180
+ index.update(files=["policy.docx"]) # re-index a changed file
181
+ index.delete(ids=["faq.pdf"])
182
+
183
+ index.get() # list documents in this index
184
+ index.describe_index_stats() # namespace metadata
185
+ vl.list_indexes() # every namespace you can see
186
+ vl.health() # is the server up?
187
+ ```
188
+
189
+ `upsert()` is an alias for `add()`.
190
+
191
+ ### Custom metadata via `metadatas`
192
+
193
+ `index.add()` / `index.update()` accept a `metadatas` argument, forwarded to the underlying client's `files_meta`. It accepts two shapes:
194
+
195
+ - **dict, keyed by original filename** — the recommended shape when using `files=` (path mode). Resolved per source file regardless of chunk-splitting or batch-interleaving order:
196
+
197
+ ```python
198
+ index.add(
199
+ files=["report.pdf", "notes.txt"],
200
+ metadatas={
201
+ "report.pdf": {"department": "finance", "year": 2026},
202
+ "notes.txt": {"author": "alice"},
203
+ },
204
+ )
205
+ ```
206
+
207
+ Files not mentioned as a key just get the default `{"filename", "extension", "timestamp"}` stub.
208
+
209
+ - **list, positionally aligned with `documents`/`ids`** — the original in-memory-mode behaviour:
210
+
211
+ ```python
212
+ index.add(
213
+ documents=["full text one", "full text two"],
214
+ ids=["a.txt", "b.txt"],
215
+ metadatas=[{"author": "alice"}, {"author": "bob"}],
216
+ )
217
+ ```
218
+
219
+ A list must be the same length as `documents`, and is not accepted together with `files=` — path mode requires the dict shape, since there's no fixed per-document ordering to align a list against. Passing a list with `files=` raises a `ValueError` explaining this rather than silently dropping your metadata.
220
+
221
+ See [`files_meta` — Custom Metadata](#files_meta--custom-metadata) below for the equivalent behaviour on the low-level `VectorLakeClient`, and [Filename Sanitization](#filename-sanitization) for why the dict is keyed by filename rather than position.
222
+
223
+ ---
224
+
225
+ ## Processing Modes
226
+
227
+ Two upload modes are supported. Set `MODE` at the top of `run.py`.
228
+
229
+ ### `sequential` (default)
230
+
231
+ All source files are chunked to disk first, then batches are uploaded one at a time.
232
+
233
+ - **Resume:** if a run is interrupted, set `RESUME = True` (default). The SDK reads the checkpoint and picks up from the next unprocessed batch.
234
+ - **Re-chunking guard:** each successfully uploaded source file gets an MD5 sidecar. On the next run, if the file is unchanged, chunking and OCR are skipped entirely. If changed, stale chunks are purged and the file is re-extracted automatically.
235
+ - **Manual resume:** set `START_FROM_BATCH = N` to skip the first N−1 batches (ignored when `RESUME = True` and a checkpoint exists).
236
+
237
+ ### `streaming`
238
+
239
+ Extraction and upload are pipelined: the SDK begins uploading the first minibatch as soon as it is ready, while OCR of later files proceeds concurrently. Best for large collections with expensive PDF/image extraction.
240
+
241
+ - **Resume:** completed file stems are stored in the checkpoint. On restart, already-uploaded files are skipped automatically.
242
+ - `start_from_batch` / `end_batch` are not supported in streaming mode.
243
+
244
+ ---
245
+
246
+ ## Checkpointing
247
+
248
+ Checkpoints are written to:
249
+
250
+ ```
251
+ {VECTOR_LAKE_PATH}/chunks/checkpoint_{USER_ID}_{NAMESPACE}_{operation}.json
252
+ ```
253
+
254
+ The filename encodes **user ID**, **namespace**, and **operation type** (`add_docs`, `refresh_docs`, `insert_docs`) so checkpoints for different namespaces or operations are always independent and never collide.
255
+
256
+ **Sequential checkpoint:**
257
+
258
+ ```json
259
+ {
260
+ "last_ok_batch": 14,
261
+ "operation": "add_docs",
262
+ "user_id": "alice_at_example.com",
263
+ "namespace": "finance_q3",
264
+ "mode": "sequential",
265
+ "updated_at": "2025-08-01T10:22:00+00:00"
266
+ }
267
+ ```
268
+
269
+ **Streaming checkpoint:**
270
+
271
+ ```json
272
+ {
273
+ "completed_stems": ["report_2024", "appendix_a"],
274
+ "operation": "add_docs",
275
+ "user_id": "alice_at_example.com",
276
+ "namespace": "finance_q3",
277
+ "mode": "streaming",
278
+ "updated_at": "2025-08-01T10:22:00+00:00"
279
+ }
280
+ ```
281
+
282
+ Checkpoints are **cleared automatically** when a run completes with zero failures. To force a fresh start, set `RESUME = False` or delete the checkpoint file.
283
+
284
+ ---
285
+
286
+ ## Failure Auditing
287
+
288
+ Every failed batch is appended to `logs/failed_files.jsonl`:
289
+
290
+ ```json
291
+ {
292
+ "timestamp": "2025-08-01T10:23:45Z",
293
+ "operation": "add_docs",
294
+ "user_id": "alice_at_example.com",
295
+ "namespace": "finance_q3",
296
+ "batch_num": 7,
297
+ "files": ["report_part3.txt", "report_part4.txt"],
298
+ "error_type": "HTTP_500",
299
+ "error_message": "Internal server error",
300
+ "traceback": null,
301
+ "extra": { "elapsed_ms": 312.4, "processing_time": 0.31 }
302
+ }
303
+ ```
304
+
305
+ Failures are written both from `run.py` and from within `client.py` directly, so every failure path is covered regardless of how the SDK is invoked.
306
+
307
+ ---
308
+
309
+ ## `run.py` — Operations Launcher
310
+
311
+ Set `ACTION` at the top of `run.py`, then run `python run.py`.
312
+
313
+ ```
314
+ run.py
315
+ │
316
+ ├── UPLOAD
317
+ │ ├── "add" — reads all files from VECTOR_LAKE_PATH as new documents
318
+ │ ├── "refresh" — re-chunks and re-uploads existing documents
319
+ │ ├── "update" — alias for "refresh"
320
+ │ ├── "insert" — insert documents at a controlled position
321
+ │ └── "delete" — remove documents by name (requires FILES_TO_DELETE)
322
+ │
323
+ ├── QUERY
324
+ │ └── "query" — semantic search (flat or flat_filter)
325
+ │
326
+ └── INFO
327
+ └── "health" — ping server
328
+ └── "info" — list indexed documents
329
+ ```
330
+
331
+ All upload operations support both **path mode** (reads from `VECTOR_LAKE_PATH`) and **direct mode** (supply `files_name` + `files_data` inline), except `delete` which only needs filenames.
332
+
333
+ ### Key settings in `run.py`
334
+
335
+ ```python
336
+ ACTION = "add" # operation to run
337
+ MODE = "sequential" # "sequential" | "streaming"
338
+ RESUME = True # auto-resume from checkpoint
339
+ START_FROM_BATCH = 1 # ignored when RESUME=True and checkpoint exists
340
+ END_BATCH = None # cap the run; None = run all batches
341
+ FILES_TO_DELETE = [] # required for ACTION="delete"
342
+ ```
343
+
344
+ ---
345
+
346
+ ## Supported File Types
347
+
348
+ | Extension | Processing strategy |
349
+ |---|---|
350
+ | `txt`, `py` | Plain text, paragraph-chunked |
351
+ | `ipynb` | Code cells extracted, paragraph-chunked |
352
+ | `pdf` | Text extracted via PyMuPDF; embedded images OCR'd if enabled |
353
+ | `docx` | Text + inline images extracted; images OCR'd if enabled |
354
+ | `csv` | Row-safe split; header preserved in every chunk |
355
+ | `xlsx` | Multi-section workbook flattened to CSV rows; row-safe split (standard CSV, proper quoting), header preserved in every chunk |
356
+ | `jsonl`, `ndjson` | Record-safe split; each line validated as JSON |
357
+ | `json` | Kept atomic — never split |
358
+ | `png`, `jpg`, `jpeg`, `tiff`, `tif`, `bmp`, `webp` | Full-image OCR via local Tesseract or cloud engine |
359
+
360
+ ---
361
+
362
+ ## Chunk Naming
363
+
364
+ All chunks follow this convention:
365
+
366
+ ```
367
+ {stem}_part{num}.txt
368
+ ```
369
+
370
+ Example — a PDF split into 3 parts:
371
+ ```
372
+ annual_report_part1.txt
373
+ annual_report_part2.txt
374
+ annual_report_part3.txt
375
+ ```
376
+
377
+ Chunks already on disk are **reused on re-run** — the pipeline is idempotent and safe to restart after a crash.
378
+
379
+ ### Filename sanitization
380
+
381
+ Before any file is chunked, the SDK checks the filename against the same rules used by `clean_filename()`: illegal filesystem characters, runs of whitespace, and Windows-reserved names are normalized away. If a source file's name isn't already clean, **the file is renamed on disk, in place**, to its cleaned equivalent — e.g. `"Q3 Report (final).pdf"` → `"Q3_Report_final.pdf"` — before extraction ever runs.
382
+
383
+ This applies automatically in both `sequential` and `streaming` path-mode uploads (`files=` or auto-discovery), and to the file lists `run.py`/`run_add()` build for MD5 change-detection and streaming recovery. You don't need to do anything — but be aware that:
384
+
385
+ - Source filenames in `VECTOR_LAKE_PATH` **will change** the first time a messy-named file is processed.
386
+ - Chunk filenames, `.md5` sidecars, checkpoint entries, and `files_meta.filename` values are always derived from the *clean* name, so everything downstream stays consistent.
387
+ - If a cleaned name would collide with a different, already-existing file, the rename is skipped and a warning is logged — nothing is overwritten.
388
+ - The rename is idempotent: re-running against an already-sanitized directory does nothing.
389
+
390
+ ---
391
+
392
+ ## Image & OCR Extraction
393
+
394
+ OCR-derived text is wrapped in provenance markers inside chunk files:
395
+
396
+ ```
397
+ <<<IMAGE_EXTRACT source="scan.pdf" page=2 image_index=1 method="aws_textract">>>
398
+ ... extracted text ...
399
+ <<<END_IMAGE_EXTRACT>>>
400
+ ```
401
+
402
+ Use the helper functions to work with these markers:
403
+
404
+ ```python
405
+ from waveflowdb_client import strip_image_markers, list_image_regions
406
+
407
+ clean_text = strip_image_markers(chunk_text) # markers removed, OCR text kept
408
+ regions = list_image_regions(chunk_text) # list of {source, page, image_index, method, ocr_text}
409
+ ```
410
+
411
+ ### Local OCR (Tesseract)
412
+
413
+ Enabled by default when `pymupdf` and `pytesseract` are installed.
414
+
415
+ ```python
416
+ cfg = Config(api_key="...", enable_ocr=True, ocr_lang="eng")
417
+ ```
418
+
419
+ ### Cloud OCR Providers
420
+
421
+ | `cloud_ocr_provider` | Provider | Best for |
422
+ |---|---|---|
423
+ | `"aws"` | AWS Textract | Tables, forms, handwriting |
424
+ | `"gcp"` | Google Cloud Vision | Highest accuracy, 100+ languages |
425
+ | `"azure"` | Azure Document Intelligence | Forms, invoices, custom models |
426
+ | `"mathpix"` | Mathpix | Math, scientific papers, LaTeX |
427
+ | `"llama_parse"` | LlamaParse | Complex layouts, MDX |
428
+
429
+ Set `cloud_ocr_strategy="hybrid"` (default) to use local OCR first with cloud fallback. Set `"cloud"` to always use the cloud provider.
430
+
431
+ ```python
432
+ # AWS Textract — hybrid
433
+ cfg = Config(api_key="...", cloud_ocr_provider="aws", aws_region="eu-west-1")
434
+
435
+ # LlamaParse — cloud only
436
+ cfg = Config(
437
+ api_key="...",
438
+ cloud_ocr_provider="llama_parse",
439
+ cloud_ocr_strategy="cloud",
440
+ llama_parse_api_key="...",
441
+ )
442
+ ```
443
+
444
+ ---
445
+
446
+ ## Client API Reference
447
+
448
+ All public methods return a plain `dict` and **never raise** — errors surface as `{"success": False, "error": "...", "message": "..."}`.
449
+
450
+ ### `add_documents`
451
+
452
+ Uploads **new** documents to the index.
453
+
454
+ | Parameter | Type | Default | Description |
455
+ |---|---|---|---|
456
+ | `user_id` | str | required | User identifier |
457
+ | `vector_lake_description` | str | required | Target namespace |
458
+ | `files_name` + `files_data` | List[str] | — | **Direct mode**: names and string contents (equal length) |
459
+ | `files` | List[str] | `None` | **Path mode**: filenames to read from `vector_lake_path` |
460
+ | `start_from_batch` | int | `1` | Resume point for path mode |
461
+ | `end_batch` | int | `None` | Upper batch bound (inclusive) |
462
+ | `processing_mode` | str | `"sequential"` | `"sequential"` or `"streaming"` |
463
+ | `intelligent_segmentation` | bool | `True` | Server-side segmentation |
464
+ | `files_meta` | dict \| List[dict] | `None` | Per-file metadata. **Dict, keyed by original filename** (recommended for path mode — resolved per source file regardless of chunk order) or a positional **list** (legacy — reliable only in direct mode). Auto-generated `{filename, extension, timestamp}` stub used when omitted or unmatched. See [`files_meta` — Custom Metadata](#files_meta--custom-metadata). |
465
+ | `session_id` | str | `None` | Optional session token |
466
+
467
+ ### `refresh_documents`
468
+
469
+ Updates **existing** documents. Stale chunks are purged and regenerated before uploading. Accepts the same parameters as `add_documents`, including the dict/list `files_meta` shapes above.
470
+
471
+ ### `delete_documents`
472
+
473
+ Removes documents by filename. Lightweight metadata call — no chunking required.
474
+
475
+ | Parameter | Type | Default | Description |
476
+ |---|---|---|---|
477
+ | `user_id` | str | required | User identifier |
478
+ | `vector_lake_description` | str | required | Target namespace |
479
+ | `files_name` | List[str] | required | Basenames to delete (at least one) |
480
+ | `session_id` | str | `None` | Optional session token |
481
+
482
+ ### `insert_documents`
483
+
484
+ Inserts documents at a controlled position in the corpus. Supports both path mode and direct mode, matching the calling convention of `add_documents` and `refresh_documents` exactly.
485
+
486
+ | Parameter | Type | Default | Description |
487
+ |---|---|---|---|
488
+ | `user_id` | str | required | User identifier |
489
+ | `vector_lake_description` | str | required | Target namespace |
490
+ | `files_name` + `files_data` | List[str] | — | **Direct mode**: names and string contents |
491
+ | `files` | List[str] | `None` | **Path mode**: filenames from `vector_lake_path` |
492
+ | `start_from_batch` | int | `1` | Resume point for path mode |
493
+ | `end_batch` | int | `None` | Upper batch bound |
494
+ | `processing_mode` | str | `"sequential"` | `"sequential"` or `"streaming"` |
495
+ | `intelligent_segmentation` | bool | `True` | Server-side segmentation |
496
+ | `files_meta` | dict \| List[dict] | `None` | Per-file metadata — same dict/list shapes as `add_documents` |
497
+ | `session_id` | str | `None` | Optional session token |
498
+
499
+ ### `get_matching_docs`
500
+
501
+ Retrieves top-matching document chunks using semantic search with optional hybrid filtering.
502
+
503
+ | Parameter | Type | Default | Description |
504
+ |---|---|---|---|
505
+ | `query` | str | required | Natural language or VQL search query |
506
+ | `user_id` | str | required | User identifier |
507
+ | `vector_lake_description` | str | required | Target namespace |
508
+ | `pattern` | str | `"static"` | `"static"` for indexed docs; `"dynamic"` for inline files |
509
+ | `hybrid_filter` | bool | `False` | Enable keyword hybrid filter. **Required when `search_type` is set** |
510
+ | `search_type` | str | `None` | `"flat"` — full-corpus fusion. `"flat_filter"` — semantic over filtered candidates only |
511
+ | `top_docs` | int | `10` | Maximum chunks to return |
512
+ | `threshold` | float | `0.2` | Similarity score cutoff |
513
+ | `with_data` | bool | `False` | Include raw chunk text in response |
514
+ | `files_name` + `files_data` | List[str] | `None` | Dynamic mode: temporary files to search |
515
+ | `session_id` | str | `None` | Optional session token |
516
+
517
+ ### `health_check`
518
+
519
+ Pings the server and confirms namespace connectivity.
520
+
521
+ ### `get_namespace_details`
522
+
523
+ Returns storage and quota metadata for one or all namespaces belonging to the user.
524
+
525
+ ### `get_docs_information`
526
+
527
+ Returns document-level metadata, optionally filtered by keyword (`keyword`, `threshold=70`).
528
+
529
+ ### `full_corpus_search`
530
+
531
+ Full-text keyword search across all documents. Complements semantic search for exact-match lookups.
532
+
533
+ ---
534
+
535
+ ## Search Modes
536
+
537
+ ### `search_type="flat"` — Full Corpus Fusion
538
+
539
+ Semantic search and hybrid filter run independently across **all** documents, then fused into a single ranked list.
540
+
541
+ ```
542
+ Tier 1: matched BOTH filter and semantic → highest score
543
+ Tier 2: filter match only
544
+ Tier 3: semantic match only (fallback)
545
+ ```
546
+
547
+ Best for: exploratory search, maximum recall.
548
+
549
+ ### `search_type="flat_filter"` — Filtered Semantic Search
550
+
551
+ Hybrid filter runs first as a **hard gate** — only documents that pass are eligible for semantic ranking.
552
+
553
+ Best for: targeted retrieval when filter criteria are strong.
554
+
555
+ ---
556
+
557
+ ## VQL — Vector Query Language
558
+
559
+ Use braces `{…}` to pin your search to documents or passages that contain specific terms.
560
+
561
+ ```python
562
+ QUERY = """select top 5
563
+ where query is "patients with high sodium levels"
564
+ contains {sodium} {(clinical trial)} {PID 555}"""
565
+ ```
566
+
567
+ ### Syntax
568
+
569
+ ```
570
+ {A B} implicit AND: both A and B must match
571
+ {A or B} either A or B
572
+ {(A B) or C} phrase "A B", or term C
573
+ {A} {B} groups combine with implicit AND
574
+ ```
575
+
576
+ ### Structured data filtering (JSON, NDJSON, CSV)
577
+
578
+ Because the tokeniser splits on `:`, `,`, `|`, `=`, you can filter by exact field:value pairs:
579
+
580
+ ```python
581
+ # Log file: find a specific transaction
582
+ QUERY = """select top 1 where query is "event_type"
583
+ contains {transaction_id:c00d7eac-5b86-439e-956b-118583df6d67}"""
584
+
585
+ # CSV: filter by column values
586
+ QUERY = """select top 10 where query is "shipped orders from Delhi"
587
+ contains {status:shipped} {city:Delhi}"""
588
+ ```
589
+
590
+ ### Important rules
591
+
592
+ - Short tokens (≤ 2 chars) and pure numbers are not indexed — use `{context_status_code:400}` not `{400}`
593
+ - Token must appear exactly as written in the source
594
+ - If an entire brace group normalises to empty, it contributes no constraint (not zero results)
595
+ - If no filter hits, the system falls back to full semantic search automatically
596
+
597
+ ---
598
+
599
+ ## `files_meta` — Root File Type Identification
600
+
601
+ Every batch upload automatically attaches a `files_meta` array. Each entry carries at minimum:
602
+
603
+ ```json
604
+ { "filename": "invoice_part1.txt", "extension": "pdf", "timestamp": "2026-08-05T14:22:07+00:00" }
605
+ ```
606
+
607
+ The `extension` field tells the backend the **original source file type** before chunking. This is critical for format-aware indexing — CSV triggers row-level tokenisation, PDF/DOCX use paragraph tokenisation, etc. The SDK resolves this automatically by looking up the source file alongside the chunk on disk.
608
+
609
+ The `timestamp` field is a UTC ISO-8601 string (`YYYY-MM-DDTHH:MM:SS+00:00`) stamped automatically for every file — no configuration needed. All files processed together in the same batch/upload call share one timestamp value, reflecting when that batch was sent. If you supply your own `"timestamp"` key via custom metadata (see below), your value takes precedence over the auto-generated one.
610
+
611
+ ### `files_meta` — Custom Metadata
612
+
613
+ Beyond `filename`/`extension`, you can attach **your own fields** — department, author, tags, whatever your application needs — via the `files_meta` parameter on `add_documents`, `refresh_documents`, `run_insert_path`, and `run_insert_path_direct` (or `metadatas` on the high-level `Index.add()` / `Index.update()`).
614
+
615
+ Two shapes are accepted:
616
+
617
+ **Dict, keyed by original filename** (recommended for path mode):
618
+
619
+ ```python
620
+ client.add_documents(
621
+ user_id="u1",
622
+ vector_lake_description="my_lake",
623
+ files=["report.pdf", "notes.txt"],
624
+ files_meta={
625
+ "report.pdf": {"department": "finance", "year": 2026},
626
+ "notes.txt": {"author": "alice"},
627
+ },
628
+ )
629
+ ```
630
+
631
+ Each chunk's *real source file* is resolved automatically — regardless of how the SDK happens to split it into multiple parts or interleave it with other files across batches — and your dict entry is merged on top of the auto-generated `{"filename", "extension", "timestamp"}` stub. Files you don't mention just get the default stub. Because lookups key off the filename (after [sanitization](#filename-sanitization), if any), this shape is order-independent and safe under any batching strategy, including `streaming` mode.
632
+
633
+ **List, positionally aligned with files/chunks** (legacy):
634
+
635
+ ```python
636
+ client.run_insert_path_direct(
637
+ user_id="u1",
638
+ vector_lake_description="my_lake",
639
+ files_name=["appendix.txt"],
640
+ files_data=["Section A content..."],
641
+ files_meta=[{"filename": "appendix.txt", "extension": "txt", "author": "Bob"}],
642
+ )
643
+ ```
644
+
645
+ Reliable in **direct mode**, where you control the exact `files_name`/`files_data` order yourself. Fragile in path mode, where the SDK controls chunk-splitting and batch interleaving — prefer the dict shape there.
646
+
647
+ `None` (the default) sends only the auto-generated `{"filename", "extension", "timestamp"}` stub for every file.
648
+
649
+ ---
650
+
651
+ ## Log Files
652
+
653
+ | File | Contents |
654
+ |---|---|
655
+ | `logs/run_operations.log` | Full structured log of every run (DEBUG+) |
656
+ | `logs/failed_files.jsonl` | Append-only audit trail of every failed batch |
657
+ | `logs/api_errors.csv` | Per-request API errors with batch correlation |
658
+ | `logs/performance.csv` | Per-request latency, payload size, HTTP status |
659
+ | `logs/skipped_files.csv` | Files skipped due to unsupported extension etc. |
660
+ | `{VECTOR_LAKE_PATH}/chunks/run_<id>.json` | Per-run batch outcome report |
661
+
662
+ ---
663
+
664
+ ## Error Handling
665
+
666
+ All exceptions inherit from `VectorLakeError` and expose `.to_response()`.
667
+
668
+ | Exception | When raised |
669
+ |---|---|
670
+ | `ConfigError` | API key missing or config invalid at init |
671
+ | `ValidationError` | Mismatched `files_name`/`files_data` lengths, mismatched `metadatas`/`documents` lengths, or other pre-flight failures |
672
+ | `InvalidSearchTypeError` | `search_type` not `"flat"` or `"flat_filter"` |
673
+ | `DocumentNotFoundError` | Filename cannot be resolved in the index |
674
+ | `UnsupportedFileTypeError` | File extension not in `allowed_extensions` |
675
+ | `FileProcessingError` | File I/O, encoding, or parsing failure |
676
+ | `APIError` | HTTP 4xx/5xx. Carries `.status_code` and `.response_text` |
677
+ | `ThrottleError` | HTTP 429 rate limit. Carries `.retry_after` |
678
+
679
+ ### Retry and backoff
680
+
681
+ ```
682
+ Request attempt 1
683
+ ├── HTTP 429 → wait Retry-After (or 2^attempt s) → retry
684
+ ├── Timeout → wait 2^attempt s → retry
685
+ ├── ConnError → wait 2^attempt s → retry
686
+ ├── HTTP 4xx/5xx → return error dict immediately (no retry)
687
+ └── Success → return response dict
688
+
689
+ Max retries: 2 (VECTOR_LAKE_MAX_RETRIES)
690
+ ```
691
+
692
+ ---
693
+
694
+ ## Scale-Out Cluster
695
+
696
+ For production deployments, `cluster_controller.py` + `cluster_api.py` act as a transparent reverse proxy. Point your SDK's `host` at the controller — zero changes to any SDK call.
697
+
698
+ ```
699
+ App SDK
700
+ │ POST /upload/add_docs
701
+ ▼
702
+ cluster_api.py (FastAPI, port 8080)
703
+ │
704
+ ├── Upload → UploadRouter → single node (co-located or round-robin)
705
+ └── Query → QueryRouter → fan-out to all nodes holding namespace
706
+ → merge results → return to SDK
707
+ ```
708
+
709
+ ### Quick start
710
+
711
+ ```bash
712
+ pip install fastapi uvicorn httpx
713
+
714
+ # Single node (dev)
715
+ export DEFAULT_NODE_HOST=http://localhost:9000
716
+ export DEFAULT_NODE_API_KEY=sk-dev-key
717
+ python cluster_api.py
718
+
719
+ # Multi-node — nodes.json
720
+ export NODES_FILE=nodes.json
721
+ export NS_INDEX_PATH=namespace_index.json
722
+ python cluster_api.py
723
+ ```
724
+
725
+ ```json
726
+ // nodes.json
727
+ [
728
+ {"id": "vl1", "host": "https://vl1.example.com", "api_key": "sk-1", "weight": 2},
729
+ {"id": "vl2", "host": "https://vl2.example.com", "api_key": "sk-2", "weight": 1}
730
+ ]
731
+ ```
732
+
733
+ ```python
734
+ # SDK — only change is host
735
+ cfg = Config(api_key="your-key", host="http://controller:8080")
736
+ ```
737
+
738
+ ### Proxied endpoints
739
+
740
+ All SDK endpoints are proxied. Upload calls route to one node; query calls fan out to all nodes holding the namespace and merge results (sort by score, de-dup by filename).
741
+
742
+ ### Admin API
743
+
744
+ | Method | Path | Description |
745
+ |---|---|---|
746
+ | `GET` | `/admin/status` | Full cluster snapshot |
747
+ | `GET` | `/admin/nodes` | List registered nodes |
748
+ | `GET` | `/admin/namespaces` | Namespace → node map |
749
+ | `POST` | `/admin/nodes/register` | Register a node at runtime |
750
+ | `DELETE` | `/admin/nodes/{node_id}` | Deregister a node |
751
+
752
+ ---
753
+
754
+ ## Directory Layout
755
+
756
+ ```
757
+ project/
758
+ ├── run.py # launcher — set ACTION here
759
+ ├── .env # credentials (not committed)
760
+ ├── upload/ # source files go here
761
+ │ └── chunks/ # auto-generated: chunk files, MD5 sidecars, checkpoints, run reports
762
+ ├── logs/ # auto-generated: run_operations.log, failed_files.jsonl, CSVs
763
+ └── waveflowdb_client/ # SDK package
764
+ ├── __init__.py
765
+ ├── client.py
766
+ ├── config.py
767
+ ├── exceptions.py
768
+ ├── extractors.py
769
+ ├── index.py # high-level VectorLake / Index facade
770
+ ├── models.py
771
+ ├── run_utils.py
772
+ └── utils.py
773
+ ```
774
+
775
+ ---
776
+
777
+ ## Support
778
+
779
+ For API or platform support, visit: **https://db.agentanalytics.ai**
780
+
781
+ ---
782
+
783
+ ## License
784
+
785
+ Copyright DIBR tech private ltd.