Spaces:
Running
Running
File size: 6,472 Bytes
0231daa 155ad69 0231daa d9f3e5d 376886a 0231daa 155ad69 0231daa 376886a d57816a 0231daa 155ad69 0231daa 2e2b2b3 0231daa d57816a 0231daa 2e2b2b3 f55bc7f da0b1f1 f55bc7f 0231daa 155ad69 d57816a 0231daa 2e2b2b3 d57816a 0231daa d57816a 0231daa d57816a 2e2b2b3 d57816a 0231daa 2e2b2b3 0231daa 2e2b2b3 0231daa 2e2b2b3 0231daa 155ad69 0231daa 155ad69 0231daa 155ad69 0231daa d57816a 0231daa f55bc7f 2e2b2b3 0231daa a23b910 d57816a 0231daa 2e2b2b3 d57816a 2e2b2b3 d57816a 0231daa d57816a 0231daa 36e672d 2e2b2b3 36e672d 0231daa d57816a 0231daa 2e2b2b3 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 |
"""
Single/Batch embedding generation endpoints.
This module provides routes for generating embeddings for
multiple texts in a single request.
"""
import time
from fastapi import APIRouter, Depends, HTTPException, status
from loguru import logger
from src.models.schemas import (
EmbedRequest,
DenseEmbedResponse,
EmbeddingObject,
TokenUsage,
SparseEmbedResponse,
SparseEmbedding,
)
from src.core.manager import ModelManager
from src.core.exceptions import (
ModelNotFoundError,
ModelNotLoadedError,
EmbeddingGenerationError,
ValidationError,
)
from src.api.dependencies import get_model_manager
from src.utils.validators import (
extract_embedding_kwargs,
count_tokens_batch,
)
router = APIRouter(tags=["embeddings"])
def _ensure_model_type(config, expected_type: str, model_id: str) -> None:
"""
Validate that the model configuration matches the expected type.
Raises:
HTTPException: If the model is missing or the type does not match.
"""
if config is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Model '{model_id}' not found.",
)
if config.type != expected_type:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
f"Model '{model_id}' is not a {expected_type.replace('-', ' ')} "
f"model. Detected type: {config.type}"
),
)
@router.post(
"/embeddings",
response_model=DenseEmbedResponse,
summary="Generate single/batch embeddings",
description="Generate embeddings for multiple texts in a single request",
)
async def create_embeddings(
request: EmbedRequest, manager: ModelManager = Depends(get_model_manager)
):
"""
Generate embeddings for multiple texts.
The endpoint validates the request, checks that the requested
model is a dense embedding model, and returns a
:class:`DenseEmbedResponse`.
Raises:
HTTPException: On validation or generation errors
"""
texts = [request.input] if isinstance(request.input, str) else request.input
if not texts or not isinstance(texts, list):
raise ValidationError("Input must be a non-empty list or string.")
try:
kwargs = extract_embedding_kwargs(request)
model = manager.get_model(request.model)
config = manager.model_configs.get(request.model)
_ensure_model_type(config, "embeddings", request.model)
start_time = time.time()
embeddings = model.embed(input=texts, **kwargs)
processing_time = time.time() - start_time
data = [
EmbeddingObject(
object="embedding",
embedding=embedding,
index=idx,
)
for idx, embedding in enumerate(embeddings)
]
token_usage = TokenUsage(
prompt_tokens=count_tokens_batch(texts),
total_tokens=count_tokens_batch(texts),
)
response = DenseEmbedResponse(
object="list",
data=data,
model=request.model,
usage=token_usage,
)
logger.info(
f"Generated {len(texts)} embeddings "
f"in {processing_time:.3f}s ({len(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")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to create embeddings: {str(e)}",
)
@router.post(
"/embed_sparse",
response_model=SparseEmbedResponse,
summary="Generate single/batch sparse embeddings",
description="Generate embedding for a multiple query text",
)
async def create_sparse_embedding(
request: EmbedRequest,
manager: ModelManager = Depends(get_model_manager),
):
"""
Generate a single/batch sparse embedding.
The endpoint validates the request, checks that the requested
model is a sparse embedding model, and returns a
:class:`SparseEmbedResponse`.
Raises:
HTTPException: On validation or generation errors
"""
texts = [request.input] if isinstance(request.input, str) else request.input
if not texts or not isinstance(texts, list):
raise ValidationError("Input must be a non-empty list or string.")
try:
kwargs = extract_embedding_kwargs(request)
model = manager.get_model(request.model)
config = manager.model_configs.get(request.model)
_ensure_model_type(config, "sparse-embeddings", request.model)
start_time = time.time()
sparse_results = model.embed(input=texts, **kwargs)
processing_time = time.time() - start_time
sparse_embeddings = [
SparseEmbedding(
text=texts[idx],
indices=sparse_result["indices"],
values=sparse_result["values"],
)
for idx, sparse_result in enumerate(sparse_results)
]
response = SparseEmbedResponse(
embeddings=sparse_embeddings,
count=len(sparse_embeddings),
model=request.model,
)
logger.info(
f"Generated {len(texts)} embeddings "
f"in {processing_time:.3f}s ({len(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_sparse_embedding")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to create sparse embedding: {str(e)}",
)
|