ETL: потоковое чтение S3, парсер content, чекпоинты, конкурентные эмбеддинги, CLI прогресса
This commit is contained in:
1 parent
e3f6084527
commit
c6b2f0a520
21 files changed
+1808
-65
No files matched your search
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import structlog
|
||||
|
||||
@@ -17,6 +19,8 @@ class OpenAIEmbeddingProvider(EmbeddingProvider):
|
||||
api_url: Базовый URL API (например, ``https://api.openai.com/v1``).
|
||||
api_key: API-ключ для авторизации (Bearer token).
|
||||
model: Имя модели эмбеддингов.
|
||||
batch_size: Максимум текстов в одном HTTP-запросе.
|
||||
concurrency: Сколько запросов выполнять параллельно.
|
||||
timeout: Таймаут HTTP-запроса в секундах.
|
||||
"""
|
||||
|
||||
@@ -25,22 +29,44 @@ class OpenAIEmbeddingProvider(EmbeddingProvider):
|
||||
api_url: str,
|
||||
api_key: str,
|
||||
model: str,
|
||||
batch_size: int = 100,
|
||||
concurrency: int = 1,
|
||||
timeout: float = 30.0,
|
||||
) -> None:
|
||||
if batch_size <= 0:
|
||||
raise ValueError("batch_size должен быть положительным")
|
||||
if concurrency <= 0:
|
||||
raise ValueError("concurrency должен быть положительным")
|
||||
|
||||
self._api_url = api_url.rstrip("/")
|
||||
self._api_key = api_key
|
||||
self._model = model
|
||||
self._batch_size = batch_size
|
||||
self._concurrency = concurrency
|
||||
self._semaphore = asyncio.Semaphore(concurrency)
|
||||
self._client = httpx.AsyncClient(timeout=timeout)
|
||||
|
||||
async def embed(self, texts: list[str]) -> list[list[float]]:
|
||||
"""Векторизует тексты, деля их на батчи и выполняя до N запросов параллельно."""
|
||||
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},
|
||||
)
|
||||
batches = [
|
||||
texts[i : i + self._batch_size]
|
||||
for i in range(0, len(texts), self._batch_size)
|
||||
]
|
||||
results = await asyncio.gather(*(self._embed_batch(batch) for batch in batches))
|
||||
# Сохраняем исходный порядок текстов
|
||||
return [vector for batch in results for vector in batch]
|
||||
|
||||
async def _embed_batch(self, texts: list[str]) -> list[list[float]]:
|
||||
"""Один HTTP-запрос к embedding API (с ограничением конкурентности)."""
|
||||
async with self._semaphore:
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user