Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions docs/modules/rag.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,14 +362,20 @@ if __name__ == "__main__":
|--------|-------------|------------|--------------|
| `__init__` | Initializes the RAGEngine with RAG and storage configurations. | `config: RAGConfig`, `storage_handler: StorageHandler` | None |
| `read` | Loads and chunks documents into a corpus. | `file_paths`, `exclude_files`, `filter_file_by_suffix`, `merge_by_file`, `show_progress`, `corpus_id` | `Corpus` |
| `add` | Adds nodes to an index for a specific corpus. | `index_type`, `nodes`, `corpus_id` | None |
| `add` | Adds nodes to an index for a specific corpus. | `index_type`, `nodes`, `corpus_id` | Inserted chunk IDs; `[]` on failure |
| `delete` | Deletes nodes or an entire index from a corpus. | `corpus_id`, `index_type`, `node_ids`, `metadata_filters` | None |
| `clear` | Clears indices for a specific corpus or all corpora. | `corpus_id` | None |
| `save` | Saves indices to files or a database. | `output_path`, `corpus_id`, `index_type`, `table` | None |
| `load` | Loads indices from files or a database. | `source`, `corpus_id`, `index_type`, `table` | None |
| `load` | Loads indices from files or a database. | `source`, `corpus_id`, `index_type`, `table` | Loaded chunk IDs |
| `query` | Executes a query and returns processed results. | `query`, `corpus_id`, `query_transforms` | `RagResult` |

## Notes
- **Query Transforms**: The `query` method supports optional query transforms for preprocessing, which can be customized to enhance retrieval (e.g., HyDE, query decomposition).
- **Storage Backend**: Ensure `StorageHandler` is properly configured to handle vector and metadata storage.
- **Warning**: Loading indices multiple times may cause issues (e.g., duplicate node insertion in vector stores). Clear indices before reloading.
- **Corpus ownership**: Each vector index has its own FAISS backend. Chunk IDs may repeat across corpora; querying, updating or deleting one corpus does not affect another. `add(nodes=corpus, ...)` uses the corpus's ID unless an explicit `corpus_id` is supplied.
- **Batch updates**: A repeated chunk ID replaces its prior value; within one batch the final value wins. Embedding or storage failures preserve the previous vector index. Direct `VectorIndexing.insert_nodes` callers receive the error, while `RAGEngine.add` retains its `[]` failure result. Batch related updates to reduce LlamaIndex catalog serialization overhead.
- **Snapshot replacement**: Loading a vector snapshot replaces the selected index, including removal of nodes absent from the snapshot. Repeated loads are safe. Configure the same embedding model, dimensions and modality as the saved data; incompatible snapshots fail before replacing live vector indices.
- **Portable files**: New snapshots use a metadata pointer, immutable JSONL content and a checksum. Keep the referenced files together. Older JSONL/metadata pairs remain readable; saving into their directory upgrades the selected snapshot. Prior content generations remain available for readers already using them, so repeated saves can grow the directory.
- **Database snapshots**: Multiple index types share a versioned payload in the existing corpus row. Saving one type preserves the others, and legacy single-index rows need no schema migration. `StorageHandler.load_index(..., index_type="vector")` selects one payload.
- **Deletion selectors**: Omitting both node selectors deletes the selected index. Explicit empty node IDs or metadata filters select no nodes; an empty corpus selector does not clear all corpora.
- **Graph persistence**: Graph indices retain their external backend lifecycle; the vector rollback guarantees do not imply a distributed transaction with a graph database.
62 changes: 62 additions & 0 deletions evoagentx/rag/indexings/_transaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""A delta journal for the in-memory catalogs used by vector indexing."""
from contextlib import contextmanager
from copy import deepcopy
from typing import Any, Dict, Iterator, Optional, Tuple

from llama_index.core.storage.kvstore.simple_kvstore import SimpleKVStore
from llama_index.core.storage.kvstore.types import DEFAULT_COLLECTION


class JournaledKVStore(SimpleKVStore):
"""Undo writes to node, reference-document and index catalog records.

Only changed keys are retained. In particular, adding a node does not copy
the text/metadata of every existing node. Serialized index records contain
immutable JSON strings, so journaling them does not duplicate that payload.
Reads are detached because LlamaIndex may update nested reference-node lists
while preparing a subsequent put; a shallow read would change live state
before the journal had a chance to capture it.
"""

def __init__(self):
super().__init__()
self._journal: Optional[Dict[Tuple[str, str], Any]] = None

@contextmanager
def transaction(self) -> Iterator[None]:
"""Restore every changed record if the enclosing vector write fails."""
if self._journal is not None:
yield
return
self._journal = {}
try:
yield
except BaseException:
for (collection, key), previous in reversed(list(self._journal.items())):
if previous is None:
super().delete(key, collection=collection)
else:
super().put(key, previous, collection=collection)
raise
finally:
self._journal = None

def _remember(self, key: str, collection: str) -> None:
"""Capture a key's original value once per transaction."""
identity = (collection, key)
if self._journal is not None and identity not in self._journal:
self._journal[identity] = deepcopy(super().get(key, collection=collection))

def get(self, key: str, collection: str = DEFAULT_COLLECTION):
"""Return detached data so nested caller changes cannot bypass journaling."""
return deepcopy(super().get(key, collection=collection))

def put(self, key: str, val: dict, collection: str = DEFAULT_COLLECTION) -> None:
"""Record the prior value before publishing a catalog record."""
self._remember(key, collection)
super().put(key, deepcopy(val), collection=collection)

def delete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool:
"""Record a deletion before removing the catalog record."""
self._remember(key, collection)
return super().delete(key, collection=collection)
Loading