Kalpokoch commited on
Commit
784b064
·
verified ·
1 Parent(s): 5340487

Update app/policy_vector_db.py

Browse files
Files changed (1) hide show
  1. app/policy_vector_db.py +76 -18
app/policy_vector_db.py CHANGED
@@ -13,9 +13,10 @@ logger = logging.getLogger(__name__)
13
 
14
  class PolicyVectorDB:
15
  """
16
- Manages the connection, population, and querying of a ChromaDB vector database
17
  for policy documents.
18
  """
 
19
  def __init__(self, persist_directory: str, top_k_default: int = 5, relevance_threshold: float = 0.5):
20
  self.persist_directory = persist_directory
21
  self.client = chromadb.PersistentClient(path=persist_directory, settings=Settings(allow_reset=True))
@@ -24,10 +25,10 @@ class PolicyVectorDB:
24
  # Using a powerful open-source embedding model.
25
  # Change 'cpu' to 'cuda' if a GPU is available for significantly faster embedding.
26
  logger.info("Loading embedding model 'BAAI/bge-large-en-v1.5'. This may take a moment...")
27
- self.embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5', device='cpu')
28
  logger.info("Embedding model loaded successfully.")
29
 
30
- self.collection = None # Initialize collection as None for lazy loading
31
  self.top_k_default = top_k_default
32
  self.relevance_threshold = relevance_threshold
33
 
@@ -44,13 +45,22 @@ class PolicyVectorDB:
44
 
45
  def _flatten_metadata(self, metadata: Dict) -> Dict:
46
  """Ensures all metadata values are strings, as required by some ChromaDB versions."""
47
- return {key: str(value) for key, value in metadata.items()}
 
 
 
 
 
 
 
 
48
 
49
  def add_chunks(self, chunks: List[Dict]):
50
  """
51
  Adds a list of chunks to the vector database, skipping any that already exist.
52
  """
53
  collection = self._get_collection()
 
54
  if not chunks:
55
  logger.info("No chunks provided to add.")
56
  return
@@ -58,6 +68,7 @@ class PolicyVectorDB:
58
  chunks_with_ids = [c for c in chunks if c.get('id')]
59
  if len(chunks) != len(chunks_with_ids):
60
  logger.warning(f"Skipped {len(chunks) - len(chunks_with_ids)} chunks that were missing an 'id'.")
 
61
  if not chunks_with_ids:
62
  return
63
 
@@ -67,24 +78,23 @@ class PolicyVectorDB:
67
  if not new_chunks:
68
  logger.info("All provided chunks already exist in the database. No new data to add.")
69
  return
70
-
71
  logger.info(f"Adding {len(new_chunks)} new chunks to the vector database...")
72
-
73
  # Process in batches for efficiency
74
- batch_size = 32 # Reduced batch size for potentially large embeddings
75
  for i in range(0, len(new_chunks), batch_size):
76
  batch = new_chunks[i:i + batch_size]
77
-
78
  ids = [str(chunk['id']) for chunk in batch]
79
  texts = [chunk['text'] for chunk in batch]
80
  metadatas = [self._flatten_metadata(chunk.get('metadata', {})) for chunk in batch]
81
-
82
  # For BGE models, it's recommended not to add instructions to the document embeddings
83
  embeddings = self.embedding_model.encode(texts, normalize_embeddings=True, show_progress_bar=False).tolist()
84
-
85
  collection.add(ids=ids, embeddings=embeddings, documents=texts, metadatas=metadatas)
86
  logger.info(f"Added batch {i//batch_size + 1}/{(len(new_chunks) + batch_size - 1) // batch_size}")
87
-
88
  logger.info(f"Finished adding {len(new_chunks)} chunks.")
89
 
90
  def search(self, query_text: str, top_k: int = None) -> List[Dict]:
@@ -105,26 +115,72 @@ class PolicyVectorDB:
105
  # Retrieve more results initially to allow for filtering
106
  results = collection.query(
107
  query_embeddings=query_embedding,
108
- n_results=k * 2, # Retrieve more to filter by threshold
109
  include=["documents", "metadatas", "distances"]
110
  )
111
-
112
  search_results = []
113
  if results and results.get('documents') and results['documents'][0]:
114
- for i, doc in enumerate(results['documents'][0]):
115
  # The distance for normalized embeddings is often interpreted as 1 - cosine_similarity
116
  relevance_score = 1 - results['distances'][0][i]
117
-
118
  if relevance_score >= self.relevance_threshold:
119
  search_results.append({
120
  'text': doc,
121
  'metadata': results['metadatas'][0][i],
122
  'relevance_score': relevance_score
123
  })
124
-
125
  # Sort by relevance score and return the top_k results
126
  return sorted(search_results, key=lambda x: x['relevance_score'], reverse=True)[:k]
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> bool:
129
  """
130
  Checks if the DB is empty and populates it from a JSONL file if needed.
@@ -135,10 +191,11 @@ def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> b
135
  return True
136
 
137
  logger.info("Vector database is empty. Attempting to populate from chunks file.")
 
138
  if not os.path.exists(chunks_file_path):
139
  logger.error(f"Chunks file not found at '{chunks_file_path}'. Cannot populate DB.")
140
  return False
141
-
142
  chunks_to_add = []
143
  with open(chunks_file_path, 'r', encoding='utf-8') as f:
144
  for line in f:
@@ -146,7 +203,7 @@ def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> b
146
  chunks_to_add.append(json.loads(line))
147
  except json.JSONDecodeError:
148
  logger.warning(f"Skipping malformed line in chunks file: {line.strip()}")
149
-
150
  if not chunks_to_add:
151
  logger.warning(f"Chunks file at '{chunks_file_path}' is empty or invalid. No data to add.")
152
  return False
@@ -154,6 +211,7 @@ def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> b
154
  db_instance.add_chunks(chunks_to_add)
155
  logger.info("Vector database population attempt complete.")
156
  return True
 
157
  except Exception as e:
158
  logger.error(f"An error occurred during DB population check: {e}", exc_info=True)
159
  return False
 
13
 
14
  class PolicyVectorDB:
15
  """
16
+ Manages the connection, population, and querying of a ChromaDB vector database
17
  for policy documents.
18
  """
19
+
20
  def __init__(self, persist_directory: str, top_k_default: int = 5, relevance_threshold: float = 0.5):
21
  self.persist_directory = persist_directory
22
  self.client = chromadb.PersistentClient(path=persist_directory, settings=Settings(allow_reset=True))
 
25
  # Using a powerful open-source embedding model.
26
  # Change 'cpu' to 'cuda' if a GPU is available for significantly faster embedding.
27
  logger.info("Loading embedding model 'BAAI/bge-large-en-v1.5'. This may take a moment...")
28
+ self.embedding_model = SentenceTransformer('BAAI/bge-large-en-v1.5', device='cpu')
29
  logger.info("Embedding model loaded successfully.")
30
 
31
+ self.collection = None # Initialize collection as None for lazy loading
32
  self.top_k_default = top_k_default
33
  self.relevance_threshold = relevance_threshold
34
 
 
45
 
46
  def _flatten_metadata(self, metadata: Dict) -> Dict:
47
  """Ensures all metadata values are strings, as required by some ChromaDB versions."""
48
+ def flatten_value(value):
49
+ if isinstance(value, dict):
50
+ return str(value)
51
+ elif isinstance(value, list):
52
+ return str(value)
53
+ else:
54
+ return str(value)
55
+
56
+ return {key: flatten_value(value) for key, value in metadata.items()}
57
 
58
  def add_chunks(self, chunks: List[Dict]):
59
  """
60
  Adds a list of chunks to the vector database, skipping any that already exist.
61
  """
62
  collection = self._get_collection()
63
+
64
  if not chunks:
65
  logger.info("No chunks provided to add.")
66
  return
 
68
  chunks_with_ids = [c for c in chunks if c.get('id')]
69
  if len(chunks) != len(chunks_with_ids):
70
  logger.warning(f"Skipped {len(chunks) - len(chunks_with_ids)} chunks that were missing an 'id'.")
71
+
72
  if not chunks_with_ids:
73
  return
74
 
 
78
  if not new_chunks:
79
  logger.info("All provided chunks already exist in the database. No new data to add.")
80
  return
81
+
82
  logger.info(f"Adding {len(new_chunks)} new chunks to the vector database...")
83
+
84
  # Process in batches for efficiency
85
+ batch_size = 32 # Reduced batch size for potentially large embeddings
86
  for i in range(0, len(new_chunks), batch_size):
87
  batch = new_chunks[i:i + batch_size]
 
88
  ids = [str(chunk['id']) for chunk in batch]
89
  texts = [chunk['text'] for chunk in batch]
90
  metadatas = [self._flatten_metadata(chunk.get('metadata', {})) for chunk in batch]
91
+
92
  # For BGE models, it's recommended not to add instructions to the document embeddings
93
  embeddings = self.embedding_model.encode(texts, normalize_embeddings=True, show_progress_bar=False).tolist()
94
+
95
  collection.add(ids=ids, embeddings=embeddings, documents=texts, metadatas=metadatas)
96
  logger.info(f"Added batch {i//batch_size + 1}/{(len(new_chunks) + batch_size - 1) // batch_size}")
97
+
98
  logger.info(f"Finished adding {len(new_chunks)} chunks.")
99
 
100
  def search(self, query_text: str, top_k: int = None) -> List[Dict]:
 
115
  # Retrieve more results initially to allow for filtering
116
  results = collection.query(
117
  query_embeddings=query_embedding,
118
+ n_results=k * 2, # Retrieve more to filter by threshold
119
  include=["documents", "metadatas", "distances"]
120
  )
121
+
122
  search_results = []
123
  if results and results.get('documents') and results['documents'][0]:
124
+ for i, doc in enumerate(results['documents']):
125
  # The distance for normalized embeddings is often interpreted as 1 - cosine_similarity
126
  relevance_score = 1 - results['distances'][0][i]
 
127
  if relevance_score >= self.relevance_threshold:
128
  search_results.append({
129
  'text': doc,
130
  'metadata': results['metadatas'][0][i],
131
  'relevance_score': relevance_score
132
  })
133
+
134
  # Sort by relevance score and return the top_k results
135
  return sorted(search_results, key=lambda x: x['relevance_score'], reverse=True)[:k]
136
 
137
+ def search_with_filters(self, query_text: str, top_k: int = None,
138
+ section_filter: str = None, chunk_type_filter: str = None) -> List[Dict]:
139
+ """Enhanced search with metadata filtering capability."""
140
+ collection = self._get_collection()
141
+
142
+ instructed_query = f"Represent this sentence for searching relevant passages: {query_text}"
143
+ query_embedding = self.embedding_model.encode([instructed_query], normalize_embeddings=True).tolist()
144
+
145
+ k = top_k if top_k is not None else self.top_k_default
146
+
147
+ # Build where clause for filtering
148
+ where_clause = {}
149
+ if section_filter:
150
+ where_clause["section"] = section_filter
151
+ if chunk_type_filter:
152
+ where_clause["chunk_type"] = chunk_type_filter
153
+
154
+ try:
155
+ results = collection.query(
156
+ query_embeddings=query_embedding,
157
+ n_results=k * 2,
158
+ include=["documents", "metadatas", "distances"],
159
+ where=where_clause if where_clause else None
160
+ )
161
+ except Exception as e:
162
+ logger.warning(f"Filtered search failed, falling back to regular search: {e}")
163
+ # Fall back to regular search if filtering fails
164
+ results = collection.query(
165
+ query_embeddings=query_embedding,
166
+ n_results=k * 2,
167
+ include=["documents", "metadatas", "distances"]
168
+ )
169
+
170
+ search_results = []
171
+ if results and results.get('documents') and results['documents'][0]:
172
+ for i, doc in enumerate(results['documents']):
173
+ relevance_score = 1 - results['distances'][i]
174
+ if relevance_score >= self.relevance_threshold:
175
+ search_results.append({
176
+ 'text': doc,
177
+ 'metadata': results['metadatas'][0][i],
178
+ 'relevance_score': relevance_score
179
+ })
180
+
181
+ return sorted(search_results, key=lambda x: x['relevance_score'], reverse=True)[:k]
182
+
183
+
184
  def ensure_db_populated(db_instance: PolicyVectorDB, chunks_file_path: str) -> bool:
185
  """
186
  Checks if the DB is empty and populates it from a JSONL file if needed.
 
191
  return True
192
 
193
  logger.info("Vector database is empty. Attempting to populate from chunks file.")
194
+
195
  if not os.path.exists(chunks_file_path):
196
  logger.error(f"Chunks file not found at '{chunks_file_path}'. Cannot populate DB.")
197
  return False
198
+
199
  chunks_to_add = []
200
  with open(chunks_file_path, 'r', encoding='utf-8') as f:
201
  for line in f:
 
203
  chunks_to_add.append(json.loads(line))
204
  except json.JSONDecodeError:
205
  logger.warning(f"Skipping malformed line in chunks file: {line.strip()}")
206
+
207
  if not chunks_to_add:
208
  logger.warning(f"Chunks file at '{chunks_file_path}' is empty or invalid. No data to add.")
209
  return False
 
211
  db_instance.add_chunks(chunks_to_add)
212
  logger.info("Vector database population attempt complete.")
213
  return True
214
+
215
  except Exception as e:
216
  logger.error(f"An error occurred during DB population check: {e}", exc_info=True)
217
  return False