"""OpenAI 兼容的 embedding 适配器。 覆盖 OpenAI / Qwen / vLLM / Ollama / 以及任何实现了 /v1/embeddings 的服务。 """ from __future__ import annotations import httpx from ...contracts import Capabilities, HealthStatus, Modality from ..base import ProviderError from .base import EmbeddingProvider class OpenAICompatEmbedding(EmbeddingProvider): name = "openai_compat" def __init__( self, *, base_url: str, model: str, api_key: str | None = None, dim: int = 1024, timeout: float = 30.0, ) -> None: self.model = model self._dim = dim headers = {"Content-Type": "application/json"} if api_key: headers["Authorization"] = f"Bearer {api_key}" self._client = httpx.AsyncClient( base_url=base_url.rstrip("/"), timeout=httpx.Timeout(timeout, connect=10.0), headers=headers, ) @property def capabilities(self) -> Capabilities: return Capabilities(modality=Modality.VECTOR, extra={"dim": self._dim}) async def health(self) -> HealthStatus: try: r = await self._client.get("/models", timeout=5.0) return HealthStatus(ok=r.status_code < 500, detail=str(r.status_code)) except httpx.HTTPError as exc: return HealthStatus(ok=False, detail=f"{type(exc).__name__}: {exc}") async def embed(self, texts: list[str]) -> list[list[float]]: if not texts: return [] try: r = await self._client.post( "/embeddings", json={"model": self.model, "input": texts} ) except httpx.HTTPError as exc: raise ProviderError(f"embedding 请求失败: {exc}") from exc if r.status_code >= 400: raise ProviderError(f"embedding HTTP {r.status_code}: {r.text[:300]}") data = r.json().get("data", []) # 按 index 排序,防止服务端乱序 data = sorted(data, key=lambda d: d.get("index", 0)) vectors = [d["embedding"] for d in data] if len(vectors) != len(texts): raise ProviderError( f"embedding 数量不匹配: 请求 {len(texts)},返回 {len(vectors)}" ) return vectors async def aclose(self) -> None: await self._client.aclose()