"""Local ONNX embedding models with explicit encoder contracts. Each contract pins the model, dimension, target column and query/passage prefixes. Queries must be embedded with the same contract as the column they search; scores from different contracts are never compared directly (use RRF). """ from __future__ import annotations from dataclasses import asdict, dataclass from functools import lru_cache @dataclass(frozen=True) class EncoderContract: key: str model: str dim: int column: str model_column: str query_prefix: str = "" passage_prefix: str = "" normalized: bool = True distance: str = "cosine" runtime: str = "fastembed-onnx" weights: str = "" # exact weight source actually executed (repo@revision/file) def as_dict(self) -> dict: return asdict(self) CONTRACTS: dict[str, EncoderContract] = { "bge": EncoderContract( key="bge", model="BAAI/bge-small-en-v1.5", dim=384, column="embedding", model_column="embedding_model", query_prefix="Represent this sentence for searching relevant passages: ", weights="Qdrant/bge-small-en-v1.5-onnx-Q@aa8f8b060edb00e03bfdd08813a2949946c8ba55/model_optimized.onnx (quantized)", ), "gte": EncoderContract( key="gte", model="Supabase/gte-small", dim=384, column="embedding_edge", model_column="embedding_edge_model", weights="Supabase/gte-small@93b36ff09519291b77d6000d2e86bd8565378086/onnx/model.onnx (mean pool, L2)", ), } @lru_cache(maxsize=None) def _model(key: str): from fastembed import TextEmbedding c = CONTRACTS[key] if key == "gte": from fastembed.common.model_description import ModelSource, PoolingType known = {m["model"] for m in TextEmbedding.list_supported_models()} if c.model not in known: TextEmbedding.add_custom_model( model=c.model, pooling=PoolingType.MEAN, normalization=True, sources=ModelSource(hf=c.model), dim=c.dim, model_file="onnx/model.onnx", ) import os cache = os.environ.get("FASTEMBED_CACHE_PATH") or os.path.expanduser("~/.cache/fastembed") return TextEmbedding(c.model, cache_dir=cache) def embed_passages(key: str, texts: list[str], batch_size: int = 16) -> list[list[float]]: c = CONTRACTS[key] vecs = _model(key).embed([c.passage_prefix + t for t in texts], batch_size=batch_size) out = [[float(x) for x in v] for v in vecs] _check(c, out) return out def embed_query(key: str, text: str) -> list[float]: c = CONTRACTS[key] # Prefixes are applied explicitly so the contract, not library defaults, governs them. out = [[float(x) for x in v] for v in _model(key).embed([c.query_prefix + text])] _check(c, out) return out[0] def _check(c: EncoderContract, vecs: list[list[float]]) -> None: for v in vecs: if len(v) != c.dim: raise ValueError(f"{c.model} produced dim {len(v)}, contract says {c.dim}") def to_pgvector(v: list[float]) -> str: return "[" + ",".join(f"{x:.7g}" for x in v) + "]"