init
This commit is contained in:
1 parent
84ae2122b7
commit
3c4e8e6cee
54 files changed
+4329
No files matched your search
@@ -0,0 +1,55 @@
|
||||
"""OpenAI-совместимый провайдер эмбеддингов (httpx)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import structlog
|
||||
|
||||
from src.embeddings.base import EmbeddingAPIError, EmbeddingProvider
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
class OpenAIEmbeddingProvider(EmbeddingProvider):
|
||||
"""Провайдер эмбеддингов для OpenAI-совместимого API.
|
||||
|
||||
Args:
|
||||
api_url: Базовый URL API (например, ``https://api.openai.com/v1``).
|
||||
api_key: API-ключ для авторизации (Bearer token).
|
||||
model: Имя модели эмбеддингов.
|
||||
timeout: Таймаут HTTP-запроса в секундах.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
api_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
timeout: float = 30.0,
|
||||
) -> None:
|
||||
self._api_url = api_url.rstrip("/")
|
||||
self._api_key = api_key
|
||||
self._model = model
|
||||
self._client = httpx.AsyncClient(timeout=timeout)
|
||||
|
||||
async def embed(self, texts: list[str]) -> list[list[float]]:
|
||||
if not texts:
|
||||
return []
|
||||
|
||||
response = await self._client.post(
|
||||
f"{self._api_url}/embeddings",
|
||||
headers={"Authorization": f"Bearer {self._api_key}"},
|
||||
json={"model": self._model, "input": texts},
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise EmbeddingAPIError(response.status_code, response.text)
|
||||
|
||||
data = response.json()
|
||||
# Сортируем по index для гарантии порядка
|
||||
sorted_data = sorted(data["data"], key=lambda item: item["index"])
|
||||
return [item["embedding"] for item in sorted_data]
|
||||
|
||||
async def close(self) -> None:
|
||||
await self._client.aclose()
|
||||
logger.info("OpenAI embedding provider закрыт")
|
||||
Reference in new issue
Block a user