File size: 8,654 Bytes
e70c280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5583f46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e70c280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""
File: /embeddings.py
Created Date: Sunday October 19th 2025
Author: Christian Nonis <alch.infoemail@gmail.com>
-----
Last Modified: Thursday January 29th 2026 8:43:59 pm
Modified By: Christian Nonis <alch.infoemail@gmail.com>
-----
"""

import uuid
try:
    from tenacity import (
        retry,
        stop_after_attempt,
        wait_exponential,
        retry_if_exception_type,
        RetryError,
    )
except ModuleNotFoundError:
    def retry(*args, **kwargs):
        def _decorator(func):
            return func

        return _decorator

    def stop_after_attempt(*args, **kwargs):
        return None

    def wait_exponential(*args, **kwargs):
        return None

    def retry_if_exception_type(*args, **kwargs):
        return None

    class RetryError(Exception):
        pass

from src.adapters.interfaces.embeddings import EmbeddingsClient, VectorStoreClient
from src.constants.embeddings import Vector
try:
    from src.lib.embeddings.client import EmbeddingError
except ModuleNotFoundError:
    class EmbeddingError(Exception):
        pass


class EmbeddingFailureStrategy:
    def on_single_failure(self, error: EmbeddingError) -> Vector:
        raise NotImplementedError

    def on_batch_failure(self, error: EmbeddingError, count: int) -> list[Vector]:
        raise NotImplementedError


class ReturnEmptyVectorStrategy(EmbeddingFailureStrategy):
    def on_single_failure(self, error: EmbeddingError) -> Vector:
        print(f"Embedding failed in adapter, returning empty vector: {error}")
        return Vector(id=str(uuid.uuid4()), embeddings=[], metadata={})

    def on_batch_failure(self, error: EmbeddingError, count: int) -> list[Vector]:
        print(f"Embedding failed in adapter, returning empty vectors: {error}")
        return [Vector(id=str(uuid.uuid4()), embeddings=[], metadata={}) for _ in range(count)]


class RaiseEmbeddingFailureStrategy(EmbeddingFailureStrategy):
    def on_single_failure(self, error: EmbeddingError) -> Vector:
        raise error

    def on_batch_failure(self, error: EmbeddingError, count: int) -> list[Vector]:
        raise error


class EmbeddingsAdapter:
    def __init__(self, failure_strategy: EmbeddingFailureStrategy | None = None):
        self.embeddings = None
        self.failure_strategy = failure_strategy or ReturnEmptyVectorStrategy()

    def add_client(self, client: EmbeddingsClient) -> None:
        """
        Add a embeddings client to the adapter.
        """
        self.embeddings = client

    def set_failure_strategy(self, strategy: EmbeddingFailureStrategy) -> None:
        self.failure_strategy = strategy

    def _to_embedding_error(self, error: Exception) -> EmbeddingError:
        if isinstance(error, EmbeddingError):
            return error
        if isinstance(error, RetryError):
            last_attempt = getattr(error, "last_attempt", None)
            if last_attempt and hasattr(last_attempt, "exception"):
                last_exception = last_attempt.exception()
                if isinstance(last_exception, EmbeddingError):
                    return last_exception
                if isinstance(last_exception, Exception):
                    return EmbeddingError(str(last_exception))
        return EmbeddingError(str(error))

    @retry(
        stop=stop_after_attempt(5),
        wait=wait_exponential(multiplier=1, min=2, max=30),
        retry=retry_if_exception_type(EmbeddingError),
    )
    def _embed_text_with_retry(self, text: str) -> list[float]:
        return self.embeddings.embed_text(text)

    @retry(
        stop=stop_after_attempt(5),
        wait=wait_exponential(multiplier=1, min=2, max=30),
        retry=retry_if_exception_type(EmbeddingError),
    )
    def _embed_texts_with_retry(self, texts: list[str]) -> list[list[float]]:
        return self.embeddings.embed_texts(texts)

    def embed_text(self, text: str) -> Vector:
        """
        Embed a text and return a vector.
        """
        try:
            embeddings = self._embed_text_with_retry(text)
            return Vector(id=str(uuid.uuid4()), embeddings=embeddings, metadata={})
        except (EmbeddingError, RetryError) as e:
            return self.failure_strategy.on_single_failure(self._to_embedding_error(e))

    @retry(
        stop=stop_after_attempt(5),
        wait=wait_exponential(multiplier=1, min=2, max=30),
        retry=retry_if_exception_type(EmbeddingError),
    )
    def _embed_query_with_retry(self, text: str) -> list[float]:
        return self.embeddings.embed_query(text)

    def embed_query(self, text: str) -> Vector:
        """Apply provider-specific query steering before the shared vector transform."""
        try:
            return Vector(id=str(uuid.uuid4()), embeddings=self._embed_query_with_retry(text), metadata={})
        except (EmbeddingError, RetryError) as e:
            return self.failure_strategy.on_single_failure(self._to_embedding_error(e))

    def embed_texts(self, texts: list[str]) -> list[Vector]:
        """
        Embed a list of texts and return a list of vectors.
        """
        try:
            embeddings_list = self._embed_texts_with_retry(texts)
            return [
                Vector(id=str(uuid.uuid4()), embeddings=embeddings, metadata={})
                for embeddings in embeddings_list
            ]
        except (EmbeddingError, RetryError) as e:
            return self.failure_strategy.on_batch_failure(
                self._to_embedding_error(e), len(texts)
            )


class VectorStoreAdapter:
    def __init__(self):
        self.vector_store = None

    def add_client(self, client: VectorStoreClient) -> None:
        """
        Add a vector store client to the adapter.
        """
        self.vector_store = client

    def add_vectors(
        self, vectors: list[Vector], store: str, brain_id: str = "default"
    ) -> list[str]:
        """
        Add vectors to the vector store.
        """
        return self.vector_store.add_vectors(vectors, store, brain_id)

    def search_vectors(
        self,
        data_vector: list[float],
        brain_id: str = "default",
        store: str = "default",
        k: int = 10,
    ) -> list[Vector]:
        """
        Search vectors in the vector store and return the top k vectors.
        """
        from src.utils.vector_search import stable_top_k_vectors

        vectors = self.vector_store.search_vectors(data_vector, brain_id, store, k)
        return stable_top_k_vectors(list(vectors), k)

    def get_by_ids(
        self, ids: list[str], store: str, brain_id: str = "default"
    ) -> list[Vector]:
        """
        Get vectors by their IDs.
        """
        return self.vector_store.get_by_ids(ids, store, brain_id)

    def search_similar_by_ids(
        self,
        vector_ids: list[str],
        brain_id: str,
        store: str,
        min_similarity: float,
        limit: int = 10,
    ) -> dict[str, list[Vector]]:
        """
        Finds vectors similar to the provided vector IDs within a specified store and brain.

        Parameters:
            vector_ids (list[str]): IDs of the source vectors to find similarities for.
            brain_id (str): Identifier of the brain/namespace to search within.
            store (str): Name of the vector store to query.
            min_similarity (float): Minimum similarity threshold for returned vectors (inclusive).
            limit (int): Maximum number of similar vectors to return per source ID.

        Returns:
            dict[str, list[Vector]]: Mapping from each source vector ID to a list of similar Vectors.
            Each list contains at most `limit` items, includes only vectors with similarity >= `min_similarity`,
            and is ordered by descending similarity.
        """
        return self.vector_store.search_similar_by_ids(
            vector_ids, brain_id, store, min_similarity, limit
        )

    def remove_vectors(
        self, ids: list[str], store: str, brain_id: str = "default"
    ) -> None:
        """
        Remove vectors from the vector store.
        """
        return self.vector_store.remove_vectors(ids, store, brain_id)

    def list_vectors(
        self,
        store: str,
        brain_id: str = "default",
        limit: int = 10,
        skip: int = 0,
        include_embeddings: bool = False,
    ) -> tuple[list[Vector], int]:
        """
        List vectors in a store with pagination.
        """
        return self.vector_store.list_vectors(
            store, brain_id, limit, skip, include_embeddings
        )


_embeddings_adapter = EmbeddingsAdapter()
_vector_store_adapter = VectorStoreAdapter()