Coverage for src/app/repositories/faiss_repository.py: 100%
32 statements
« prev ^ index » next coverage.py v7.7.0, created at 2025-04-03 00:42 +0200
« prev ^ index » next coverage.py v7.7.0, created at 2025-04-03 00:42 +0200
1from langchain_community.vectorstores import FAISS
2from langchain_core.documents import Document
4from dependencies.init_vector_store import store_vector_store
6from entities.document_context_entity import DocumentContextEntity
7from entities.query_entity import QueryEntity
8from entities.file_chunk_entity import FileChunkEntity
10class FaissRepository:
12 def __init__(self, vectorstore: FAISS):
13 self.vectorstore = vectorstore
15 def similarity_search(self, query: QueryEntity) -> list[DocumentContextEntity]:
16 """
17 Performs a similarity search in the collection and returns the most relevant documents.
19 Args:
20 query (QueryEntity): The query entity containing the search parameters.
22 Returns:
23 list[DocumentContextEntity]: A list of the most relevant document context entities.
24 """
28 if not query.get_query().strip():
29 raise ValueError("Query cannot be empty")
31 try:
32 result = self.vectorstore.similarity_search(query.get_query(), k=4)
34 context_list = []
36 for context in result:
37 context_list.append(DocumentContextEntity(context.page_content))
39 return context_list
41 except Exception as e:
42 return str(e)
45 def load_chunks(self, chunks: list[FileChunkEntity]) -> str:
46 """
47 Perform a load of the chunks into the vectorstore.
49 Args:
50 chunks (list[FileChunkEntity]): The list of file chunk entities to load.
52 Returns:
53 str: The number of chunks loaded.
55 Raises:
56 Exception: If an error occurs during the load.
57 """
58 if not chunks:
59 raise ValueError("No chunks to load.")
61 try:
62 result = []
64 for chunk in chunks:
65 doc = Document(page_content=chunk.get_chunk_content(), metadata={"metadata": chunk.get_metadata()})
66 result.append(self.vectorstore.add_documents([doc]))
68 store_vector_store(self.vectorstore)
70 return f"{len(result)} chunks loaded."
72 except Exception as e:
73 return f"Error occurred during chunk loading: {str(e)}"