|
|
"""Compatibility wrapper for vector adapters.
|
|
|
|
|
|
Provides `InMemoryVectorIndex` to keep older imports working and attempts to
|
|
|
use FAISS adapter if present.
|
|
|
"""
|
|
|
from typing import List, Tuple
|
|
|
try:
|
|
|
|
|
|
from .vector_adapter_full import FaissIndex, HostedVectorAdapter
|
|
|
FAISS_AVAILABLE = True
|
|
|
except Exception:
|
|
|
FAISS_AVAILABLE = False
|
|
|
|
|
|
import math
|
|
|
|
|
|
|
|
|
class InMemoryVectorIndex:
|
|
|
def __init__(self):
|
|
|
self.data: List[Tuple[str, List[float]]] = []
|
|
|
|
|
|
def upsert(self, id: str, vector: List[float]):
|
|
|
self.data.append((id, vector))
|
|
|
|
|
|
def search(self, vector: List[float], top_k: int = 10):
|
|
|
def score(a, b):
|
|
|
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(x * x for x in b))
|
|
|
return dot / (na * nb) if na and nb else 0.0
|
|
|
|
|
|
scored = [(id, score(vec, vector)) for id, vec in self.data]
|
|
|
scored.sort(key=lambda x: x[1], reverse=True)
|
|
|
return scored[:top_k]
|
|
|
|