|
| 1 | +"""OpenRouter embedding support for repowise semantic search. |
| 2 | +
|
| 3 | +Uses the OpenAI-compatible endpoint at ``https://openrouter.ai/api/v1``. |
| 4 | +No additional pip install required — uses the ``openai`` package. |
| 5 | +
|
| 6 | +Default model: google/gemini-embedding-001 (768 dims) |
| 7 | +
|
| 8 | +Usage: |
| 9 | + from repowise.core.providers.embedding.openrouter import OpenRouterEmbedder |
| 10 | +
|
| 11 | + embedder = OpenRouterEmbedder(api_key="sk-or-...") |
| 12 | + vectors = await embedder.embed(["some text"]) |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import asyncio |
| 18 | +import math |
| 19 | +import os |
| 20 | + |
| 21 | + |
| 22 | +class OpenRouterEmbedder: |
| 23 | + """OpenRouter embedding adapter implementing the repowise Embedder protocol. |
| 24 | +
|
| 25 | + Args: |
| 26 | + api_key: OpenRouter API key. Falls back to OPENROUTER_API_KEY env var. |
| 27 | + model: Embedding model name. Default: "google/gemini-embedding-001". |
| 28 | + """ |
| 29 | + |
| 30 | + _DIMS: dict[str, int] = { |
| 31 | + "google/gemini-embedding-001": 768, |
| 32 | + "openai/text-embedding-3-small": 1536, |
| 33 | + "openai/text-embedding-3-large": 3072, |
| 34 | + } |
| 35 | + |
| 36 | + _DEFAULT_TIMEOUT: float = 10.0 |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + api_key: str | None = None, |
| 41 | + model: str = "google/gemini-embedding-001", |
| 42 | + timeout: float = _DEFAULT_TIMEOUT, |
| 43 | + ) -> None: |
| 44 | + self._api_key = api_key or os.environ.get("OPENROUTER_API_KEY") |
| 45 | + if not self._api_key: |
| 46 | + raise ValueError( |
| 47 | + "OpenRouter API key required. Pass api_key= or set OPENROUTER_API_KEY env var." |
| 48 | + ) |
| 49 | + if model not in self._DIMS: |
| 50 | + known = ", ".join(sorted(self._DIMS)) |
| 51 | + raise ValueError( |
| 52 | + f"Unknown embedding model {model!r}. Stored vectors would be mis-sized " |
| 53 | + f"against the model's real output, silently corrupting the vector store. " |
| 54 | + f"Add {model!r} to OpenRouterEmbedder._DIMS with its correct dimension count, " |
| 55 | + f"or pick a known model: {known}." |
| 56 | + ) |
| 57 | + self._model = model |
| 58 | + self._timeout = timeout |
| 59 | + self._client: object | None = None |
| 60 | + |
| 61 | + @property |
| 62 | + def dimensions(self) -> int: |
| 63 | + return self._DIMS[self._model] |
| 64 | + |
| 65 | + async def embed(self, texts: list[str]) -> list[list[float]]: |
| 66 | + """Embed a batch of texts using OpenRouter. |
| 67 | +
|
| 68 | + Runs the synchronous SDK call in a thread pool to avoid blocking the |
| 69 | + asyncio event loop. |
| 70 | + """ |
| 71 | + if not texts: |
| 72 | + return [] |
| 73 | + |
| 74 | + model = self._model |
| 75 | + timeout = self._timeout |
| 76 | + |
| 77 | + def _embed_sync() -> list[list[float]]: |
| 78 | + import openai |
| 79 | + |
| 80 | + if self._client is None: |
| 81 | + self._client = openai.OpenAI( |
| 82 | + api_key=self._api_key, |
| 83 | + base_url="https://openrouter.ai/api/v1", |
| 84 | + timeout=timeout, |
| 85 | + ) |
| 86 | + response = self._client.embeddings.create(model=model, input=texts) # type: ignore[union-attr] |
| 87 | + raw_vectors = [list(item.embedding) for item in response.data] |
| 88 | + return [_l2_normalize(v) for v in raw_vectors] |
| 89 | + |
| 90 | + return await asyncio.to_thread(_embed_sync) |
| 91 | + |
| 92 | + |
| 93 | +def _l2_normalize(vec: list[float]) -> list[float]: |
| 94 | + """L2-normalize a vector to unit length.""" |
| 95 | + norm = math.sqrt(sum(x * x for x in vec)) |
| 96 | + if norm == 0.0: |
| 97 | + norm = 1.0 |
| 98 | + return [x / norm for x in vec] |
0 commit comments