File size: 7,232 Bytes
8b7e8f0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | from typing import List, Dict, Any, Optional
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_chroma import Chroma
from langchain.schema import Document
import os
from src.utils.config import config
from src.utils.logger import log_error
from src.models.document import Document as DocModel
class VectorStoreService:
def __init__(self):
# Initialize embeddings
self.embeddings = GoogleGenerativeAIEmbeddings(
model=config.EMBEDDING_MODEL, google_api_key=config.GOOGLE_API_KEY
)
# Ensure Chroma directory exists
os.makedirs(config.CHROMA_PERSIST_DIR, exist_ok=True)
# Initialize Chroma vector store
self.vector_store = Chroma(
persist_directory=config.CHROMA_PERSIST_DIR,
embedding_function=self.embeddings,
collection_name="lega_documents",
)
def add_document(
self, document_id: str, text: str, metadata: Dict[str, Any] = None
) -> bool:
"""Add a document to the vector store."""
try:
# Create document chunks for better retrieval
chunks = self._chunk_document(text)
documents = []
metadatas = []
ids = []
for i, chunk in enumerate(chunks):
chunk_metadata = {
"document_id": document_id,
"chunk_id": i,
"chunk_type": "text",
**(metadata or {}),
}
documents.append(chunk)
metadatas.append(chunk_metadata)
ids.append(f"{document_id}_chunk_{i}")
# Add to vector store
self.vector_store.add_texts(texts=documents, metadatas=metadatas, ids=ids)
return True
except Exception as e:
log_error(f"Error adding document to vector store: {str(e)}")
return False
def search_similar_documents(self, query: str, k: int = 5) -> List[Dict[str, Any]]:
"""Search for similar documents based on query."""
try:
results = self.vector_store.similarity_search_with_score(query=query, k=k)
formatted_results = []
for doc, score in results:
formatted_results.append(
{
"content": doc.page_content,
"metadata": doc.metadata,
"similarity_score": score,
}
)
return formatted_results
except Exception as e:
log_error(f"Error searching vector store: {str(e)}")
return []
def search_document_clauses(
self, document_id: str, query: str, k: int = 3
) -> List[Dict[str, Any]]:
"""Search for specific clauses within a document."""
try:
# Filter by document_id
results = self.vector_store.similarity_search_with_score(
query=query, k=k, filter={"document_id": document_id}
)
formatted_results = []
for doc, score in results:
formatted_results.append(
{
"content": doc.page_content,
"metadata": doc.metadata,
"similarity_score": score,
}
)
return formatted_results
except Exception as e:
log_error(f"Error searching document clauses: {str(e)}")
return []
def get_document_context(
self, document_id: str, query: str, max_chunks: int = 5
) -> str:
"""Get relevant context from a document for Q&A."""
try:
results = self.search_document_clauses(document_id, query, k=max_chunks)
# Combine relevant chunks
context_parts = []
for result in results:
if result["similarity_score"] < 0.8: # Only use highly relevant chunks
context_parts.append(result["content"])
return "\n\n".join(context_parts)
except Exception as e:
log_error(f"Error getting document context: {str(e)}")
return ""
def remove_document(self, document_id: str) -> bool:
"""Remove a document and all its chunks from the vector store."""
try:
# Get all chunks for this document
results = self.vector_store.get(where={"document_id": document_id})
if results and results.get("ids"):
# Delete all chunks
self.vector_store.delete(ids=results["ids"])
return True
except Exception as e:
log_error(f"Error removing document from vector store: {str(e)}")
return False
def get_document_stats(self) -> Dict[str, Any]:
"""Get statistics about the vector store."""
try:
# Get collection info
collection = self.vector_store._collection
count = collection.count()
return {
"total_documents": count,
"collection_name": "lega_documents",
"persist_directory": config.CHROMA_PERSIST_DIR,
}
except Exception as e:
log_error(f"Error getting vector store stats: {str(e)}")
return {"total_documents": 0}
def _chunk_document(
self, text: str, chunk_size: int = 1000, overlap: int = 200
) -> List[str]:
"""Split document into chunks for embedding."""
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunk = text[start:end]
# Try to break at sentence boundary
if end < len(text):
last_period = chunk.rfind(".")
if last_period > chunk_size // 2:
chunk = chunk[: last_period + 1]
end = start + last_period + 1
chunks.append(chunk.strip())
start = end - overlap
return [chunk for chunk in chunks if chunk.strip()]
def find_similar_clauses(
self, clause_text: str, exclude_document_id: str = None, k: int = 3
) -> List[Dict[str, Any]]:
"""Find similar clauses across all documents."""
try:
filter_dict = {}
if exclude_document_id:
# This is a simplified filter - Chroma might need different syntax
filter_dict = {"document_id": {"$ne": exclude_document_id}}
results = self.vector_store.similarity_search_with_score(
query=clause_text, k=k, filter=filter_dict if filter_dict else None
)
formatted_results = []
for doc, score in results:
formatted_results.append(
{
"content": doc.page_content,
"metadata": doc.metadata,
"similarity_score": score,
}
)
return formatted_results
except Exception as e:
log_error(f"Error finding similar clauses: {str(e)}")
return []
|