"""Voyage AI Python SDK compatible /v1/embeddings facade. Voyage Client(base_url="https://host/v1", api_key="...").embed(...) works without a custom client. ColBERT's nested token vectors are an intentional 3-D extension; Voyage ordinarily returns one dense vector/input. """ import os import secrets from typing import Literal from fastapi import APIRouter, Depends, HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from pydantic import BaseModel, Field, field_validator from app.embedding import MODEL_ID as E5_ID, TooManyTokens from app.models import COLBERT_ID, QWEN_ID, ServiceBusy, ModelRegistry router = APIRouter() bearer = HTTPBearer(auto_error=False) ModelName = Literal[ "e5", "qwen", "colbert", "intfloat/multilingual-e5-small", "Qwen/Qwen3-Embedding-0.6B", "lightonai/mLateOn", ] class VoyageEmbedRequest(BaseModel): input: str | list[str] = Field( description="One text or a list of texts; max 1000 texts per request", examples=[["The first chunk", "The second chunk"]], ) model: ModelName = Field(examples=["qwen"]) input_type: Literal["query", "document"] | None = Field(default=None) truncation: bool = Field( default=True, description="SDK compatibility; E5 always truncates inputs over 512 tokens, " "including when this flag is false. Qwen/ColBERT remain strict.", ) output_dtype: Literal["float", "float32"] | None = None output_dimension: int | None = None encoding_format: Literal["base64", "float"] | None = None @field_validator("input") @classmethod def check_input(cls, value): texts = [value] if isinstance(value, str) else value if not texts or len(texts) > 1000: raise ValueError("Batch must contain between 1 and 1000 texts") if any(not isinstance(text, str) or not text.strip() for text in texts): raise ValueError("Each input must be a nonblank string") return value def authenticate(credentials: HTTPAuthorizationCredentials | None = Security(bearer)): expected = os.getenv("API_KEY") if ( not expected or credentials is None or not secrets.compare_digest(credentials.credentials, expected) ): raise HTTPException( status_code=401, detail="Invalid or missing API key", headers={"WWW-Authenticate": "Bearer"}, ) def resident_models(): # import here avoids app/router circular module initialization. from app.main import app registry = getattr(app.state, "registry", None) if registry is None: raise HTTPException(status_code=503, detail="Models are not ready") return registry @router.post("/v1/embeddings", dependencies=[Depends(authenticate)]) def embeddings(payload: VoyageEmbedRequest, registry: ModelRegistry = Depends(resident_models)): texts = [payload.input] if isinstance(payload.input, str) else payload.input model = payload.model canonical = { "e5": E5_ID, E5_ID: E5_ID, "qwen": QWEN_ID, QWEN_ID: QWEN_ID, "colbert": COLBERT_ID, COLBERT_ID: COLBERT_ID, }[model] engine = { E5_ID: registry.e5, QWEN_ID: registry.qwen, COLBERT_ID: registry.colbert, }[canonical] if engine is None: raise HTTPException(status_code=503, detail=f"Model {model} is not enabled") dimensions = engine.dimensions if payload.output_dimension is not None and payload.output_dimension != dimensions: raise HTTPException( status_code=422, detail=f"Model {canonical} only supports {dimensions} dimensions", ) # Voyage's None mode has no equivalent for asymmetric E5/Qwen/ColBERT. # Consistently treat it as 'document'. input_type remains recommended. kind = "query" if payload.input_type == "query" else "passage" try: results = registry.voyage_encode(texts, kind, canonical) except TooManyTokens as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc except ServiceBusy as exc: raise HTTPException( status_code=429, detail=str(exc), headers={"Retry-After": "2"} ) from exc except ValueError as exc: raise HTTPException(status_code=422, detail=str(exc)) from exc except Exception as exc: import logging logging.getLogger(__name__).exception("Voyage embedding failed") raise HTTPException(status_code=500, detail="Embedding failed") from exc return { "object": "list", "data": [ { "object": "embedding", "index": index, "embedding": ( result.token_embeddings if canonical == COLBERT_ID else result.embedding ), } for index, result in enumerate(results) ], "model": model, "usage": { "total_tokens": sum(item.tokens_count for item in results), }, }