Spaces:
Sleeping
Sleeping
Download src/services/retrieval_service.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 31.2 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/retrieval_service.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/src/services/retrieval_service.py
-
curl -L -o retrieval_service.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/src/services/retrieval_service.py
31.2 kB
| from __future__ import annotations | |
| import logging | |
| # Configure logger for retrieval service | |
| logger = logging.getLogger("retrieval_service") | |
| if not logger.hasHandlers(): | |
| logging.basicConfig(level=logging.INFO) | |
| logger.setLevel(logging.INFO) | |
| """retrieval_service.py | |
| Lightweight retrieval (RAG) helper for the data dictionary chatbot. | |
| Goals: | |
| - Avoid passing entire dictionaries to the LLM by selecting only relevant chunks. | |
| - Provide drill-down capability for individual columns or lines. | |
| - Be resilient when embeddings are not configured (fallback to keyword scoring). | |
| Design: | |
| - Chunks are simple dicts: {"id", "text", "dataset", "score", "meta"} | |
| - Build chunks by splitting dictionary content into non-empty lines; future improvement: structured CSV parsing. | |
| - Search uses one of: | |
| 1. Embeddings (if AZURE_OPENAI_EMBEDDING_DEPLOYMENT is set) -> cosine similarity | |
| 2. Fallback lexical scoring: token overlap + SequenceMatcher ratio. | |
| This avoids adding heavy external dependencies (FAISS/Chroma). Can be swapped out later. | |
| """ | |
| import os | |
| import math | |
| import json | |
| import re | |
| from typing import List, Dict, Any, Tuple | |
| from pathlib import Path | |
| import hashlib | |
| from services.cache_service import ensure_cache_dir, load_json, save_json | |
| from difflib import SequenceMatcher | |
| import requests | |
| import streamlit as st | |
| # Heuristic: limit total chunks returned to keep prompt small | |
| DEFAULT_TOP_K = 25 | |
| LEXICAL_PREFILTER_K = 300 # limit how many chunks we embed per query | |
| MAX_CHUNK_CHARS = 1200 # prevent single giant lines blowing up context | |
| class RetrievalService: | |
| def __init__(self, data_dictionary_service): | |
| self.data_service = data_dictionary_service | |
| self.chunks: List[Dict[str, Any]] = [] | |
| # Support separate embedding endpoint if configured, otherwise use main endpoint | |
| self._embedding_endpoint = os.getenv("AZURE_OPENAI_EMBEDDING_ENDPOINT") or os.getenv("AZURE_OPENAI_ENDPOINT", "") | |
| self._embedding_endpoint = self._embedding_endpoint.rstrip("/") | |
| self._embedding_key = os.getenv("AZURE_OPENAI_API_KEY") | |
| self._embedding_deployment = os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT") # user must set | |
| self._api_version = os.getenv("AZURE_OPENAI_EMBEDDING_API_VERSION") or os.getenv("AZURE_OPENAI_API_VERSION", "2024-02-15-preview") | |
| self._embeddings_cache: Dict[str, List[float]] = {} # All embeddings (queries + chunks) in memory | |
| self._chunk_texts_set: set = set() # Track which texts are chunks (not queries) | |
| # Cache paths | |
| self._cache_dir = ensure_cache_dir() | |
| self._chunks_path = Path(self._cache_dir) / "chunks.json" | |
| self._embeds_path = Path(self._cache_dir) / "embeddings.json" # Only stores chunk embeddings | |
| self._sig_path = Path(self._cache_dir) / "corpus_sig.txt" | |
| # Preload cached index/embeddings if signatures match | |
| self._corpus_sig = self._compute_corpus_signature() | |
| self._load_cached_index() | |
| self._load_cached_embeddings() | |
| # -------------------- Public API -------------------- # | |
| def index(self) -> int: | |
| """(Re)build chunk list from current data dictionaries. | |
| Returns number of chunks indexed.""" | |
| logger.info("[RetrievalService] Indexing all data dictionaries...") | |
| self.chunks = [] | |
| for name, content in self.data_service.data_dictionaries.items(): | |
| dataset = name | |
| # Special handling for CSV data dictionaries - parse structured columns | |
| if name.lower().endswith('.csv'): | |
| lines = content.splitlines() | |
| if lines: | |
| # Try to detect CSV structure (header + data rows) | |
| header_line = lines[0] if lines else "" | |
| # For each subsequent line, combine with header context for better retrieval | |
| for i, line in enumerate(lines[1:], start=1): # Skip header | |
| line = line.strip() | |
| if not line or len(line) < 3: | |
| continue | |
| # Enhance CSV rows with semantic context | |
| # This makes "E_DIABETES,Percentage of individuals with diabetes" more searchable | |
| truncated = line[:MAX_CHUNK_CHARS] | |
| chunk = { | |
| "id": f"{dataset}:{i}", | |
| "dataset": dataset, | |
| "text": truncated, | |
| "meta": {"line_number": i, "is_csv": True} | |
| } | |
| self.chunks.append(chunk) | |
| continue | |
| # Standard line-by-line indexing for other formats | |
| for i, line in enumerate(content.splitlines()): | |
| line = line.strip() | |
| if not line or len(line) < 3: | |
| continue | |
| truncated = line[:MAX_CHUNK_CHARS] | |
| chunk = { | |
| "id": f"{dataset}:{i}", | |
| "dataset": dataset, | |
| "text": truncated, | |
| "meta": {"line_number": i} | |
| } | |
| self.chunks.append(chunk) | |
| logger.info(f"[RetrievalService] Indexed {len(self.chunks)} chunks from {len(self.data_service.data_dictionaries)} dictionaries.") | |
| # Build set of chunk texts for persistence tracking | |
| self._chunk_texts_set = set(chunk["text"] for chunk in self.chunks) | |
| logger.info(f"[RetrievalService] Tracking {len(self._chunk_texts_set)} chunk texts for selective persistence") | |
| # Save index and signature | |
| save_json(self._chunks_path, self.chunks) | |
| try: | |
| self._sig_path.write_text(self._corpus_sig, encoding="utf-8") | |
| except Exception: | |
| pass | |
| return len(self.chunks) | |
| def ensure_index(self): | |
| if not self.chunks: | |
| self.index() | |
| def warm_embeddings_cache(self, sample_size: int = 100) -> int: | |
| """Pre-warm embeddings cache by embedding a sample of chunks. | |
| This improves accuracy of the first query. | |
| Returns number of embeddings created.""" | |
| if not self._embedding_ready(): | |
| logger.info("[RetrievalService] Embeddings not configured, skipping warm-up.") | |
| return 0 | |
| self.ensure_index() | |
| if not self.chunks: | |
| return 0 | |
| # Select diverse sample: take chunks spread across the corpus | |
| import random | |
| sample_size = min(sample_size, len(self.chunks)) | |
| step = max(1, len(self.chunks) // sample_size) | |
| sample_chunks = [self.chunks[i] for i in range(0, len(self.chunks), step)][:sample_size] | |
| # Filter out already cached | |
| texts_to_embed = [c["text"] for c in sample_chunks if c["text"] not in self._embeddings_cache] | |
| if not texts_to_embed: | |
| logger.info(f"[RetrievalService] βΉοΈ All {sample_size} sample chunks already embedded.") | |
| return 0 | |
| logger.info(f"[RetrievalService] π₯ WARM-UP: Generating {len(texts_to_embed)} embeddings to pre-warm cache...") | |
| batch_vecs = self._embed_batch(texts_to_embed) | |
| # Update cache | |
| for text, vec in zip(texts_to_embed, batch_vecs): | |
| self._embeddings_cache[text] = vec | |
| # Persist to disk | |
| save_json(self._embeds_path, self._embeddings_cache) | |
| cache_size = len(self._embeddings_cache) | |
| logger.info(f"[RetrievalService] β WARM-UP COMPLETE: {len(texts_to_embed)} new embeddings added. Total cache size: {cache_size}") | |
| return len(texts_to_embed) | |
| def generate_missing_embeddings(self, batch_size: int = 50) -> int: | |
| """Generate embeddings for chunks that don't have them yet. | |
| This builds up the embedding cache over time as queries are made. | |
| Called periodically to improve coverage. | |
| Returns number of new embeddings created.""" | |
| if not self._embedding_ready(): | |
| logger.info("[RetrievalService] Embeddings not configured, skipping generation.") | |
| return 0 | |
| self.ensure_index() | |
| if not self.chunks: | |
| return 0 | |
| # Find chunks without embeddings | |
| unembed_chunks = [c["text"] for c in self.chunks if c["text"] not in self._embeddings_cache] | |
| if not unembed_chunks: | |
| logger.info("[RetrievalService] All chunks already have embeddings.") | |
| return 0 | |
| logger.info(f"[RetrievalService] Found {len(unembed_chunks)} chunks without embeddings. Generating in batches...") | |
| # Process in batches to avoid overwhelming API | |
| created_count = 0 | |
| for i in range(0, len(unembed_chunks), batch_size): | |
| batch = unembed_chunks[i:i+batch_size] | |
| try: | |
| batch_vecs = self._embed_batch(batch) | |
| for text, vec in zip(batch, batch_vecs): | |
| self._embeddings_cache[text] = vec | |
| created_count += len(batch) | |
| logger.info(f"[RetrievalService] Generated embeddings for batch {i//batch_size + 1}: {len(batch)} chunks (total: {created_count})") | |
| except Exception as e: | |
| logger.error(f"[RetrievalService] Error generating batch embeddings: {e}") | |
| break | |
| # Persist to disk | |
| if created_count > 0: | |
| save_json(self._embeds_path, self._embeddings_cache) | |
| logger.info(f"[RetrievalService] Generated and cached {created_count} new embeddings. Cache now has {len(self._embeddings_cache)} total embeddings.") | |
| return created_count | |
| # -------------------- Cache Status & Maintenance -------------------- # | |
| def get_cache_status(self) -> Dict[str, Any]: | |
| """Return lightweight cache/index status for UI display.""" | |
| return { | |
| "chunks_indexed": len(self.chunks), | |
| "embeddings_cached": len(self._embeddings_cache), | |
| "embeddings_enabled": self._embedding_ready(), | |
| "cache_dir": str(self._cache_dir), | |
| "corpus_sig": (self._corpus_sig[:12] + "β¦") if getattr(self, "_corpus_sig", None) else "", | |
| } | |
| def _update_session_state(self) -> None: | |
| """Update session state with current cache size for UI (sidebar) display.""" | |
| try: | |
| st.session_state['embedding_cache_size'] = len(self._embeddings_cache) | |
| except Exception: | |
| # Session state may not be available in all contexts (e.g., background threads) | |
| pass | |
| def clear_cache(self) -> None: | |
| """Clear on-disk caches and in-memory caches.""" | |
| logger.info("[RetrievalService] Clearing caches (index + embeddings).") | |
| # Clear disk files | |
| for p in [self._chunks_path, self._embeds_path, self._sig_path]: | |
| try: | |
| if p.exists(): | |
| p.unlink() | |
| except Exception: | |
| pass | |
| # Clear memory | |
| self.chunks = [] | |
| self._embeddings_cache = {} | |
| def search(self, query: str, active_datasets: List[str], top_k: int = DEFAULT_TOP_K, disable_embeddings: bool = False, ensure_diversity: bool = True) -> List[Dict[str, Any]]: | |
| logger.info(f"[RetrievalService] search() called with query: '{query}' and active_datasets: {active_datasets}") | |
| # Skip retrieval for very short conversational messages (greetings, acknowledgments) | |
| if len(query.strip().split()) <= 3 and not any(kw in query.lower() for kw in ['column', 'data', 'dataset', 'show', 'recommend', 'suggest']): | |
| logger.info("[RetrievalService] Skipping retrieval for short conversational message.") | |
| return [] # Let chat history handle short conversational exchanges | |
| # If corpus has changed (e.g., new upload), refresh index | |
| current_sig = self._compute_corpus_signature() | |
| if current_sig != self._corpus_sig: | |
| logger.info("[RetrievalService] Corpus changed; rebuilding index and refreshing cache.") | |
| self._corpus_sig = current_sig | |
| self.index() | |
| self.ensure_index() | |
| filtered = [c for c in self.chunks if c["dataset"] in active_datasets] | |
| logger.info(f"[RetrievalService] {len(filtered)} chunks after filtering by active datasets.") | |
| if not filtered: | |
| logger.info("[RetrievalService] No chunks found for active datasets.") | |
| return [] | |
| # Always do a quick lexical prefilter first to keep embedding calls bounded | |
| q_tokens = tokenize(query) | |
| # Query expansion for ML/predictive modeling use cases | |
| expanded_tokens = q_tokens.copy() | |
| if any(term in query.lower() for term in ['predict', 'model', 'risk', 'classification', 'regression']): | |
| # Add common feature-related terms | |
| expanded_tokens.update(['feature', 'predictor', 'variable', 'factor', 'indicator']) | |
| # For specific disease/outcome predictions, add risk factor terms | |
| if 'diabetes' in query.lower(): | |
| expanded_tokens.update(['age', 'obesity', 'insurance', 'poverty', 'income', 'uninsured', | |
| 'education', 'unemployed', 'smoking', 'physical', 'activity', | |
| 'age65', 'age17', 'pov200', 'nohsdp', 'uninsur', 'bmi']) | |
| if 'heart' in query.lower() or 'cardiac' in query.lower(): | |
| expanded_tokens.update(['blood', 'pressure', 'cholesterol', 'smoking', 'age', 'hypertension', | |
| 'obesity', 'insurance', 'poverty', 'bphigh', 'chd']) | |
| if 'cancer' in query.lower(): | |
| expanded_tokens.update(['smoking', 'exposure', 'age', 'screening', 'family', 'history', | |
| 'pollution', 'air', 'quality', 'toxics', 'carcinogen']) | |
| for c in filtered: | |
| c_tokens = tokenize(c["text"]) | |
| # Base overlap score with expanded query | |
| overlap = len(expanded_tokens & c_tokens) / (len(expanded_tokens) + 1e-9) | |
| seq_ratio = SequenceMatcher(None, query.lower(), c["text"].lower()).ratio() | |
| # Boost score if chunk looks like a column definition (has certain patterns) | |
| column_boost = 0.0 | |
| text_lower = c["text"].lower() | |
| # Boost if it has column-like patterns | |
| if any(pattern in text_lower for pattern in ['estimate', 'percentage', 'percent', 'rate', 'count', 'index', 'score', 'level', 'status']): | |
| column_boost += 0.1 | |
| # Boost if it contains actual data field patterns (especially for CSV dictionaries) | |
| if any(pattern in c["text"] for pattern in ['E_', 'EPL_', 'F_', 'M_', 'RPL_', 'SPL_']): | |
| column_boost += 0.2 # Higher boost for actual column names | |
| # Additional boost for CSV-based dictionaries (structured data) | |
| if c.get("meta", {}).get("is_csv", False): | |
| column_boost += 0.15 | |
| # Boost known risk factor columns for diabetes/disease prediction | |
| risk_factor_boost = 0.0 | |
| if any(term in query.lower() for term in ['predict', 'model', 'risk']): | |
| # Boost socioeconomic risk factors | |
| if any(pattern in c["text"] for pattern in ['E_POV200', 'E_UNINSUR', 'E_NOHSDP', 'E_UNEMP', 'E_AGE65', 'E_AGE17', 'E_MINRTY', 'E_HOUBDN']): | |
| risk_factor_boost += 0.25 | |
| # Boost health behavior/clinical columns | |
| if any(pattern in text_lower for pattern in ['obesity', 'smoking', 'physical activity', 'bmi', 'blood pressure', 'cholesterol']): | |
| risk_factor_boost += 0.2 | |
| # Penalize metadata/documentation chunks | |
| metadata_penalty = 0.0 | |
| if any(pattern in text_lower for pattern in ['variable beginning', 'table below', 'for example', 'note:', 'see detailed', 'guidance document', 'census bureau']): | |
| metadata_penalty += 0.3 | |
| # Penalize outcome/death statistics when predicting | |
| if any(term in query.lower() for term in ['predict', 'model', 'risk']): | |
| # Heavy penalty for using the disease itself as a predictor | |
| if 'diabetes' in query.lower() and any(pattern in c["text"] for pattern in ['E_DIABETES', 'EPL_DIABETES', 'F_DIABETES']): | |
| metadata_penalty += 0.4 # Very high penalty - this is the target, not a feature | |
| if any(term in text_lower for term in ['death', 'mortality', 'died', 'deceased']): | |
| metadata_penalty += 0.2 | |
| c["_lex"] = ((overlap * 0.5) + (seq_ratio * 0.3) + column_boost + risk_factor_boost - metadata_penalty) | |
| prefiltered = sorted(filtered, key=lambda x: x["_lex"], reverse=True)[:min(LEXICAL_PREFILTER_K, len(filtered))] | |
| logger.info(f"[RetrievalService] Lexical prefilter reduced to {len(prefiltered)} chunks.") | |
| # Diagnostic: Log if active datasets are missing from prefiltered results | |
| # This helps identify if scoring needs adjustment, but we don't force-add irrelevant content | |
| if ensure_diversity and len(active_datasets) > 1: | |
| prefiltered_datasets = set(c["dataset"] for c in prefiltered) | |
| missing_datasets = set(active_datasets) - prefiltered_datasets | |
| if missing_datasets: | |
| logger.info(f"[RetrievalService] Note: These datasets had no matches in top 300 prefilter: {missing_datasets}") | |
| logger.info(f"[RetrievalService] This is normal if they don't contain relevant content for this query.") | |
| # If embeddings are ready, re-rank the prefiltered set with semantic similarity | |
| if self._embedding_ready() and not disable_embeddings: | |
| logger.info("[RetrievalService] Using embedding-based rerank on prefiltered set.") | |
| query_vec = self._get_embedding(query) | |
| if query_vec and any(v != 0.0 for v in query_vec): | |
| # Batch-embed any prefiltered texts not in cache | |
| texts_to_embed = [] | |
| idx_map = [] # indices of prefiltered needing embeddings | |
| for idx, c in enumerate(prefiltered): | |
| if c["text"] not in self._embeddings_cache: | |
| texts_to_embed.append(c["text"]) | |
| idx_map.append(idx) | |
| if texts_to_embed: | |
| logger.info(f"[RetrievalService] Batch embedding {len(texts_to_embed)} prefiltered chunks...") | |
| batch_vecs = self._embed_batch(texts_to_embed) | |
| for i, vec in zip(idx_map, batch_vecs): | |
| self._embeddings_cache[prefiltered[i]["text"]] = vec | |
| # Compute cosine similarity using cached (or newly embedded) vectors | |
| for c in prefiltered: | |
| vec = self._embeddings_cache.get(c["text"], []) | |
| c["score"] = cosine_similarity(query_vec, vec) | |
| ranked = sorted(prefiltered, key=lambda x: x["score"], reverse=True) | |
| # Apply diversity filter if requested (ensures results from multiple datasets) | |
| if ensure_diversity and len(active_datasets) > 1: | |
| ranked = self._apply_diversity_filter(ranked, top_k, active_datasets) | |
| logger.info(f"[RetrievalService] Applied diversity filter: {len(ranked)} chunks from {len(set(c['dataset'] for c in ranked))} datasets.") | |
| else: | |
| ranked = ranked[:top_k] | |
| logger.info(f"[RetrievalService] Returning top {len(ranked)} chunks (embedding rerank, no diversity filter).") | |
| return ranked | |
| else: | |
| logger.warning("[RetrievalService] Embedding unavailable, using lexical scores only.") | |
| # No embeddings: use lexical scores | |
| ranked = sorted(prefiltered, key=lambda x: x["_lex"], reverse=True) | |
| if ensure_diversity and len(active_datasets) > 1: | |
| ranked = self._apply_diversity_filter(ranked, top_k, active_datasets) | |
| logger.info(f"[RetrievalService] Applied diversity filter (lexical): {len(ranked)} chunks from {len(set(c['dataset'] for c in ranked))} datasets.") | |
| else: | |
| ranked = ranked[:top_k] | |
| logger.info(f"[RetrievalService] Returning top {len(ranked)} chunks (lexical only, no diversity filter).") | |
| return ranked | |
| def _apply_diversity_filter(self, ranked_chunks: List[Dict[str, Any]], top_k: int, active_datasets: List[str]) -> List[Dict[str, Any]]: | |
| """ | |
| Ensures results are distributed across multiple datasets for better coverage. | |
| Uses round-robin strategy to include top results from each dataset. | |
| Critical for investor prototype with 100s of dictionaries - ensures all relevant | |
| datasets are represented in results, not just the top-scoring ones. | |
| """ | |
| # Group chunks by dataset | |
| by_dataset = {} | |
| for chunk in ranked_chunks: | |
| ds = chunk["dataset"] | |
| if ds not in by_dataset: | |
| by_dataset[ds] = [] | |
| by_dataset[ds].append(chunk) | |
| # Calculate how many datasets have relevant results | |
| num_datasets = len(by_dataset) | |
| logger.info(f"[RetrievalService] Diversity filter: {num_datasets} datasets have relevant results out of {len(active_datasets)} active.") | |
| # Diagnostic: Log if some datasets didn't make it to final results | |
| # This is informational only - we prioritize quality over forced diversity | |
| missing_datasets = set(active_datasets) - set(by_dataset.keys()) | |
| if missing_datasets: | |
| logger.info(f"[RetrievalService] Note: These datasets had no results in final ranking: {missing_datasets}") | |
| logger.info(f"[RetrievalService] This means they don't contain relevant content for this specific query.") | |
| if num_datasets == 0: | |
| return [] | |
| # Strategy: Ensure minimum representation from each dataset, then fill remaining with top scores | |
| # For investor prototype with 100+ dicts: ensure better balance | |
| if num_datasets <= 5: | |
| # For small numbers of datasets: guarantee representation from ALL | |
| min_per_dataset = max(3, top_k // num_datasets) # More balanced - e.g., 25/4 = 6 per dataset | |
| else: | |
| min_per_dataset = max(2, top_k // (num_datasets * 2)) # At least 2-3 per dataset for many datasets | |
| remaining_slots = top_k | |
| results = [] | |
| dataset_quotas = {ds: min_per_dataset for ds in by_dataset.keys()} | |
| # Phase 1: Get minimum from each dataset (round-robin) | |
| for ds in sorted(by_dataset.keys()): # Sort for deterministic order | |
| quota = min(dataset_quotas[ds], len(by_dataset[ds])) | |
| results.extend(by_dataset[ds][:quota]) | |
| by_dataset[ds] = by_dataset[ds][quota:] # Remove used chunks | |
| remaining_slots -= quota | |
| # Phase 2: Fill remaining slots with highest-scoring chunks across all datasets | |
| all_remaining = [] | |
| for ds, chunks in by_dataset.items(): | |
| all_remaining.extend(chunks) | |
| # Sort remaining by score and add until we hit top_k | |
| score_key = "score" if "score" in ranked_chunks[0] else "_lex" | |
| all_remaining_sorted = sorted(all_remaining, key=lambda x: x.get(score_key, 0), reverse=True) | |
| results.extend(all_remaining_sorted[:remaining_slots]) | |
| # Final sort by score to maintain quality order | |
| results = sorted(results, key=lambda x: x.get(score_key, 0), reverse=True)[:top_k] | |
| # Log dataset distribution | |
| dataset_counts = {} | |
| for chunk in results: | |
| ds = chunk["dataset"] | |
| dataset_counts[ds] = dataset_counts.get(ds, 0) + 1 | |
| logger.info(f"[RetrievalService] Final distribution: {dataset_counts}") | |
| return results | |
| # -------------------- Embeddings Helpers -------------------- # | |
| def _embedding_ready(self) -> bool: | |
| return all([self._embedding_endpoint, self._embedding_key, self._embedding_deployment]) | |
| def _get_embedding(self, text: str) -> List[float]: | |
| if text in self._embeddings_cache: | |
| return self._embeddings_cache[text] | |
| url = f"{self._embedding_endpoint}/openai/deployments/{self._embedding_deployment}/embeddings?api-version={self._api_version}" | |
| headers = {"Content-Type": "application/json", "api-key": self._embedding_key} | |
| data = {"input": text} | |
| try: | |
| is_chunk = text in self._chunk_texts_set | |
| logger.info(f"[RetrievalService] π NEW EMBEDDING GENERATED: text length={len(text)} chars (type: {'CHUNK' if is_chunk else 'QUERY'})") | |
| logger.info(f"[RetrievalService] Requesting embedding from Azure OpenAI...") | |
| resp = requests.post(url, headers=headers, json=data, timeout=10) | |
| resp.raise_for_status() | |
| vec = resp.json()["data"][0]["embedding"] | |
| self._embeddings_cache[text] = vec | |
| # Only persist CHUNK embeddings to disk (not query embeddings) | |
| if is_chunk: | |
| save_json(self._embeds_path, self._embeddings_cache) | |
| logger.info(f"[RetrievalService] β Chunk embedding persisted to disk") | |
| # Update cache size in session state | |
| cache_size = len(self._embeddings_cache) | |
| logger.info(f"[RetrievalService] β Embedding received. Cache now has {cache_size} embeddings") | |
| self._update_session_state() | |
| return vec | |
| except Exception as e: | |
| logger.error(f"[RetrievalService] Embedding API call failed: {e}") | |
| # On any failure, return empty vector to trigger lexical fallback | |
| return [] | |
| def _embed_batch(self, texts: List[str]) -> List[List[float]]: | |
| """Embed multiple texts in a single request (or minimal number of requests). | |
| Returns vectors in the same order as input texts. On failure, returns empty vectors. | |
| Always persists to disk since this is called only for chunks. | |
| """ | |
| if not texts: | |
| return [] | |
| url = f"{self._embedding_endpoint}/openai/deployments/{self._embedding_deployment}/embeddings?api-version={self._api_version}" | |
| headers = {"Content-Type": "application/json", "api-key": self._embedding_key} | |
| try: | |
| logger.info(f"[RetrievalService] π BATCH EMBEDDINGS: Generating {len(texts)} new chunk embeddings...") | |
| resp = requests.post(url, headers=headers, json={"input": texts}, timeout=20) | |
| resp.raise_for_status() | |
| data = resp.json().get("data", []) | |
| # Azure returns embeddings in the same order as inputs | |
| vectors = [item.get("embedding", []) for item in data] | |
| # Cache all embeddings | |
| for text, vec in zip(texts, vectors): | |
| if vec: | |
| self._embeddings_cache[text] = vec | |
| cache_size = len(self._embeddings_cache) | |
| logger.info(f"[RetrievalService] β Batch complete. Generated {len(vectors)} chunk embeddings. Total in-memory cache: {cache_size} embeddings") | |
| if len(vectors) != len(texts): | |
| logger.warning("[RetrievalService] Mismatch in batch embeddings count; falling back to empty vectors for missing entries.") | |
| # pad to expected length | |
| while len(vectors) < len(texts): | |
| vectors.append([]) | |
| # Update cache and persist (these are all chunks) | |
| for txt, vec in zip(texts, vectors): | |
| self._embeddings_cache[txt] = vec | |
| save_json(self._embeds_path, self._embeddings_cache) | |
| logger.info(f"[RetrievalService] πΎ Chunk embeddings persisted to disk") | |
| self._update_session_state() | |
| return vectors | |
| except Exception as e: | |
| logger.error(f"[RetrievalService] Batch embedding failed: {e}") | |
| return [[] for _ in texts] | |
| # -------------------- Cache Helpers -------------------- # | |
| def _compute_corpus_signature(self) -> str: | |
| hasher = hashlib.sha256() | |
| # Use names + sizes + head/tail slices for a stable signature | |
| for name in sorted(self.data_service.data_dictionaries.keys()): | |
| content = self.data_service.data_dictionaries.get(name, "") | |
| head = content[:1024] | |
| tail = content[-1024:] | |
| hasher.update(name.encode("utf-8", errors="ignore")) | |
| hasher.update(str(len(content)).encode("utf-8")) | |
| hasher.update(head.encode("utf-8", errors="ignore")) | |
| hasher.update(tail.encode("utf-8", errors="ignore")) | |
| return hasher.hexdigest() | |
| def _load_cached_index(self): | |
| try: | |
| sig = self._sig_path.read_text(encoding="utf-8") if self._sig_path.exists() else "" | |
| if sig and sig == self._corpus_sig: | |
| cached = load_json(self._chunks_path) | |
| if isinstance(cached, list): | |
| self.chunks = cached | |
| logger.info(f"[RetrievalService] Loaded {len(self.chunks)} chunks from cache.") | |
| except Exception: | |
| pass | |
| def _load_cached_embeddings(self): | |
| try: | |
| cached = load_json(self._embeds_path) | |
| if isinstance(cached, dict): | |
| self._embeddings_cache = cached | |
| logger.info(f"[RetrievalService] Loaded {len(self._embeddings_cache)} embeddings from cache.") | |
| except Exception: | |
| pass | |
| # -------------------- Utility Functions -------------------- # | |
| def tokenize(text: str) -> set: | |
| return set(re.findall(r"[a-zA-Z0-9_]+", text.lower())) | |
| def cosine_similarity(a: List[float], b: List[float]) -> float: | |
| if not a or not b or len(a) != len(b): | |
| return 0.0 | |
| dot = sum(x * y for x, y in zip(a, b)) | |
| na = math.sqrt(sum(x * x for x in a)) | |
| nb = math.sqrt(sum(y * y for y in b)) | |
| if na == 0 or nb == 0: | |
| return 0.0 | |
| return dot / (na * nb) | |
| # -------------------- Prompt Assembly Helper -------------------- # | |
| def format_retrieved_chunks(chunks: List[Dict[str, Any]]) -> str: | |
| if not chunks: | |
| return "" | |
| parts = ["### Retrieved Relevant Entries (Always cite the Dataset name when recommending columns)"] | |
| for i, c in enumerate(chunks, start=1): | |
| parts.append(f"{i}. **Dataset: {c['dataset']}** | {c['text']}") | |
| return "\n".join(parts) | |
| if __name__ == "__main__": | |
| # Simple manual test (requires data service mock) | |
| class DummyDataService: | |
| def __init__(self): | |
| self.data_dictionaries = {"TEST_DICT": "COLUMN_A Description of A\nCOLUMN_B Description about B and health\nCOLUMN_C Irrelevant line"} | |
| ds = DummyDataService() | |
| rs = RetrievalService(ds) | |
| rs.index() | |
| results = rs.search("health columns", ["TEST_DICT"], top_k=5) | |
| print(format_retrieved_chunks(results)) | |