Spaces:
Running
Running
Download infrastructure/vector_search.py from phaethon-order/tech-trans-rag: direct link, hf CLI and curl.
- Browser
- Download file 6.72 kB
-
https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/infrastructure/vector_search.py
- Command line
-
hf download hf://spaces/phaethon-order/tech-trans-rag/infrastructure/vector_search.py
-
curl -L -o vector_search.py https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/infrastructure/vector_search.py
6.72 kB
| """Hybrid semantic and lexical retrieval backed by Neon Postgres.""" | |
| from __future__ import annotations | |
| import math | |
| import re | |
| from typing import Any | |
| from infrastructure.database import ( | |
| search_lexical_candidates, | |
| search_vector_candidates, | |
| ) | |
| from infrastructure.embeddings import DEFAULT_MODEL, generate_embedding | |
| from infrastructure.logger import get_logger | |
| logger = get_logger() | |
| RRF_K = 60 | |
| MMR_LAMBDA = 0.85 | |
| MAX_CANDIDATES = 100 | |
| MIN_CANDIDATES = 20 | |
| CANDIDATE_MULTIPLIER = 4 | |
| def _candidate_limit(top_k: int) -> int: | |
| return min(MAX_CANDIDATES, max(MIN_CANDIDATES, top_k * CANDIDATE_MULTIPLIER)) | |
| def _cosine_similarity(left: list[float], right: list[float]) -> float: | |
| if len(left) != len(right) or not left: | |
| return 0.0 | |
| left_norm = math.sqrt(sum(value * value for value in left)) | |
| right_norm = math.sqrt(sum(value * value for value in right)) | |
| if not left_norm or not right_norm: | |
| return 0.0 | |
| similarity = sum(a * b for a, b in zip(left, right, strict=True)) / ( | |
| left_norm * right_norm | |
| ) | |
| return max(0.0, min(1.0, similarity)) | |
| def _normalized_text(text: str) -> str: | |
| return re.sub(r"\s+", " ", text).strip().casefold() | |
| def fuse_and_select( | |
| vector_candidates: list[dict[str, Any]], | |
| lexical_candidates: list[dict[str, Any]], | |
| *, | |
| top_k: int, | |
| ) -> list[dict[str, Any]]: | |
| """Fuse candidate ranks with RRF, then select diverse results with MMR.""" | |
| merged: dict[int, dict[str, Any]] = {} | |
| for rank, candidate in enumerate(vector_candidates, start=1): | |
| chunk_id = int(candidate["chunk_id"]) | |
| item = merged.setdefault(chunk_id, dict(candidate)) | |
| item.update(candidate) | |
| item["vector_rank"] = rank | |
| for rank, candidate in enumerate(lexical_candidates, start=1): | |
| chunk_id = int(candidate["chunk_id"]) | |
| item = merged.setdefault(chunk_id, dict(candidate)) | |
| vector_rank = item.get("vector_rank") | |
| distance = item.get("distance") | |
| vector = item.get("embedding") | |
| item.update(candidate) | |
| if vector_rank is not None: | |
| item["vector_rank"] = vector_rank | |
| item["distance"] = distance | |
| item["embedding"] = vector | |
| item["lexical_rank"] = rank | |
| candidates: list[dict[str, Any]] = [] | |
| for item in merged.values(): | |
| vector_rank = item.get("vector_rank") | |
| lexical_rank = item.get("lexical_rank") | |
| item["rrf_score"] = sum( | |
| 1.0 / (RRF_K + rank) | |
| for rank in (vector_rank, lexical_rank) | |
| if rank is not None | |
| ) | |
| if vector_rank is not None and lexical_rank is not None: | |
| item["selection_reason"] = "hybrid" | |
| elif vector_rank is not None: | |
| item["selection_reason"] = "vector" | |
| else: | |
| item["selection_reason"] = "lexical" | |
| candidates.append(item) | |
| candidates.sort( | |
| key=lambda item: ( | |
| -float(item["rrf_score"]), | |
| int(item["chunk_id"]), | |
| ) | |
| ) | |
| unique: list[dict[str, Any]] = [] | |
| seen_text: set[tuple[int, str]] = set() | |
| for item in candidates: | |
| normalized = _normalized_text(str(item.get("text") or "")) | |
| duplicate_key = (int(item["doc_id"]), normalized) | |
| if normalized and duplicate_key in seen_text: | |
| continue | |
| if normalized: | |
| seen_text.add(duplicate_key) | |
| unique.append(item) | |
| selected: list[dict[str, Any]] = [] | |
| max_rrf = max((float(item["rrf_score"]) for item in unique), default=1.0) | |
| remaining = list(unique) | |
| while remaining and len(selected) < top_k: | |
| scored: list[tuple[float, float, int, dict[str, Any]]] = [] | |
| for item in remaining: | |
| relevance = float(item["rrf_score"]) / max_rrf | |
| vector = item.get("embedding") | |
| redundancy = 0.0 | |
| if vector: | |
| redundancy = max( | |
| ( | |
| _cosine_similarity(vector, other["embedding"]) | |
| for other in selected | |
| if other.get("embedding") | |
| ), | |
| default=0.0, | |
| ) | |
| mmr_score = MMR_LAMBDA * relevance - (1.0 - MMR_LAMBDA) * redundancy | |
| scored.append( | |
| ( | |
| mmr_score, | |
| float(item["rrf_score"]), | |
| -int(item["chunk_id"]), | |
| item, | |
| ) | |
| ) | |
| chosen_score, _, _, chosen = max(scored, key=lambda value: value[:3]) | |
| remaining.remove(chosen) | |
| chosen["mmr_score"] = chosen_score | |
| selected.append(chosen) | |
| output: list[dict[str, Any]] = [] | |
| for rank, item in enumerate(selected, start=1): | |
| result = {key: value for key, value in item.items() if key != "embedding"} | |
| result["id"] = str(item["chunk_id"]) | |
| result["document"] = item.get("text") | |
| result["rank"] = rank | |
| output.append(result) | |
| return output | |
| def find_nearest_neighbors( | |
| query: str, | |
| num_neighbors: int, | |
| where: dict[str, Any] | None = None, | |
| where_document: dict[str, Any] | None = None, | |
| ) -> list[dict[str, Any]]: | |
| """Return hybrid-ranked chunks for a natural-language query.""" | |
| if num_neighbors < 1: | |
| return [] | |
| if where_document: | |
| logger.warning("where_document filtering is not supported by Neon search") | |
| candidate_limit = _candidate_limit(num_neighbors) | |
| lexical_candidates = search_lexical_candidates( | |
| query, | |
| limit=candidate_limit, | |
| filters=where, | |
| ) | |
| query_vector = generate_embedding(query, model=DEFAULT_MODEL) | |
| vector_candidates: list[dict[str, Any]] = [] | |
| if query_vector: | |
| vector_candidates = search_vector_candidates( | |
| query_vector, | |
| model=DEFAULT_MODEL, | |
| limit=candidate_limit, | |
| filters=where, | |
| ) | |
| else: | |
| logger.warning("Query embedding failed; continuing with lexical candidates") | |
| return fuse_and_select( | |
| vector_candidates, | |
| lexical_candidates, | |
| top_k=num_neighbors, | |
| ) | |
| def upsert_datapoints(datapoints: list[dict[str, Any]]) -> None: | |
| """Persist legacy datapoints through the Neon embedding API.""" | |
| from infrastructure.database import upsert_embedding | |
| for datapoint in datapoints: | |
| vector = datapoint.get("embedding") or [] | |
| if not vector: | |
| continue | |
| upsert_embedding( | |
| chunk_id=int(datapoint["datapoint_id"]), | |
| model=str(datapoint.get("model") or DEFAULT_MODEL), | |
| dim=len(vector), | |
| vector_bytes=vector, | |
| ) | |
| __all__ = ["find_nearest_neighbors", "fuse_and_select", "upsert_datapoints"] | |