|
| 1 | +"""Adapters and fakes for the RAG evaluation runner. |
| 2 | +
|
| 3 | +This module provides: |
| 4 | +
|
| 5 | +- ``FakeEmbeddingAdapter`` – deterministic, stateless embeddings derived |
| 6 | + from text hashing, suitable for tests and offline runs. |
| 7 | +- ``InMemoryVectorStoreAdapter`` – simple in-memory vector store using |
| 8 | + cosine similarity with deterministic tie-breaking. |
| 9 | +
|
| 10 | +Both adapters implement the ports defined in :mod:`electripy.ai.rag` and |
| 11 | +are intentionally minimal to keep dependencies small and behaviour |
| 12 | +predictable. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import hashlib |
| 18 | +import math |
| 19 | +from collections.abc import Mapping, Sequence |
| 20 | + |
| 21 | +from electripy.ai.rag.domain import Chunk |
| 22 | +from electripy.ai.rag.ports import EmbeddingPort, VectorStorePort |
| 23 | + |
| 24 | + |
| 25 | +class FakeEmbeddingAdapter(EmbeddingPort): |
| 26 | + """Deterministic embedding adapter based on SHA-256 hashing. |
| 27 | +
|
| 28 | + The adapter produces fixed-size embedding vectors whose components |
| 29 | + are derived from the SHA-256 digest of the input text. The mapping |
| 30 | + is purely functional and does not involve any randomness, making it |
| 31 | + suitable for reproducible tests. |
| 32 | +
|
| 33 | + Example: |
| 34 | + >>> adapter = FakeEmbeddingAdapter() |
| 35 | + >>> vectors = adapter.embed_texts(["hello", "world"]) |
| 36 | + >>> len(vectors) == 2 |
| 37 | + True |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__(self, *, dim: int = 16) -> None: |
| 41 | + if dim <= 0: |
| 42 | + raise ValueError("dim must be positive") |
| 43 | + self._dim = dim |
| 44 | + |
| 45 | + def embed_texts(self, texts: Sequence[str]) -> list[list[float]]: |
| 46 | + if not texts: |
| 47 | + return [] |
| 48 | + return [self._embed_single(text) for text in texts] |
| 49 | + |
| 50 | + def _embed_single(self, text: str) -> list[float]: |
| 51 | + digest = hashlib.sha256(text.encode("utf-8")).digest() |
| 52 | + # Use bytes from the digest to populate the vector deterministically. |
| 53 | + values: list[float] = [] |
| 54 | + for i in range(self._dim): |
| 55 | + # Wrap around the digest if needed. |
| 56 | + b = digest[i % len(digest)] |
| 57 | + # Map byte to [-0.5, 0.5] and then scale. |
| 58 | + values.append((float(b) / 255.0) - 0.5) |
| 59 | + # L2-normalise to keep cosine similarity well-behaved. |
| 60 | + norm = math.sqrt(sum(v * v for v in values)) or 1.0 |
| 61 | + return [v / norm for v in values] |
| 62 | + |
| 63 | + |
| 64 | +class InMemoryVectorStoreAdapter(VectorStorePort): |
| 65 | + """In-memory vector store implementing :class:`VectorStorePort`. |
| 66 | +
|
| 67 | + Notes: |
| 68 | + - Stores vectors in process memory only; suitable for tests and |
| 69 | + local evaluation runs. |
| 70 | + - Uses cosine similarity for ranking and breaks ties |
| 71 | + deterministically by chunk id. |
| 72 | + """ |
| 73 | + |
| 74 | + def __init__(self) -> None: |
| 75 | + self._store: dict[str, tuple[Chunk, list[float]]] = {} |
| 76 | + |
| 77 | + def upsert(self, chunks: Sequence[Chunk], vectors: Sequence[list[float]]) -> None: |
| 78 | + if len(chunks) != len(vectors): |
| 79 | + raise ValueError("chunks and vectors must have the same length") |
| 80 | + for chunk, vector in zip(chunks, vectors): |
| 81 | + self._store[chunk.id] = (chunk, list(vector)) |
| 82 | + |
| 83 | + def query( |
| 84 | + self, |
| 85 | + vector: Sequence[float], |
| 86 | + *, |
| 87 | + top_k: int, |
| 88 | + filters: Mapping[str, object] | None = None, |
| 89 | + ) -> list[tuple[Chunk, float]]: |
| 90 | + if top_k <= 0: |
| 91 | + raise ValueError("top_k must be positive") |
| 92 | + if not self._store: |
| 93 | + return [] |
| 94 | + |
| 95 | + # For now, filters are ignored; they are present to satisfy the |
| 96 | + # protocol and keep a future extension point. |
| 97 | + del filters |
| 98 | + |
| 99 | + norm_q = math.sqrt(sum(float(v) * float(v) for v in vector)) or 1.0 |
| 100 | + scores: list[tuple[Chunk, float]] = [] |
| 101 | + for chunk_id, (chunk, stored_vec) in self._store.items(): |
| 102 | + dot = 0.0 |
| 103 | + norm_v = 0.0 |
| 104 | + for a, b in zip(vector, stored_vec): |
| 105 | + fa = float(a) |
| 106 | + fb = float(b) |
| 107 | + dot += fa * fb |
| 108 | + norm_v += fb * fb |
| 109 | + norm_v = math.sqrt(norm_v) or 1.0 |
| 110 | + score = dot / (norm_q * norm_v) |
| 111 | + scores.append((chunk, score)) |
| 112 | + |
| 113 | + # Deterministic ordering: sort by descending score, then chunk id. |
| 114 | + scores.sort(key=lambda item: (-item[1], item[0].id)) |
| 115 | + return scores[:top_k] |
| 116 | + |
| 117 | + def delete_by_document(self, document_id: str) -> None: |
| 118 | + to_delete = [cid for cid, (chunk, _) in self._store.items() if chunk.document_id == document_id] |
| 119 | + for cid in to_delete: |
| 120 | + self._store.pop(cid, None) |
0 commit comments