File size: 9,678 Bytes
0231daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""
Single/Batch embedding generation endpoints.

This module provides routes for generating embeddings for
multiple texts in a single request.
"""

import time
from typing import Union
from fastapi import APIRouter, Depends, HTTPException, status
from loguru import logger

from src.models.schemas import (
    EmbedRequest,
    DenseEmbedResponse,
    SparseEmbedResponse,
    SparseEmbedding,
)
from src.core.manager import ModelManager
from src.core.cache import EmbeddingCache
from src.core.exceptions import (
    ModelNotFoundError,
    ModelNotLoadedError,
    EmbeddingGenerationError,
    ValidationError,
)
from src.api.dependencies import get_model_manager, get_cache_if_enabled
from src.utils.validators import extract_embedding_kwargs, validate_texts
from src.config.settings import get_settings


router = APIRouter(prefix="/embeddings", tags=["embeddings"])


@router.post(
    "/embed",
    response_model=Union[DenseEmbedResponse, SparseEmbedResponse],
    summary="Generate single/batch embeddings spesialization document",
    description="Generate embeddings for multiple texts in a single request",
)
async def create_embeddings_document(
    request: EmbedRequest,
    manager: ModelManager = Depends(get_model_manager),
    cache: EmbeddingCache = Depends(get_cache_if_enabled),
    settings=Depends(get_settings),
):
    """
    Generate embeddings for multiple texts.

    This endpoint efficiently processes multiple texts in a single batch,
    reducing overhead compared to multiple single requests.

    Args:
        request: BatchEmbedRequest with texts, model_id, and optional parameters
        manager: Model manager dependency
        cache: Cache dependency (if enabled)
        settings: Application settings

    Returns:
        DenseEmbedResponse or SparseEmbedResponse depending on model type

    Raises:
        HTTPException: On validation or generation errors
    """
    try:
        # Validate input
        validate_texts(
            request.texts,
            max_length=settings.MAX_TEXT_LENGTH,
            max_batch_size=settings.MAX_BATCH_SIZE,
        )

        # Extract kwargs
        kwargs = extract_embedding_kwargs(request)

        # Check cache first (batch requests typically not cached due to size)
        # But we can cache if batch is small
        if cache is not None and len(request.texts) <= 10:
            cache_key = str(sorted(request.texts))  # Simple key for small batches
            cached_result = cache.get(
                texts=cache_key,
                model_id=request.model_id,
                prompt=request.prompt,
                **kwargs,
            )
            if cached_result is not None:
                logger.debug(f"Cache hit for batch (size={len(request.texts)})")
                return cached_result

        # Get model
        model = manager.get_model(request.model_id)
        config = manager.model_configs[request.model_id]

        start_time = time.time()

        # Generate embeddings based on model type
        if config.type == "sparse-embeddings":
            # Sparse batch embeddings
            sparse_results = model.embed_documents(
                texts=request.texts, prompt=request.prompt, **kwargs
            )
            processing_time = time.time() - start_time

            # Convert to SparseEmbedding objects
            sparse_embeddings = []
            for idx, sparse_result in enumerate(sparse_results):
                sparse_embeddings.append(
                    SparseEmbedding(
                        text=request.texts[idx],
                        indices=sparse_result["indices"],
                        values=sparse_result["values"],
                    )
                )

            response = SparseEmbedResponse(
                embeddings=sparse_embeddings,
                count=len(sparse_embeddings),
                model_id=request.model_id,
                processing_time=processing_time,
            )
        else:
            # Dense batch embeddings
            embeddings = model.embed_documents(
                texts=request.texts, prompt=request.prompt, **kwargs
            )
            processing_time = time.time() - start_time

            response = DenseEmbedResponse(
                embeddings=embeddings,
                dimension=len(embeddings[0]) if embeddings else 0,
                count=len(embeddings),
                model_id=request.model_id,
                processing_time=processing_time,
            )

        # Cache small batches
        if cache is not None and len(request.texts) <= 10:
            cache_key = str(sorted(request.texts))
            cache.set(
                texts=cache_key,
                model_id=request.model_id,
                result=response,
                prompt=request.prompt,
                **kwargs,
            )

        logger.info(
            f"Generated {len(request.texts)} embeddings "
            f"in {processing_time:.3f}s ({len(request.texts) / processing_time:.1f} texts/s)"
        )

        return response

    except (ValidationError, ModelNotFoundError) as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except ModelNotLoadedError as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except EmbeddingGenerationError as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except Exception as e:
        logger.exception("Unexpected error in create_embeddings_document")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to create batch embeddings: {str(e)}",
        )


@router.post(
    "/query",
    response_model=Union[DenseEmbedResponse, SparseEmbedResponse],
    summary="Generate single/batch embeddings spesialization document",
    description="Generate embedding for a multiple query text",
)
async def create_query_embedding(
    request: EmbedRequest,
    manager: ModelManager = Depends(get_model_manager),
    cache: EmbeddingCache = Depends(get_cache_if_enabled),
    settings=Depends(get_settings),
):
    """
    Generate a single/batch query embedding.

    This endpoint creates embeddings optimized for search queries.
    Some models differentiate between query and document embeddings.

    Args:
        request: EmbedRequest with text, model_id, and optional parameters
        manager: Model manager dependency
        cache: Cache dependency (if enabled)
        settings: Application settings

    Returns:
        DenseEmbedResponse or SparseEmbedResponse depending on model type

    Raises:
        HTTPException: On validation or generation errors
    """
    try:
        # Validate input
        validate_texts(request.texts)

        # Extract kwargs
        kwargs = extract_embedding_kwargs(request)

        # Check cache (with 'query' prefix in key)
        cache_key_kwargs = {"endpoint": "query", **kwargs}

        if cache is not None:
            cached_result = cache.get(
                texts=request.text,
                model_id=request.model_id,
                prompt=request.prompt,
                **cache_key_kwargs,
            )
            if cached_result is not None:
                logger.debug(f"Cache hit for query model {request.model_id}")
                return cached_result

        # Get model
        model = manager.get_model(request.model_id)
        config = manager.model_configs[request.model_id]

        start_time = time.time()

        # Generate embedding based on model type
        if config.type == "sparse-embeddings":
            # Sparse embedding
            sparse_results = model.embed_query(
                texts=request.texts, prompt=request.prompt, **kwargs
            )
            processing_time = time.time() - start_time

            sparse_result = sparse_results[0]
            sparse_embedding = SparseEmbedding(
                text=request.texts,
                indices=sparse_result["indices"],
                values=sparse_result["values"],
            )

            response = SparseEmbedResponse(
                sparse_embedding=sparse_embedding,
                model_id=request.model_id,
                processing_time=processing_time,
            )
        else:
            # Dense embedding
            embeddings = model.embed_query(
                texts=request.texts, prompt=request.prompt, **kwargs
            )
            processing_time = time.time() - start_time

            response = DenseEmbedResponse(
                embedding=embeddings[0],
                dimension=len(embeddings[0]),
                model_id=request.model_id,
                processing_time=processing_time,
            )

        # Cache the result
        if cache is not None:
            cache.set(
                texts=request.texts,
                model_id=request.model_id,
                result=response,
                prompt=request.prompt,
                **cache_key_kwargs,
            )

        return response

    except (ValidationError, ModelNotFoundError) as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except ModelNotLoadedError as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except EmbeddingGenerationError as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except Exception as e:
        logger.exception("Unexpected error in create_query_embedding")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to create query embedding: {str(e)}",
        )