Update vectorstore.py
This commit is contained in:
+29
-62
@@ -1,94 +1,61 @@
|
|||||||
"""Vector store utilities for ChromaDB with Ollama embeddings.
|
"""Vector store utilities using ChromaDB and Ollama embeddings.
|
||||||
|
|
||||||
This module provides functions to create a persistent Chroma vector store and
|
This module provides functions to create a persistent Chroma vector store
|
||||||
load documents from a directory into it. Documents are split into chunks using
|
and to load documents from a directory into the store.
|
||||||
`RecursiveCharacterTextSplitter` and stored in the Chroma collection.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List
|
from typing import Iterable
|
||||||
|
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
||||||
from langchain_chroma import Chroma
|
from langchain_chroma import Chroma
|
||||||
from langchain_ollama import OllamaEmbeddings
|
from langchain_ollama import OllamaEmbeddings
|
||||||
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Vector store creation
|
# Create a persistent Chroma vector store.
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def create_vectorstore(persist_directory: str = "./chroma_db") -> Chroma:
|
def create_vectorstore(persist_directory: str = "./chroma_db") -> Chroma:
|
||||||
"""Create or load a Chroma vector store.
|
"""Create a Chroma vector store with Ollama embeddings.
|
||||||
|
|
||||||
Parameters
|
Parameters
|
||||||
----------
|
----------
|
||||||
persist_directory: str
|
persist_directory: str
|
||||||
Directory where the Chroma DB files are stored.
|
Directory where the Chroma database will be stored.
|
||||||
|
|
||||||
Returns
|
Returns
|
||||||
-------
|
-------
|
||||||
Chroma
|
Chroma
|
||||||
A Chroma vector store instance.
|
A Chroma vector store instance.
|
||||||
"""
|
"""
|
||||||
# Ensure directory exists
|
|
||||||
Path(persist_directory).mkdir(parents=True, exist_ok=True)
|
|
||||||
# Use Ollama embeddings
|
|
||||||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||||||
# Create Chroma store
|
return Chroma(persist_directory=persist_directory, embedding_function=embeddings)
|
||||||
vectorstore = Chroma(persist_directory=persist_directory, embedding_function=embeddings)
|
|
||||||
return vectorstore
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Document loading
|
# Load documents from a directory into the vector store.
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _load_text_files(directory: str) -> List[str]:
|
def load_documents(directory: str, vectorstore: Chroma) -> None:
|
||||||
"""Load all .txt and .md files from a directory into a list of strings."""
|
"""Load all .txt and .md files from *directory* into *vectorstore*.
|
||||||
texts = []
|
|
||||||
for root, _, files in os.walk(directory):
|
|
||||||
for file in files:
|
|
||||||
if file.lower().endswith(('.txt', '.md')):
|
|
||||||
path = Path(root) / file
|
|
||||||
try:
|
|
||||||
content = path.read_text(encoding="utf-8")
|
|
||||||
texts.append(content)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Failed to read {path}: {e}")
|
|
||||||
return texts
|
|
||||||
|
|
||||||
|
The documents are split into chunks using a RecursiveCharacterTextSplitter
|
||||||
def load_documents(directory: str, vectorstore: Chroma, chunk_size: int = 1000, chunk_overlap: int = 200) -> None:
|
before being added to the vector store.
|
||||||
"""Load documents from a directory into the provided vector store.
|
|
||||||
|
|
||||||
Parameters
|
|
||||||
----------
|
|
||||||
directory: str
|
|
||||||
Path to the directory containing .txt/.md files.
|
|
||||||
vectorstore: Chroma
|
|
||||||
The vector store to add documents to.
|
|
||||||
chunk_size: int, optional
|
|
||||||
Maximum size of each chunk.
|
|
||||||
chunk_overlap: int, optional
|
|
||||||
Number of characters to overlap between chunks.
|
|
||||||
"""
|
"""
|
||||||
texts = _load_text_files(directory)
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
||||||
if not texts:
|
|
||||||
print("No text files found in the directory.")
|
|
||||||
return
|
|
||||||
|
|
||||||
splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
|
||||||
docs = []
|
docs = []
|
||||||
for text in texts:
|
for path in Path(directory).rglob("*.txt"):
|
||||||
docs.extend(splitter.split_text(text))
|
docs.append(path.read_text(encoding="utf-8"))
|
||||||
|
for path in Path(directory).rglob("*.md"):
|
||||||
# Add documents to Chroma
|
docs.append(path.read_text(encoding="utf-8"))
|
||||||
vectorstore.add_texts(docs)
|
if not docs:
|
||||||
print(f"Loaded {len(docs)} chunks into the vector store.")
|
return
|
||||||
|
# Split the documents into chunks.
|
||||||
|
chunks = splitter.split_text("\n\n".join(docs))
|
||||||
|
# Create LangChain Document objects.
|
||||||
|
from langchain.docstore.document import Document
|
||||||
|
documents = [Document(page_content=chunk) for chunk in chunks]
|
||||||
|
vectorstore.add_documents(documents)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Example usage (uncomment to run directly)
|
# End of vectorstore.py
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# if __name__ == "__main__":
|
|
||||||
# store = create_vectorstore()
|
|
||||||
# load_documents("documents", store)
|
|
||||||
""
|
|
||||||
Reference in New Issue
Block a user