-
Notifications
You must be signed in to change notification settings - Fork 5
feat(indexers): make persisting VectorStore to disk optional #174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lukeroantreeONS
wants to merge
5
commits into
main
Choose a base branch
from
173-make-persisting-a-vectorstore-optional
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+77
β48
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b11f233
feat(indexers): make persisting VectorStore to disk optional, defaultβ¦
lukeroantreeONS fa1ff72
Merge branch 'main' into 173-make-persisting-a-vectorstore-optional
lukeroantreeONS 91d1034
chore(indexers): rename persist_to_disk to skip_save (and reverse logic)
lukeroantreeONS 626fcfb
chore(indexers): update logging around skip_save parameter
lukeroantreeONS d19db24
docs(indexers): Add description of VectorStore saving options
lukeroantreeONS File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -92,6 +92,7 @@ def __init__( # noqa: C901, PLR0912, PLR0913, PLR0915 | |
| output_dir: str | None = None, | ||
| overwrite: bool = False, | ||
| hooks: dict | None = None, | ||
| skip_save: bool = False, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we move the new parameter above hooks, so that its grouped with the relevant other parameters? |
||
| ): | ||
| """Initializes the `VectorStore` object by processing the input CSV file and generating | ||
| vector embeddings. | ||
|
|
@@ -107,9 +108,14 @@ def __init__( # noqa: C901, PLR0912, PLR0913, PLR0915 | |
| Defaults to `None`. | ||
| output_dir (str): [optional] The directory where the `VectorStore` will be saved. | ||
| Defaults to `None`, where input file name will be used. | ||
| Note: ignored if `skip_save=True`. | ||
| overwrite (bool): [optional] If `True`, allows overwriting existing folders with the same name. | ||
| Defaults to `False` to prevent accidental overwrites. | ||
| Note: ignored if `skip_save=True`. | ||
| hooks (dict): [optional] A dictionary of user-defined hooks for preprocessing and postprocessing. Defaults to `None`. | ||
| skip_save (bool): [optional] If `False`, will save the `VectorStore` to disk after creation, if `True`, will | ||
| just keep it in memory (for testing or ephemeral use cases). | ||
| Defaults to `False`. | ||
|
|
||
|
|
||
| Raises: | ||
|
|
@@ -160,28 +166,45 @@ def __init__( # noqa: C901, PLR0912, PLR0913, PLR0915 | |
| self.num_vectors = None | ||
| self.vectoriser_class = vectoriser.__class__.__name__ | ||
| self.hooks = {} if hooks is None else hooks | ||
| self.skip_save = skip_save | ||
|
|
||
| # ---- Output directory handling (filesystem problems) -> ConfigurationError | ||
| try: | ||
| if self.output_dir is None: | ||
| logging.info("No output directory specified, attempting to use input file name as output folder name.") | ||
| normalized_file_name = os.path.basename(os.path.splitext(self.file_name)[0]) | ||
| self.output_dir = os.path.join(normalized_file_name) | ||
|
|
||
| if os.path.isdir(self.output_dir): | ||
| if overwrite: | ||
| shutil.rmtree(self.output_dir) | ||
| else: | ||
| raise ConfigurationError( | ||
| "Output directory already exists. Pass overwrite=True to overwrite the folder.", | ||
| context={"output_dir": self.output_dir}, | ||
| if self.output_dir is not None and self.skip_save: | ||
| logging.warning( | ||
| "VectorStore creation: output_dir is set to %s but skip_save is True, so the VectorStore will not be saved to disk. output_dir will be ignored.", | ||
| self.output_dir, | ||
| ) | ||
|
|
||
| if self.output_dir is not None and not isinstance(self.output_dir, str): | ||
| raise DataValidationError( | ||
| "output_dir must be a string or None.", context={"output_dir_type": type(self.output_dir).__name__} | ||
| ) | ||
|
|
||
| if not self.skip_save: | ||
| # ---- Output directory handling (filesystem problems) -> ConfigurationError | ||
| try: | ||
| if self.output_dir is None: | ||
| logging.info( | ||
| "No output directory specified, attempting to use input file name as output folder name." | ||
| ) | ||
| os.makedirs(self.output_dir, exist_ok=True) | ||
| except Exception as e: | ||
| raise ConfigurationError( | ||
| "Failed to prepare output directory.", | ||
| context={"output_dir": self.output_dir}, | ||
| ) from e | ||
| normalized_file_name = os.path.basename(os.path.splitext(self.file_name)[0]) | ||
| self.output_dir = os.path.join(normalized_file_name) | ||
|
|
||
| if os.path.isdir(self.output_dir): | ||
| if overwrite: | ||
| shutil.rmtree(self.output_dir) | ||
| else: | ||
| raise ConfigurationError( | ||
| "Output directory already exists. Pass overwrite=True to overwrite the folder.", | ||
| context={"output_dir": self.output_dir}, | ||
| ) | ||
| os.makedirs(self.output_dir, exist_ok=True) | ||
| except Exception as e: | ||
| raise ConfigurationError( | ||
| "Failed to prepare output directory.", | ||
| context={"output_dir": self.output_dir}, | ||
| ) from e | ||
| else: | ||
| logging.debug("skip_save is set to True, the VectorStore will not be saved to disk after creation.") | ||
|
|
||
| # ---- Build index (wrap every unexpected failure) -> IndexBuildError | ||
| try: | ||
|
|
@@ -202,23 +225,25 @@ def __init__( # noqa: C901, PLR0912, PLR0913, PLR0915 | |
| ) from e | ||
|
|
||
| # ---- Save + derived metadata (IO/format problems) -> IndexBuildError | ||
| try: | ||
| logging.info("Gathering metadata and saving vector store / metadata...") | ||
|
|
||
| self.vector_shape = self.vectors["embeddings"].to_numpy().shape[1] | ||
| self.num_vectors = len(self.vectors) | ||
| self.vector_shape = self.vectors["embeddings"].to_numpy().shape[1] | ||
| self.num_vectors = len(self.vectors) | ||
|
|
||
| self.vectors.write_parquet(os.path.join(self.output_dir, "vectors.parquet")) | ||
| self._save_metadata(os.path.join(self.output_dir, "metadata.json")) | ||
| if not self.skip_save: | ||
| try: | ||
| logging.info("Gathering metadata and saving vector store / metadata...") | ||
| self.vectors.write_parquet(os.path.join(self.output_dir, "vectors.parquet")) | ||
| self._save_metadata(os.path.join(self.output_dir, "metadata.json")) | ||
|
|
||
| logging.info("Vector Store created - files saved to %s", self.output_dir) | ||
| except ClassifaiError: | ||
| raise | ||
| except Exception as e: | ||
| raise IndexBuildError( | ||
| "Vector store was created but saving outputs failed.", | ||
| context={"cause_type": type(e).__name__, "cause_message": str(e)}, | ||
| ) from e | ||
| logging.info("Vector Store created - files saved to %s", self.output_dir) | ||
| except ClassifaiError: | ||
| raise | ||
| except Exception as e: | ||
| raise IndexBuildError( | ||
| "Vector store was created but saving outputs failed.", | ||
| context={"cause_type": type(e).__name__, "cause_message": str(e)}, | ||
| ) from e | ||
| else: | ||
| logging.debug("skip_save is True, skipping saving VectorStore to disk.") | ||
|
|
||
| def _save_metadata(self, path: str): | ||
| """Saves metadata about the `VectorStore` to a JSON file. | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
consider making this new paragraph normal text size? - the two above it were shorter summary sentences made bigger for emphasis. The longer paragraph as a header makes it look slightly cluttered in the rendered notebook