File size: 8,941 Bytes
e8f9d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# filename: router.py

"""
FastAPI Router for Embeddings Service

This file exposes the EmbeddingsService functionality via a RESTful API
to generate embeddings and rank candidates.

Supported Text Model IDs:
- "multilingual-e5-small"
- "paraphrase-multilingual-MiniLM-L12-v2"
- "bge-m3"

Supported Image Model ID:
- "google/siglip-base-patch16-256-multilingual"
"""

from __future__ import annotations

import logging
from typing import List, Union
from enum import Enum

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field

from .service import ModelConfig, TextModelType, EmbeddingsService

logger = logging.getLogger(__name__)

# Initialize FastAPI router
router = APIRouter(
    tags=["v1"],
    responses={404: {"description": "Not found"}},
)


class ModelType(str, Enum):
    """
    High-level distinction for text vs. image models.
    """

    TEXT = "text"
    IMAGE = "image"


def detect_model_type(model_id: str) -> ModelType:
    """
    Detect whether the provided model ID is for text or image.

    Supported text model IDs:
      - "multilingual-e5-small"
      - "paraphrase-multilingual-MiniLM-L12-v2"
      - "bge-m3"

    Supported image model ID:
      - "google/siglip-base-patch16-256-multilingual"
      (or any model containing "siglip" in its identifier).

    Args:
        model_id: String identifier of the model.

    Returns:
        ModelType.TEXT if it matches one of the recognized text model IDs,
        ModelType.IMAGE if it matches (or contains "siglip").

    Raises:
        ValueError: If the model_id is not recognized as either text or image.
    """
    # Gather all known text model IDs (from TextModelType enum)
    text_model_ids = {m.value for m in TextModelType}

    # Simple check: if it's in text_model_ids, it's text;
    # if 'siglip' is in the model ID, it's recognized as an image model.
    if model_id in text_model_ids:
        return ModelType.TEXT
    elif "siglip" in model_id.lower():
        return ModelType.IMAGE

    error_msg = (
        f"Unsupported model ID: '{model_id}'.\n"
        "Valid text model IDs are: "
        "'multilingual-e5-small', 'paraphrase-multilingual-MiniLM-L12-v2', 'bge-m3'.\n"
        "Valid image model ID contains 'siglip', for example: 'google/siglip-base-patch16-256-multilingual'."
    )
    raise ValueError(error_msg)


# Pydantic Models for request/response
class EmbeddingRequest(BaseModel):
    """
    Request body for embedding creation.

    Model IDs (text):
      - "multilingual-e5-small"
      - "paraphrase-multilingual-MiniLM-L12-v2"
      - "bge-m3"

    Model ID (image):
      - "google/siglip-base-patch16-256-multilingual"
    """

    model: str = Field(
        default=TextModelType.MULTILINGUAL_E5_SMALL.value,
        description=(
            "Model ID to use. Possible text models include: 'multilingual-e5-small', "
            "'paraphrase-multilingual-MiniLM-L12-v2', 'bge-m3'. "
            "For images, you can use: 'google/siglip-base-patch16-256-multilingual' "
            "or any ID containing 'siglip'."
        ),
    )
    input: Union[str, List[str]] = Field(
        ...,
        description=(
            "Input text(s) or image path(s)/URL(s). "
            "Accepts a single string or a list of strings."
        ),
    )


class RankRequest(BaseModel):
    """
    Request body for ranking candidates against queries.

    Model IDs (text):
      - "multilingual-e5-small"
      - "paraphrase-multilingual-MiniLM-L12-v2"
      - "bge-m3"

    Model ID (image):
      - "google/siglip-base-patch16-256-multilingual"
    """

    model: str = Field(
        default=TextModelType.MULTILINGUAL_E5_SMALL.value,
        description=(
            "Model ID to use for the queries. Supported text models: "
            "'multilingual-e5-small', 'paraphrase-multilingual-MiniLM-L12-v2', 'bge-m3'. "
            "For image queries, use an ID containing 'siglip' such as 'google/siglip-base-patch16-256-multilingual'."
        ),
    )
    queries: Union[str, List[str]] = Field(
        ...,
        description=(
            "Query input(s): can be text(s) or image path(s)/URL(s). "
            "If using an image model, ensure your inputs reference valid image paths or URLs."
        ),
    )
    candidates: List[str] = Field(
        ...,
        description=(
            "List of candidate texts to rank against the given queries. "
            "Currently, all candidates must be text."
        ),
    )


class EmbeddingResponse(BaseModel):
    """
    Response structure for embedding creation.
    """

    object: str = "list"
    data: List[dict]
    model: str
    usage: dict


class RankResponse(BaseModel):
    """
    Response structure for ranking results.
    """

    probabilities: List[List[float]]
    cosine_similarities: List[List[float]]


# Initialize the service with default configuration
service_config = ModelConfig()
embeddings_service = EmbeddingsService(config=service_config)


@router.post("/embeddings", response_model=EmbeddingResponse, tags=["embeddings"])
async def create_embeddings(request: EmbeddingRequest):
    """
    Generate embeddings for the provided input text(s) or image(s).

    Supported Model IDs for text:
      - "multilingual-e5-small"
      - "paraphrase-multilingual-MiniLM-L12-v2"
      - "bge-m3"

    Supported Model ID for image:
      - "google/siglip-base-patch16-256-multilingual"

    Steps:
      1. Detects model type (text or image) based on the model ID.
      2. Adjusts the service configuration accordingly.
      3. Produces embeddings via the EmbeddingsService.
      4. Returns embedding vectors along with usage information.

    Raises:
      HTTPException: For any errors during model detection or embedding generation.
    """
    try:
        modality = detect_model_type(request.model)

        # Adjust global config based on the detected modality
        if modality == ModelType.TEXT:
            service_config.text_model_type = TextModelType(request.model)
        else:
            service_config.image_model_id = request.model

        # Generate embeddings asynchronously
        embeddings = await embeddings_service.generate_embeddings(
            input_data=request.input, modality=modality.value
        )

        # Estimate tokens only if it's text
        total_tokens = 0
        if modality == ModelType.TEXT:
            total_tokens = embeddings_service.estimate_tokens(request.input)

        return {
            "object": "list",
            "data": [
                {
                    "object": "embedding",
                    "index": idx,
                    "embedding": emb.tolist(),
                }
                for idx, emb in enumerate(embeddings)
            ],
            "model": request.model,
            "usage": {
                "prompt_tokens": total_tokens,
                "total_tokens": total_tokens,
            },
        }

    except Exception as e:
        error_msg = (
            "Failed to generate embeddings. Please verify your model ID, input data, and server logs.\n"
            f"Error Details: {str(e)}"
        )
        logger.error(error_msg)
        raise HTTPException(status_code=500, detail=error_msg)


@router.post("/rank", response_model=RankResponse, tags=["rank"])
async def rank_candidates(request: RankRequest):
    """
    Rank the given candidate texts against the provided queries.

    Supported Model IDs for text queries:
      - "multilingual-e5-small"
      - "paraphrase-multilingual-MiniLM-L12-v2"
      - "bge-m3"

    Supported Model ID for image queries:
      - "google/siglip-base-patch16-256-multilingual"

    Steps:
      1. Detects model type (text or image) based on the query model ID.
      2. Adjusts the service configuration accordingly.
      3. Generates embeddings for the queries (text or image).
      4. Generates embeddings for the candidates (always text).
      5. Computes cosine similarities and returns softmax-normalized probabilities.

    Raises:
      HTTPException: For any errors during model detection or ranking.
    """
    try:
        modality = detect_model_type(request.model)

        # Adjust global config based on the detected modality
        if modality == ModelType.TEXT:
            service_config.text_model_type = TextModelType(request.model)
        else:
            service_config.image_model_id = request.model

        # Perform the ranking
        results = await embeddings_service.rank(
            queries=request.queries,
            candidates=request.candidates,
            modality=modality.value,
        )
        return results

    except Exception as e:
        error_msg = (
            "Failed to rank candidates. Please verify your model ID, input data, and server logs.\n"
            f"Error Details: {str(e)}"
        )
        logger.error(error_msg)
        raise HTTPException(status_code=500, detail=error_msg)