Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(embedding): survive provider rate limits — key rotation, retry budget, global throttle (#962)

Wong1625cdd10580
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 8fc8910d4..5d8acddb0 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -241,12 +241,13 @@ class MinerUSettingsUpdate(BaseModel):
``api_token`` is tri-state: ``None`` keeps the stored token (the UI sends
None when the user didn't edit the secret field), ``""`` clears it, and a
- non-empty string replaces it. The GET payload never echoes the raw token.
+ non-empty string or string array replaces it. The GET payload never echoes
+ the raw token.
"""
mode: Literal["local", "cloud"] = "local"
api_base_url: str = "https://mineru.net"
- api_token: Optional[str] = None
+ api_token: Optional[str | list[str]] = None
local_cli_path: str = ""
model_download_source: Literal["huggingface", "modelscope"] = "huggingface"
model_download_endpoint: str = ""
@@ -938,7 +939,11 @@ async def update_mineru_settings(payload: MinerUSettingsUpdate):
# Tri-state token: None keeps the stored value, anything else replaces it.
token = current.get("api_token", "")
if payload.api_token is not None:
- token = payload.api_token.strip()
+ token = (
+ [value.strip() for value in payload.api_token if value.strip()]
+ if isinstance(payload.api_token, list)
+ else payload.api_token.strip()
+ )
service.save_mineru(
{
"mode": payload.mode,
@@ -1230,7 +1235,13 @@ async def test_mineru_connection(payload: MinerUSettingsUpdate):
service = get_runtime_settings_service()
stored = service.load_mineru(include_process_overrides=False)
- token = stored.get("api_token", "") if payload.api_token is None else payload.api_token.strip()
+ token = stored.get("api_token", "")
+ if payload.api_token is not None:
+ token = (
+ [value.strip() for value in payload.api_token if value.strip()]
+ if isinstance(payload.api_token, list)
+ else payload.api_token.strip()
+ )
config = MinerUConfig(
mode="cloud",
api_base_url=(payload.api_base_url or "").strip().rstrip("/") or "https://mineru.net",
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 2090aa5dd..537c5e426 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -11,7 +11,7 @@ import asyncio
from collections import OrderedDict
from collections.abc import Callable
import contextlib
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
import hashlib
import inspect
import json
@@ -23,6 +23,7 @@ import httpx
from openai import AsyncAzureOpenAI, AsyncOpenAI
from deeptutor.services.config import load_system_settings
+from deeptutor.services.keypool import KeyPool
from deeptutor.services.llm import get_token_limit_kwargs, supports_tools
from deeptutor.services.llm.openai_http_client import sanitize_invalid_ssl_env
from deeptutor.services.llm.reasoning_params import (
@@ -55,7 +56,7 @@ class LLMClientConfig:
binding: str
model: str | None
- api_key: str | None
+ api_key: str | list[str] | None
base_url: str | None
api_version: str | None = None
extra_headers: dict[str, str] | None = None
@@ -67,7 +68,8 @@ def _client_cache_key(
loop: asyncio.AbstractEventLoop,
disable_ssl_verify: bool,
) -> tuple[Any, ...]:
- secret = hashlib.sha256((config.api_key or "").encode("utf-8")).hexdigest()[:16]
+ serialized_key = json.dumps(config.api_key or "", ensure_ascii=False, separators=(",", ":"))
+ secret = hashlib.sha256(serialized_key.encode("utf-8")).hexdigest()[:16]
headers = json.dumps(config.extra_headers or {}, sort_keys=True, separators=(",", ":"))
return (
loop,
@@ -81,11 +83,27 @@ def _client_cache_key(
)
-def _build_openai_client(config: LLMClientConfig, *, disable_ssl_verify: bool) -> Any:
+def _build_openai_client(
+ config: LLMClientConfig,
+ *,
+ disable_ssl_verify: bool,
+ sdk_max_retries: int | None = None,
+) -> Any:
# A stale SSL_CERT_FILE (common with cloned conda envs) makes httpx's
# create_ssl_context raise FileNotFoundError mid-__init__, aborting client
# construction. Drop broken CA paths first so TLS uses its default CA config.
sanitize_invalid_ssl_env()
+ if isinstance(config.api_key, list):
+ keys = [str(key).strip() for key in config.api_key if str(key or "").strip()]
+ clients = {
+ key: _build_openai_client(
+ replace(config, api_key=key),
+ disable_ssl_verify=disable_ssl_verify,
+ sdk_max_retries=0,
+ )
+ for key in keys
+ }
+ return _KeyRotatingClient(KeyPool(keys), clients)
default_headers = config.extra_headers or None
spec = find_by_name(config.binding)
if spec:
@@ -97,21 +115,56 @@ def _build_openai_client(config: LLMClientConfig, *, disable_ssl_verify: bool) -
if disable_ssl_verify:
http_client = httpx.AsyncClient(verify=False) # nosec B501
if config.binding == "azure_openai" or (config.binding == "openai" and config.api_version):
+ retry_kwargs = {"max_retries": sdk_max_retries} if sdk_max_retries is not None else {}
return AsyncAzureOpenAI(
api_key=config.api_key or "sk-no-key-required",
azure_endpoint=config.base_url,
api_version=config.api_version,
http_client=http_client,
default_headers=default_headers,
+ **retry_kwargs,
)
+ retry_kwargs = {"max_retries": sdk_max_retries} if sdk_max_retries is not None else {}
return AsyncOpenAI(
api_key=config.api_key or "sk-no-key-required",
base_url=config.base_url or None,
http_client=http_client,
default_headers=default_headers,
+ **retry_kwargs,
)
+class _KeyRotatingCompletions:
+ def __init__(self, key_pool: KeyPool, clients: dict[str, Any]) -> None:
+ self._key_pool = key_pool
+ self._clients = clients
+
+ async def create(self, **kwargs: Any) -> Any:
+ for attempt in range(2):
+ api_key = self._key_pool.next()
+ try:
+ return await self._clients[api_key].chat.completions.create(**kwargs)
+ except Exception as exc:
+ status = getattr(exc, "status_code", None) or getattr(
+ getattr(exc, "response", None), "status_code", None
+ )
+ if status != 429:
+ raise
+ self._key_pool.mark_429(api_key)
+ if attempt:
+ raise
+ raise RuntimeError("LLM key rotation exhausted")
+
+
+class _KeyRotatingClient:
+ def __init__(self, key_pool: KeyPool, clients: dict[str, Any]) -> None:
+ self._clients = clients
+ self.chat = SimpleNamespace(completions=_KeyRotatingCompletions(key_pool, clients))
+
+ async def close(self) -> None:
+ await asyncio.gather(*(_close_client(client) for client in self._clients.values()))
+
+
async def _close_client(client: Any) -> None:
close = getattr(client, "aclose", None) or getattr(client, "close", None)
if not callable(close):
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index fc77064f1..2c42b2279 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -513,7 +513,7 @@ class NormalizedProviderConfig:
"""Normalized provider configuration input."""
name: str
- api_key: str = ""
+ api_key: str | list[str] = ""
api_base: str | None = None
api_version: str | None = None
extra_headers: dict[str, str] | None = None
@@ -528,7 +528,7 @@ class ResolvedLLMConfig:
provider_mode: str
binding_hint: str | None = None
binding: str = "openai"
- api_key: str = ""
+ api_key: str | list[str] = ""
base_url: str | None = None
effective_url: str | None = None
api_version: str | None = None
@@ -546,7 +546,7 @@ class ResolvedEmbeddingConfig:
provider_mode: str
binding_hint: str | None = None
binding: str = "openai"
- api_key: str = ""
+ api_key: str | list[str] = ""
base_url: str | None = None
effective_url: str | None = None
api_version: str | None = None
@@ -590,6 +590,18 @@ def _as_str(value: Any) -> str:
return str(value).strip() if value is not None else ""
+def _as_api_key(value: Any) -> str | list[str]:
+ if isinstance(value, list):
+ return [key for item in value if (key := _as_str(item))]
+ return _as_str(value)
+
+
+def _primary_api_key(value: str | list[str]) -> str:
+ return (
+ value[0] if isinstance(value, list) and value else value if isinstance(value, str) else ""
+ )
+
+
def _to_headers(value: Any) -> dict[str, str]:
if isinstance(value, dict):
return {str(k): str(v) for k, v in value.items() if str(k).strip() and v is not None}
@@ -657,7 +669,7 @@ def _collect_provider_pool(catalog: dict[str, Any]) -> dict[str, NormalizedProvi
continue
providers[name] = NormalizedProviderConfig(
name=name,
- api_key=_as_str(profile.get("api_key")),
+ api_key=_as_api_key(profile.get("api_key")),
api_base=_as_str(profile.get("base_url")) or None,
api_version=_as_str(profile.get("api_version")) or None,
extra_headers=_to_headers(profile.get("extra_headers")) or None,
@@ -669,14 +681,14 @@ def _choose_resolved_provider(
*,
hint: str | None,
model: str,
- api_key: str,
+ api_key: str | list[str],
api_base: str | None,
provider_pool: dict[str, NormalizedProviderConfig],
) -> ProviderSpec:
explicit_spec = find_by_name(hint) if hint else None
detected_gateway = find_gateway(
provider_name=None,
- api_key=api_key or None,
+ api_key=_primary_api_key(api_key) or None,
api_base=api_base or None,
)
# Keep backward compatibility: old `binding=openai` should not block
@@ -736,7 +748,7 @@ def resolve_llm_runtime_config(
binding_hint_raw = _as_str((profile or {}).get("binding"))
binding_hint = canonical_provider_name(binding_hint_raw)
- active_api_key = _as_str((profile or {}).get("api_key"))
+ active_api_key = _as_api_key((profile or {}).get("api_key"))
active_api_base = _as_str((profile or {}).get("base_url"))
active_api_version = _as_str((profile or {}).get("api_version"))
reasoning_effort = _as_str((model or {}).get("reasoning_effort")) or None
@@ -811,7 +823,7 @@ def _collect_embedding_provider_pool(
continue
providers[name] = NormalizedProviderConfig(
name=name,
- api_key=_as_str(profile.get("api_key")),
+ api_key=_as_api_key(profile.get("api_key")),
api_base=_as_str(profile.get("base_url")) or None,
api_version=_as_str(profile.get("api_version")) or None,
extra_headers=_to_headers(profile.get("extra_headers")) or None,
@@ -920,7 +932,7 @@ def resolve_embedding_runtime_config(
binding_hint_raw = _as_str((profile or {}).get("binding"))
binding_hint = _canonical_embedding_provider_name(binding_hint_raw)
- active_api_key = _as_str((profile or {}).get("api_key"))
+ active_api_key = _as_api_key((profile or {}).get("api_key"))
active_api_base = _as_str((profile or {}).get("base_url"))
active_api_version = _as_str((profile or {}).get("api_version"))
active_extra_headers = _to_headers((profile or {}).get("extra_headers"))
@@ -975,8 +987,10 @@ def resolve_embedding_runtime_config(
dimension=dimension,
send_dimensions=send_dimensions,
request_timeout=60,
- batch_size=10,
- batch_delay=0.0,
+ # Some providers (e.g. Volcengine Ark plan tier) enforce very low RPM limits;
+ # allow per-profile batch_size/batch_delay in the embedding profile, defaults unchanged
+ batch_size=_clamp_batch_size(profile),
+ batch_delay=_clamp_batch_delay(profile),
)
@@ -1365,3 +1379,17 @@ __all__ = [
"resolve_search_runtime_config",
"search_provider_state",
]
+
+
+def _clamp_batch_size(profile: dict | None) -> int:
+ try:
+ return max(1, int((profile or {}).get("batch_size", 10)))
+ except Exception:
+ return 10
+
+
+def _clamp_batch_delay(profile: dict | None) -> float:
+ try:
+ return max(0.0, float((profile or {}).get("batch_delay", 0.0)))
+ except Exception:
+ return 0.0
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index f11bf9dca..f6815c48a 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -360,6 +360,12 @@ def _string(value: Any) -> str:
return "" if value is None else str(value).strip()
+def _string_or_list(value: Any) -> str | list[str]:
+ if isinstance(value, list):
+ return [item for raw in value if (item := _string(raw))]
+ return _string(value)
+
+
class RuntimeSettingsService:
"""JSON-backed runtime settings rooted in data/user/settings.
@@ -930,7 +936,7 @@ class RuntimeSettingsService:
"mode": mode,
"api_base_url": _string(settings.get("api_base_url")).rstrip("/")
or "https://mineru.net",
- "api_token": _string(settings.get("api_token")),
+ "api_token": _string_or_list(settings.get("api_token")),
"local_cli_path": _string(settings.get("local_cli_path")),
"model_download_source": download_source,
"model_download_endpoint": _string(settings.get("model_download_endpoint")).rstrip("/"),
diff --git a/deeptutor/services/embedding/adapters/base.py b/deeptutor/services/embedding/adapters/base.py
index 7f49ea523..a5c94257c 100644
--- a/deeptutor/services/embedding/adapters/base.py
+++ b/deeptutor/services/embedding/adapters/base.py
@@ -10,6 +10,8 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
+from deeptutor.services.keypool import KeyPool
+
def looks_like_multimodal_embedding_model(model_name: Optional[str]) -> bool:
"""Best-effort guard for OpenAI-compatible multimodal embedding models."""
@@ -154,7 +156,11 @@ class BaseEmbeddingAdapter(ABC):
model family (default).
- request_timeout: Request timeout in seconds
"""
- self.api_key = config.get("api_key")
+ raw_api_key = config.get("api_key")
+ keys = raw_api_key if isinstance(raw_api_key, list) else [raw_api_key]
+ keys = [str(key).strip() for key in keys if str(key or "").strip()]
+ self._key_pool = KeyPool(keys) if keys else None
+ self.api_key = keys[0] if keys else ""
self.base_url = config.get("base_url")
self.api_version = config.get("api_version")
self.model = config.get("model")
diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.py
index b2ca06363..5f028876a 100644
--- a/deeptutor/services/embedding/adapters/openai_compatible.py
+++ b/deeptutor/services/embedding/adapters/openai_compatible.py
@@ -54,11 +54,17 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
def _auth_api_key(self) -> str:
"""Return a real API key, suppressing local-provider placeholder keys."""
- key = str(self.api_key or "").strip()
+ key = self._key_pool.next() if self._key_pool else str(self.api_key or "").strip()
if key == self.NO_KEY_SENTINEL:
return ""
return key
+ def _set_auth_header(self, headers: dict[str, str], api_key: str) -> None:
+ header = "api-key" if self.api_version else "Authorization"
+ headers.pop(header, None)
+ if api_key:
+ headers[header] = api_key if self.api_version else f"Bearer {api_key}"
+
@staticmethod
def _extract_embeddings_from_response(data: Any) -> list[list[float]]:
"""
@@ -166,11 +172,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
headers = {"Content-Type": "application/json"}
api_key = self._auth_api_key()
- if self.api_version:
- if api_key:
- headers["api-key"] = api_key
- elif api_key:
- headers["Authorization"] = f"Bearer {api_key}"
+ self._set_auth_header(headers, api_key)
headers.update({str(k): str(v) for k, v in self.extra_headers.items()})
# Multimodal: pass `contents` through as `input` only for model names
@@ -225,7 +227,11 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
pool=10.0,
)
last_exc: Exception | None = None
- for attempt in range(1 + self._MAX_RETRIES):
+ rate_limit_retries = 0
+ # 槽位必须 > 限流重试上限:429 的 continue 也消耗 attempt,若循环
+ # 先耗尽而 last_exc 仍为 None,会静默落到循环外的 data 引用上
+ # (UnboundLocalError)。多给 4 个槽位兜住 8 轮限流 + 网络重试。
+ for attempt in range(1 + max(self._MAX_RETRIES, 10)):
try:
async with httpx.AsyncClient(
timeout=timeout, verify=not disable_ssl_verify_enabled()
@@ -234,15 +240,34 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
# Handle rate limiting (429) with retry
if response.status_code == 429:
+ if self._key_pool:
+ self._key_pool.mark_429(api_key)
+ # 滑动窗口 429 是瞬态的:长跑(全库 reindex 数小时)里
+ # 单次 429 不该报废整跑。最多 8 轮,每轮等窗口滑过
+ # (Retry-After 优先,无头保守 60s)。月度额度耗尽的
+ # 429 会连挂 8 轮后仍然 raise,不会无限空转。
+ if rate_limit_retries < 8:
+ rate_limit_retries += 1
+ retry_after = float(response.headers.get("Retry-After", 0))
+ await asyncio.sleep(max(retry_after, 60))
+ try:
+ api_key = self._auth_api_key()
+ except RuntimeError:
+ # 池内 key 全在冷却(KeyPool 冷却 60s)。
+ # 等冷却期过后再取一次;仍取不到才认输。
+ await asyncio.sleep(65)
+ api_key = self._auth_api_key()
+ self._set_auth_header(headers, api_key)
+ continue
retry_after = float(response.headers.get("Retry-After", 0))
- wait = max(retry_after, self._RATE_LIMIT_BACKOFF * (2**attempt))
- logger.warning(
- f"Rate limited (429) on attempt {attempt + 1}/{1 + self._MAX_RETRIES}, "
- f"retrying in {wait:.1f}s..."
+ raise EmbeddingProviderError(
+ "Embedding provider remained rate limited after key rotation"
+ + (f" (Retry-After: {retry_after:g}s)" if retry_after else ""),
+ status=429,
+ model=model,
+ url=url,
+ provider="openai_compat",
)
- await asyncio.sleep(wait)
- last_exc = Exception("HTTP 429 Too Many Requests")
- continue
if response.status_code >= 400:
body_text = response.text
diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.py
index 1b331121b..836fc013d 100644
--- a/deeptutor/services/embedding/client.py
+++ b/deeptutor/services/embedding/client.py
@@ -37,6 +37,33 @@ def _resolve_adapter_class(binding: str) -> type[BaseEmbeddingAdapter]:
class EmbeddingClient:
"""Unified embedding client for RAG and retrieval services."""
+ # 全局发帖节流:KB reindex 时 LlamaIndex 用线程池并发调 embedding,
+ # 每个线程经 _run_in_new_loop 跑独立 event loop——asyncio.Lock 绑定
+ # 创建时的 loop,跨 loop 既不互斥还会挂死。必须用线程级锁。
+ _spacing_lock: Any = None
+ _last_request_monotonic: float = 0.0
+ _thread_guard: Any = None
+
+ @classmethod
+ def _global_spacing_lock(cls):
+ import threading
+
+ if cls._spacing_lock is None:
+ cls._thread_guard = threading.Lock()
+ with cls._thread_guard:
+ if cls._spacing_lock is None:
+ from threading import Lock as _TLock
+
+ cls._spacing_lock = _TLock()
+ return cls._spacing_lock
+
+ @staticmethod
+ def _hold_spacing_lock():
+ """Blocking acquire — cross-thread, loop-agnostic."""
+ lock = EmbeddingClient._global_spacing_lock()
+ lock.acquire()
+ return lock
+
def __init__(self, config: Optional[EmbeddingConfig] = None):
self.config = config or get_embedding_config()
self.logger = logging.getLogger(__name__)
@@ -111,7 +138,24 @@ class EmbeddingClient:
input_type=role,
)
try:
- response = await self.adapter.embed(request)
+ # 全局发帖节流:线程级锁串行化"等待间隔+发帖",跨线程/跨
+ # event loop 互斥(asyncio 锁在新 loop 模型下失效的教训)。
+ # asyncio.sleep 换成阻塞等待发帖侧可接受:DT 的 embedding
+ # 并发都在后台线程里,阻塞不伤 API 主线程。
+ import time as _time
+ from time import monotonic as _mono
+
+ _lock = EmbeddingClient._hold_spacing_lock()
+ try:
+ delay = self.config.batch_delay
+ if delay > 0:
+ elapsed = _mono() - EmbeddingClient._last_request_monotonic
+ if elapsed < delay:
+ _time.sleep(delay - elapsed)
+ EmbeddingClient._last_request_monotonic = _mono()
+ response = await self.adapter.embed(request)
+ finally:
+ _lock.release()
except Exception as exc:
# Capture batch context so the task log stream / KB diagnostics
# show actionable info instead of a bare exception string.
diff --git a/deeptutor/services/embedding/config.py b/deeptutor/services/embedding/config.py
index 02a04886e..696e2e828 100644
--- a/deeptutor/services/embedding/config.py
+++ b/deeptutor/services/embedding/config.py
@@ -12,7 +12,7 @@ class EmbeddingConfig:
"""Embedding runtime configuration."""
model: str
- api_key: str
+ api_key: str | list[str]
base_url: str | None = None
effective_url: str | None = None
binding: str = "openai"
diff --git a/deeptutor/services/keypool.py b/deeptutor/services/keypool.py
new file mode 100644
index 000000000..b043cbbd9
--- /dev/null
+++ b/deeptutor/services/keypool.py
@@ -0,0 +1,59 @@
+"""Thread-safe round-robin API key rotation with rate-limit cooldowns."""
+
+from __future__ import annotations
+
+from threading import Lock
+from time import monotonic
+
+
+class KeyPool:
+ """Rotate keys and cool a key after two HTTP 429 responses."""
+
+ def __init__(self, keys: list[str], cooldown_s: int = 60) -> None:
+ self._keys = [str(key).strip() for key in keys if str(key).strip()]
+ if not self._keys:
+ raise ValueError("KeyPool requires at least one non-empty key")
+ self._cooldown_s = max(0, cooldown_s)
+ self._next_index = 0
+ self._strikes = {key: 0 for key in self._keys}
+ self._cooldown_until = {key: 0.0 for key in self._keys}
+ self._lock = Lock()
+
+ def next(self) -> str:
+ """Return the next key, preferring one that is not cooling down.
+
+ When every key is cooling we still return the one that recovers
+ soonest instead of refusing to serve. The pool spreads load across
+ keys; it is not a circuit breaker. Raising here would convert a
+ retryable provider 429 into an unretryable application error for the
+ whole cooldown window — and for the common single-key setup that means
+ every LLM and embedding call failing for a full minute, which is
+ strictly worse than letting the provider's own 429 surface and be
+ retried. The caller (``_KeyRotatingCompletions.create``) already marks
+ the strike and re-raises the real 429 on its second attempt.
+ """
+ with self._lock:
+ now = monotonic()
+ for offset in range(len(self._keys)):
+ index = (self._next_index + offset) % len(self._keys)
+ key = self._keys[index]
+ if self._cooldown_until[key] > now:
+ continue
+ if self._cooldown_until[key]:
+ self._cooldown_until[key] = 0.0
+ self._strikes[key] = 0
+ self._next_index = (index + 1) % len(self._keys)
+ return key
+ return min(self._keys, key=lambda candidate: self._cooldown_until[candidate])
+
+ def mark_429(self, key: str) -> None:
+ """Record a rate limit; the second strike starts the cooldown."""
+ with self._lock:
+ if key not in self._strikes:
+ return
+ self._strikes[key] += 1
+ if self._strikes[key] >= 2:
+ self._cooldown_until[key] = monotonic() + self._cooldown_s
+
+
+__all__ = ["KeyPool"]
diff --git a/deeptutor/services/llm/client.py b/deeptutor/services/llm/client.py
index 6192a1d29..f3ec889d4 100644
--- a/deeptutor/services/llm/client.py
+++ b/deeptutor/services/llm/client.py
@@ -49,8 +49,8 @@ class LLMClient:
# Only set env vars for OpenAI-compatible bindings
if binding in ("openai", "azure_openai", "gemini"):
- if self.config.api_key:
- os.environ["OPENAI_API_KEY"] = self.config.api_key
+ if api_key := self.config.get_api_key():
+ os.environ["OPENAI_API_KEY"] = api_key
self.logger.debug("Set OPENAI_API_KEY env var")
if self.config.base_url:
diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py
index 2550cf436..97b5d1c7c 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -29,7 +29,7 @@ class LLMConfigUpdate(TypedDict, total=False):
"""Fields allowed when cloning an LLMConfig instance."""
model: str
- api_key: str
+ api_key: str | list[str]
base_url: str | None
effective_url: str | None
binding: str
@@ -59,9 +59,12 @@ def _is_openai_compatible_binding(binding: str | None) -> bool:
return spec.backend in {"openai_compat", "azure_openai"}
-def _set_openai_env_vars(api_key: str | None, base_url: str | None, *, source: str) -> None:
- if api_key:
- os.environ["OPENAI_API_KEY"] = api_key
+def _set_openai_env_vars(
+ api_key: str | list[str] | None, base_url: str | None, *, source: str
+) -> None:
+ primary_key = api_key[0] if isinstance(api_key, list) and api_key else api_key
+ if primary_key:
+ os.environ["OPENAI_API_KEY"] = primary_key
logger.debug("Set OPENAI_API_KEY env var (%s)", source)
if base_url:
@@ -97,7 +100,7 @@ class LLMConfig:
"""LLM configuration dataclass."""
model: str
- api_key: str
+ api_key: str | list[str]
base_url: str | None = None
effective_url: str | None = None
binding: str = "openai"
@@ -123,6 +126,8 @@ class LLMConfig:
def get_api_key(self) -> str:
"""Return the API key string for provider consumers."""
+ if isinstance(self.api_key, list):
+ return self.api_key[0] if self.api_key else ""
return self.api_key
diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.py
index adc5e65b6..757bc25d0 100644
--- a/deeptutor/services/llm/factory.py
+++ b/deeptutor/services/llm/factory.py
@@ -78,14 +78,14 @@ def _resolve_provider_spec(
*,
binding: str | None,
model: str,
- api_key: str,
+ api_key: str | list[str],
base_url: str | None,
fallback: str | None,
):
explicit = find_by_name(binding)
gateway = find_gateway(
provider_name=explicit.name if explicit else None,
- api_key=api_key or None,
+ api_key=(api_key[0] if isinstance(api_key, list) and api_key else api_key) or None,
api_base=base_url or None,
)
if explicit and gateway and explicit.name == "openai":
@@ -125,7 +125,7 @@ def _binding_matches_current(binding: str | None, current: LLMConfig) -> bool:
def _matching_current_config(
*,
model: str,
- api_key: str,
+ api_key: str | list[str],
base_url: str | None,
api_version: str | None,
binding: str | None,
@@ -153,7 +153,7 @@ def _matching_current_config(
def _resolve_call_config(
*,
model: str | None,
- api_key: str | None,
+ api_key: str | list[str] | None,
base_url: str | None,
api_version: str | None,
binding: str | None,
@@ -338,7 +338,7 @@ async def complete(
prompt: str,
system_prompt: str = "You are a helpful assistant.",
model: str | None = None,
- api_key: str | None = None,
+ api_key: str | list[str] | None = None,
base_url: str | None = None,
api_version: str | None = None,
binding: str | None = None,
@@ -408,7 +408,7 @@ async def stream(
prompt: str,
system_prompt: str = "You are a helpful assistant.",
model: str | None = None,
- api_key: str | None = None,
+ api_key: str | list[str] | None = None,
base_url: str | None = None,
api_version: str | None = None,
binding: str | None = None,
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index 87093ac46..d1bf6b623 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -18,6 +18,7 @@ import uuid
import json_repair
from openai import AsyncOpenAI
+from deeptutor.services.keypool import KeyPool
from deeptutor.services.llm.capabilities import disable_response_format_at_runtime
from deeptutor.services.llm.exceptions import LLMConfigError
from deeptutor.services.llm.openai_http_client import openai_client_kwargs
@@ -115,26 +116,32 @@ class OpenAICompatProvider(LLMProvider):
def __init__(
self,
- api_key: str | None = None,
+ api_key: str | list[str] | None = None,
api_base: str | None = None,
default_model: str = "gpt-4o",
extra_headers: dict[str, str] | None = None,
spec: Any = None,
provider_name: str | None = None,
):
- super().__init__(api_key, api_base)
+ keys = api_key if isinstance(api_key, list) else [api_key]
+ keys = [str(key).strip() for key in keys if str(key or "").strip()]
+ primary_key = keys[0] if keys else None
+ super().__init__(primary_key, api_base)
+ self._key_pool = KeyPool(keys) if keys else None
self.default_model = default_model
self.extra_headers = extra_headers or {}
self._spec = spec
self._provider_name = provider_name
- if api_key and spec and spec.env_key:
- self._setup_env(api_key, api_base)
+ if primary_key and spec and spec.env_key:
+ self._setup_env(primary_key, api_base)
effective_base = api_base or (spec.default_api_base if spec else None) or None
self._effective_base = effective_base
endpoint = (effective_base or "").rstrip("/")
- placeholder_key = api_key in {None, "", "no-key", "sk-no-key-required"}
+ # api_key may be a list (key pool); only the resolved primary key
+ # counts for the configured-key check.
+ placeholder_key = primary_key in {None, "", "no-key", "sk-no-key-required"}
if (
provider_name == "openai"
and (not endpoint or endpoint == "https://api.openai.com/v1")
@@ -151,7 +158,7 @@ class OpenAICompatProvider(LLMProvider):
default_headers.update(extra_headers)
self._client = AsyncOpenAI(
- api_key=api_key or "no-key",
+ api_key=primary_key or "no-key",
base_url=effective_base,
default_headers=default_headers,
max_retries=0,
@@ -160,6 +167,32 @@ class OpenAICompatProvider(LLMProvider):
self._responses_failures: dict[str, int] = {}
self._responses_tripped_at: dict[str, float] = {}
+ @staticmethod
+ def _status_code(exc: Exception) -> int | None:
+ return getattr(exc, "status_code", None) or getattr(
+ getattr(exc, "response", None), "status_code", None
+ )
+
+ async def _create_with_key_rotation(self, create, kwargs: dict[str, Any]) -> Any:
+ if not self._key_pool:
+ return await create(**kwargs)
+ api_key = self._key_pool.next()
+ for attempt in range(2):
+ request = dict(kwargs)
+ headers = dict(request.get("extra_headers") or {})
+ headers["Authorization"] = f"Bearer {api_key}"
+ request["extra_headers"] = headers
+ try:
+ return await create(**request)
+ except Exception as exc:
+ if self._status_code(exc) != 429:
+ raise
+ self._key_pool.mark_429(api_key)
+ if attempt:
+ raise
+ api_key = self._key_pool.next()
+ raise RuntimeError("LLM key rotation exhausted")
+
def _setup_env(self, api_key: str, api_base: str | None) -> None:
import os
@@ -691,7 +724,9 @@ class OpenAICompatProvider(LLMProvider):
tool_choice,
)
body.update(adapt_chat_kwargs_to_responses(extra_kwargs))
- result = parse_response_output(await self._client.responses.create(**body))
+ result = parse_response_output(
+ await self._create_with_key_rotation(self._client.responses.create, body)
+ )
self._record_responses_success(model, reasoning_effort)
return result
except Exception as responses_error:
@@ -712,7 +747,11 @@ class OpenAICompatProvider(LLMProvider):
)
request_kwargs.update({k: v for k, v in extra_kwargs.items() if v is not None})
try:
- return self._parse(await self._client.chat.completions.create(**request_kwargs))
+ return self._parse(
+ await self._create_with_key_rotation(
+ self._client.chat.completions.create, request_kwargs
+ )
+ )
except Exception as exc:
if request_kwargs.get(
"response_format"
@@ -721,7 +760,11 @@ class OpenAICompatProvider(LLMProvider):
disable_response_format_at_runtime(binding, request_kwargs.get("model"))
retry_kwargs = dict(request_kwargs)
retry_kwargs.pop("response_format", None)
- return self._parse(await self._client.chat.completions.create(**retry_kwargs))
+ return self._parse(
+ await self._create_with_key_rotation(
+ self._client.chat.completions.create, retry_kwargs
+ )
+ )
raise
except Exception as e:
if tools and self._is_tool_format_error(e):
@@ -775,7 +818,9 @@ class OpenAICompatProvider(LLMProvider):
)
body.update(adapt_chat_kwargs_to_responses(extra_kwargs))
body["stream"] = True
- stream = await self._client.responses.create(**body)
+ stream = await self._create_with_key_rotation(
+ self._client.responses.create, body
+ )
async def _timed_stream():
stream_iter = stream.__aiter__()
@@ -818,7 +863,9 @@ class OpenAICompatProvider(LLMProvider):
if self._spec is None or self._spec.supports_stream_options:
request_kwargs["stream_options"] = {"include_usage": True}
try:
- stream = await self._client.chat.completions.create(**request_kwargs)
+ stream = await self._create_with_key_rotation(
+ self._client.chat.completions.create, request_kwargs
+ )
except Exception as exc:
if request_kwargs.get(
"response_format"
@@ -827,7 +874,9 @@ class OpenAICompatProvider(LLMProvider):
disable_response_format_at_runtime(binding, request_kwargs.get("model"))
retry_kwargs = dict(request_kwargs)
retry_kwargs.pop("response_format", None)
- stream = await self._client.chat.completions.create(**retry_kwargs)
+ stream = await self._create_with_key_rotation(
+ self._client.chat.completions.create, retry_kwargs
+ )
else:
raise
diff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.py
index c0f4c0a15..bd13bd4e0 100644
--- a/deeptutor/services/llm/provider_factory.py
+++ b/deeptutor/services/llm/provider_factory.py
@@ -19,10 +19,11 @@ _provider_pool: "OrderedDict[tuple[Any, ...], LLMProvider]" = OrderedDict()
_provider_pool_lock = threading.RLock()
-def _secret_fingerprint(value: str | None) -> str:
+def _secret_fingerprint(value: str | list[str] | None) -> str:
if not value:
return ""
- return hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
+ serialized = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:16]
def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> tuple[Any, ...]:
@@ -45,6 +46,7 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> t
def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
"""Construct one provider, importing only the selected backend SDK."""
provider_name = llm_config.provider_name or llm_config.binding
+ primary_api_key = llm_config.get_api_key()
spec = find_by_name(provider_name)
backend = spec.backend if spec else "openai_compat"
@@ -73,7 +75,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider
provider = AzureOpenAIProvider(
- api_key=llm_config.api_key or "",
+ api_key=primary_api_key,
api_base=llm_config.effective_url or llm_config.base_url or "",
default_model=llm_config.model,
extra_headers=llm_config.extra_headers or None,
@@ -82,7 +84,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:
from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider
provider = AnthropicProvider(
- api_key=llm_config.api_key or None,
+ api_key=primary_api_key or None,
api_base=llm_config.effective_url or llm_config.base_url or None,
default_model=llm_config.model,
extra_headers=llm_config.extra_headers or None,
diff --git a/deeptutor/services/parsing/engines/mineru/cloud.py b/deeptutor/services/parsing/engines/mineru/cloud.py
index c90602ce7..f25593f3c 100644
--- a/deeptutor/services/parsing/engines/mineru/cloud.py
+++ b/deeptutor/services/parsing/engines/mineru/cloud.py
@@ -28,6 +28,8 @@ import zipfile
import httpx
+from deeptutor.services.keypool import KeyPool
+
from .config import MinerUConfig, MinerUError
logger = logging.getLogger(__name__)
@@ -65,7 +67,7 @@ def parse_cloud(
Raises :class:`MinerUError` on any misconfiguration, API error, timeout,
or extraction failure.
"""
- if not config.api_token:
+ if not config.api_keys:
raise MinerUError(
"MinerU cloud mode is selected but no API token is configured. "
"Add a token in Settings → MinerU, or switch to local mode."
@@ -75,10 +77,7 @@ def parse_cloud(
raise MinerUError(f"PDF file not found: {pdf_path}")
base_url = config.api_base_url.rstrip("/")
- headers = {
- "Authorization": f"Bearer {config.api_token}",
- "Accept": "application/json",
- }
+ key_pool = KeyPool(config.api_keys)
def report(message: str) -> None:
if on_progress is None:
@@ -88,9 +87,9 @@ def parse_cloud(
except Exception:
logger.debug("on_progress callback failed", exc_info=True)
- with httpx.Client(base_url=base_url, headers=headers) as client:
+ with httpx.Client(base_url=base_url, headers={"Accept": "application/json"}) as client:
report(f"MinerU cloud: requesting upload slot for {pdf_path.name}")
- batch_id, upload_url = _request_upload(client, pdf_path, config)
+ batch_id, upload_url = _request_upload(client, pdf_path, config, key_pool)
size_mb = pdf_path.stat().st_size / (1024 * 1024)
report(f"MinerU cloud: uploading {pdf_path.name} ({size_mb:.1f} MB)")
_upload_file(pdf_path, upload_url)
@@ -101,6 +100,7 @@ def parse_cloud(
poll_interval=poll_interval,
timeout=timeout,
on_progress=on_progress,
+ key_pool=key_pool,
)
report("MinerU cloud: downloading parsed result archive")
archive_bytes = _download(zip_url)
@@ -118,7 +118,9 @@ def parse_cloud(
# ---------------------------------------------------------------------------
-def _request_upload(client: httpx.Client, pdf_path: Path, config: MinerUConfig) -> tuple[str, str]:
+def _request_upload(
+ client: httpx.Client, pdf_path: Path, config: MinerUConfig, key_pool: KeyPool
+) -> tuple[str, str]:
"""POST file-urls/batch → ``(batch_id, signed_upload_url)``."""
file_entry: dict[str, object] = {"name": pdf_path.name, "is_ocr": config.is_ocr}
body: dict[str, object] = {
@@ -130,7 +132,7 @@ def _request_upload(client: httpx.Client, pdf_path: Path, config: MinerUConfig)
if config.api_language:
body["language"] = config.api_language
- payload = _post_json(client, "/api/v4/file-urls/batch", body)
+ payload = _post_json(client, "/api/v4/file-urls/batch", body, key_pool)
data = payload.get("data") or {}
batch_id = str(data.get("batch_id") or "").strip()
file_urls = data.get("file_urls") or []
@@ -159,6 +161,7 @@ def _poll_for_zip(
batch_id: str,
file_name: str,
*,
+ key_pool: KeyPool,
poll_interval: float,
timeout: float,
on_progress: Callable[[str], None] | None = None,
@@ -168,7 +171,7 @@ def _poll_for_zip(
last_state = ""
last_report = ""
while True:
- payload = _get_json(client, f"/api/v4/extract-results/batch/{batch_id}")
+ payload = _get_json(client, f"/api/v4/extract-results/batch/{batch_id}", key_pool)
results = (payload.get("data") or {}).get("extract_result") or []
entry = _match_entry(results, file_name)
if entry is not None:
@@ -208,13 +211,10 @@ def verify_credentials(config: MinerUConfig) -> None:
is never followed by an upload, so it simply expires) and validates the
business code. Raises :class:`MinerUError` with a user-facing message on
any failure."""
- if not config.api_token:
+ if not config.api_keys:
raise MinerUError("No API token configured.")
base_url = config.api_base_url.rstrip("/")
- headers = {
- "Authorization": f"Bearer {config.api_token}",
- "Accept": "application/json",
- }
+ key_pool = KeyPool(config.api_keys)
body: dict[str, object] = {
"files": [{"name": "connectivity-check.pdf", "is_ocr": False}],
"model_version": config.model_version,
@@ -223,8 +223,8 @@ def verify_credentials(config: MinerUConfig) -> None:
}
if config.api_language:
body["language"] = config.api_language
- with httpx.Client(base_url=base_url, headers=headers) as client:
- _post_json(client, "/api/v4/file-urls/batch", body)
+ with httpx.Client(base_url=base_url, headers={"Accept": "application/json"}) as client:
+ _post_json(client, "/api/v4/file-urls/batch", body, key_pool)
def _download(zip_url: str) -> bytes:
@@ -253,30 +253,42 @@ def _match_entry(results: list, file_name: str) -> dict | None:
return rows[0]
-def _post_json(client: httpx.Client, path: str, body: dict) -> dict:
- try:
- response = client.post(path, json=body, timeout=_SUBMIT_TIMEOUT_SECONDS)
- response.raise_for_status()
- payload = response.json()
- except httpx.HTTPStatusError as exc:
- raise MinerUError(_http_error_message(exc)) from exc
- except httpx.HTTPError as exc:
- raise MinerUError(f"MinerU API request failed: {exc}") from exc
- _check_code(payload)
- return payload
+def _request_json(
+ request: Callable[..., httpx.Response],
+ path: str,
+ key_pool: KeyPool,
+ **kwargs,
+) -> dict:
+ for attempt in range(2):
+ api_key = key_pool.next()
+ try:
+ response = request(
+ path,
+ timeout=_SUBMIT_TIMEOUT_SECONDS,
+ headers={"Authorization": f"Bearer {api_key}"},
+ **kwargs,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ except httpx.HTTPStatusError as exc:
+ if exc.response.status_code == 429:
+ key_pool.mark_429(api_key)
+ if attempt == 0:
+ continue
+ raise MinerUError(_http_error_message(exc)) from exc
+ except httpx.HTTPError as exc:
+ raise MinerUError(f"MinerU API request failed: {exc}") from exc
+ _check_code(payload)
+ return payload
+ raise MinerUError("MinerU API key rotation exhausted.")
-def _get_json(client: httpx.Client, path: str) -> dict:
- try:
- response = client.get(path, timeout=_SUBMIT_TIMEOUT_SECONDS)
- response.raise_for_status()
- payload = response.json()
- except httpx.HTTPStatusError as exc:
- raise MinerUError(_http_error_message(exc)) from exc
- except httpx.HTTPError as exc:
- raise MinerUError(f"MinerU API request failed: {exc}") from exc
- _check_code(payload)
- return payload
+def _post_json(client: httpx.Client, path: str, body: dict, key_pool: KeyPool) -> dict:
+ return _request_json(client.post, path, key_pool, json=body)
+
+
+def _get_json(client: httpx.Client, path: str, key_pool: KeyPool) -> dict:
+ return _request_json(client.get, path, key_pool)
def _check_code(payload: dict) -> None:
diff --git a/deeptutor/services/parsing/engines/mineru/config.py b/deeptutor/services/parsing/engines/mineru/config.py
index 16113601a..ac69a2ba3 100644
--- a/deeptutor/services/parsing/engines/mineru/config.py
+++ b/deeptutor/services/parsing/engines/mineru/config.py
@@ -37,7 +37,7 @@ class MinerUConfig:
mode: str = MINERU_MODE_LOCAL
api_base_url: str = "https://mineru.net"
- api_token: str = ""
+ api_token: str | list[str] = ""
# Explicit path to a local MinerU executable; "" = auto-detect from PATH.
local_cli_path: str = ""
# Local-mode model weight download source + optional custom address
@@ -69,6 +69,11 @@ class MinerUConfig:
auto-detect) so callers can drop the field from the request body."""
return None if self.language.lower() == "auto" else self.language
+ @property
+ def api_keys(self) -> list[str]:
+ values = self.api_token if isinstance(self.api_token, list) else [self.api_token]
+ return [key for value in values if (key := str(value).strip())]
+
def resolve_mineru_config() -> MinerUConfig:
"""Load the effective MinerU config from ``document_parsing.json`` (+ env overrides)."""
@@ -76,7 +81,11 @@ def resolve_mineru_config() -> MinerUConfig:
return MinerUConfig(
mode=str(settings.get("mode") or MINERU_MODE_LOCAL),
api_base_url=str(settings.get("api_base_url") or "https://mineru.net"),
- api_token=str(settings.get("api_token") or ""),
+ api_token=(
+ [str(value).strip() for value in settings.get("api_token", []) if str(value).strip()]
+ if isinstance(settings.get("api_token"), list)
+ else str(settings.get("api_token") or "").strip()
+ ),
local_cli_path=str(settings.get("local_cli_path") or ""),
model_download_source=str(settings.get("model_download_source") or "huggingface"),
model_download_endpoint=str(settings.get("model_download_endpoint") or ""),
diff --git a/deeptutor/services/parsing/engines/mineru/readiness.py b/deeptutor/services/parsing/engines/mineru/readiness.py
index e0abfc6b1..b08973cf9 100644
--- a/deeptutor/services/parsing/engines/mineru/readiness.py
+++ b/deeptutor/services/parsing/engines/mineru/readiness.py
@@ -53,7 +53,7 @@ def mineru_models_ready(_source: str = "huggingface") -> bool:
def mineru_readiness(config) -> ReadinessReport:
"""Whether a MinerU parse can run now under ``config``."""
if config.is_cloud:
- if not (config.api_token or "").strip():
+ if not config.api_keys:
return ReadinessReport(
ready=False,
reason="not_configured",
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index d81ed12b7..f9e317ad2 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -59,8 +59,9 @@ class _ImageSource:
class LlamaIndexDocumentLoader:
"""Convert source files into LlamaIndex ``Document`` / ``ImageNode`` objects."""
- def __init__(self, logger=None) -> None:
+ def __init__(self, logger=None, image_concurrency: int = 6) -> None:
self.logger = logger or logging.getLogger(__name__)
+ self.image_concurrency = max(1, int(image_concurrency))
async def load(
self,
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 55ca07bfa..ea935657e 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -380,6 +380,25 @@ async def test_mineru_settings_roundtrip_redacts_token(
assert service.load_mineru()["api_token"] == "secret-token"
+async def test_mineru_settings_accept_token_array(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})
+ monkeypatch.setattr(settings_router, "get_runtime_settings_service", lambda: service)
+
+ response = await settings_router.update_mineru_settings(
+ settings_router.MinerUSettingsUpdate(
+ mode="cloud",
+ api_token=[" token-a ", "token-b"],
+ )
+ )
+
+ assert response["api_token_set"] is True
+ assert "api_token" not in response["settings"]
+ assert service.load_mineru()["api_token"] == ["token-a", "token-b"]
+
+
@pytest.mark.asyncio
async def test_mineru_token_tristate_keep_then_clear(
monkeypatch: pytest.MonkeyPatch, tmp_path
diff --git a/tests/core/test_agentic_client_provider_kwargs.py b/tests/core/test_agentic_client_provider_kwargs.py
index 0c8f7913a..3cec7ebc1 100644
--- a/tests/core/test_agentic_client_provider_kwargs.py
+++ b/tests/core/test_agentic_client_provider_kwargs.py
@@ -151,6 +151,51 @@ def test_build_openai_client_routes_oauth_backend_through_adapter(monkeypatch) -
assert captured["default_model"] == "openai-codex/gpt-5.5"
+async def test_build_openai_client_rotates_api_keys_after_429(monkeypatch) -> None:
+ await agentic_client.close_agentic_client_pool()
+ seen_keys: list[str] = []
+
+ class RateLimitError(Exception):
+ status_code = 429
+
+ class FakeCompletions:
+ def __init__(self, api_key: str) -> None:
+ self.api_key = api_key
+
+ async def create(self, **_kwargs):
+ seen_keys.append(self.api_key)
+ if self.api_key == "key-a":
+ raise RateLimitError("rate limited")
+ return "ok"
+
+ class FakeClient:
+ def __init__(self, api_key: str, **_kwargs) -> None:
+ self.chat = type("Chat", (), {"completions": FakeCompletions(api_key)})()
+
+ async def close(self) -> None:
+ return None
+
+ monkeypatch.setattr(agentic_client, "AsyncOpenAI", FakeClient)
+ monkeypatch.setattr(
+ agentic_client, "load_system_settings", lambda: {"disable_ssl_verify": False}
+ )
+ client = build_openai_client(
+ LLMClientConfig(
+ binding="openai",
+ model="gpt-test",
+ api_key=["key-a", "key-b"],
+ base_url="https://example.test/v1",
+ )
+ )
+
+ result = await client.chat.completions.create(model="gpt-test", messages=[])
+
+ assert result == "ok"
+ assert seen_keys == ["key-a", "key-b"]
+ await agentic_client.close_agentic_client_pool()
+
+
def test_build_openai_client_routes_github_copilot_backend_through_adapter(monkeypatch) -> None:
captured = {}
diff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.py
index 46d4585d2..4cefb0afc 100644
--- a/tests/services/config/test_embedding_runtime.py
+++ b/tests/services/config/test_embedding_runtime.py
@@ -103,6 +103,29 @@ def test_embedding_orcarouter_binding_uses_default_endpoint() -> None:
assert resolved.dimension == 3072
+def test_embedding_runtime_preserves_api_key_array() -> None:
+ catalog = _build_catalog(
+ embedding_profile={
+ "id": "embedding-p",
+ "name": "Embedding pool",
+ "binding": "openai",
+ "base_url": "https://api.example.com/v1/embeddings",
+ "api_key": ["key-a", "key-b"],
+ "api_version": "",
+ "extra_headers": {},
+ "models": [
+ {
+ "id": "embedding-m",
+ "name": "m",
+ "model": "text-embedding-3-small",
+ "dimension": "1536",
+ }
+ ],
+ }
+ )
+ assert resolve_embedding_runtime_config(catalog=catalog).api_key == ["key-a", "key-b"]
+
+
def test_embedding_alias_canonicalization_google_to_gemini() -> None:
catalog = _build_catalog(
embedding_profile={
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index 4efc09253..c75aeb6ef 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -80,6 +80,23 @@ def test_llm_explicit_binding_and_headers() -> None:
assert resolved.extra_headers == {"APP-Code": "abc"}
+def test_llm_runtime_preserves_api_key_array() -> None:
+ catalog = _build_catalog(
+ llm_profile={
+ "id": "llm-p",
+ "name": "LLM pool",
+ "binding": "openai",
+ "base_url": "https://api.example.com/v1",
+ "api_key": ["key-a", "key-b"],
+ "api_version": "",
+ "extra_headers": {},
+ "models": [{"id": "llm-m", "name": "m", "model": "gpt-4o-mini"}],
+ }
+ )
+
+ assert resolve_llm_runtime_config(catalog=catalog).api_key == ["key-a", "key-b"]
+
+
def test_llm_api_key_prefix_gateway() -> None:
catalog = _build_catalog(
llm_profile={
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
index 04e2eb587..8b4fd6b2d 100644
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@ -275,6 +275,9 @@ def test_mineru_defaults_and_normalization(tmp_path: Path) -> None:
# Unknown mode falls back to local.
assert service.save_mineru({"mode": "weird"})["mode"] == "local"
+ pooled = service.save_mineru({"mode": "cloud", "api_token": [" tok-a ", "tok-b"]})
+ assert pooled["api_token"] == ["tok-a", "tok-b"]
+
# Model-download fields: source whitelisted, endpoint trimmed.
saved = service.save_mineru(
{
diff --git a/tests/services/embedding/test_send_dimensions.py b/tests/services/embedding/test_send_dimensions.py
index eebf4c9d0..741c90506 100644
--- a/tests/services/embedding/test_send_dimensions.py
+++ b/tests/services/embedding/test_send_dimensions.py
@@ -174,3 +174,48 @@ async def test_payload_auto_skips_dimensions_for_non_openai_models(
adapter = _make_adapter(model="text-embedding-v4", send_dimensions=None)
await adapter.embed(_request("text-embedding-v4"))
assert "dimensions" not in capturing_httpx.captured_payloads[-1]
+
+
+async def test_embedding_retries_429_once_with_next_api_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import asyncio
+
+ seen_auth: list[str] = []
+
+ class _RateLimitThenSuccess(httpx.AsyncBaseTransport):
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ seen_auth.append(request.headers.get("Authorization", ""))
+ if len(seen_auth) == 1:
+ return httpx.Response(429, request=request)
+ return httpx.Response(
+ 200,
+ request=request,
+ json={"data": [{"embedding": [0.1, 0.2]}], "usage": {}},
+ )
+
+ transport = _RateLimitThenSuccess()
+ real_client_init = httpx.AsyncClient.__init__
+
+ def _patched_init(self: httpx.AsyncClient, *args: Any, **kwargs: Any) -> None:
+ kwargs["transport"] = transport
+ real_client_init(self, *args, **kwargs)
+
+ async def _no_sleep(_delay: float) -> None:
+ return None
+
+ monkeypatch.setattr(httpx.AsyncClient, "__init__", _patched_init)
+ monkeypatch.setattr(asyncio, "sleep", _no_sleep)
+ adapter = OpenAICompatibleEmbeddingAdapter(
+ {
+ "api_key": ["key-a", "key-b"],
+ "base_url": "https://api.example.test/v1/embeddings",
+ "model": "text-embedding-3-small",
+ }
+ )
+
+ response = await adapter.embed(_request("text-embedding-3-small"))
+
+ assert response.embeddings == [[0.1, 0.2]]
+ assert seen_auth == ["Bearer key-a", "Bearer key-b"]
diff --git a/tests/services/llm/test_key_rotation.py b/tests/services/llm/test_key_rotation.py
new file mode 100644
index 000000000..9765b9e5d
--- /dev/null
+++ b/tests/services/llm/test_key_rotation.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+
+async def test_openai_compatible_llm_retries_429_with_next_api_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from deeptutor.services.llm.provider_core import openai_compat_provider as provider_module
+
+ seen_auth: list[str] = []
+
+ class _RateLimitError(Exception):
+ status_code = 429
+
+ class _Completions:
+ async def create(self, **kwargs: Any) -> Any:
+ seen_auth.append((kwargs.get("extra_headers") or {}).get("Authorization", ""))
+ if len(seen_auth) == 1:
+ raise _RateLimitError("429 rate limited")
+ return SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ message=SimpleNamespace(
+ content="ok",
+ tool_calls=[],
+ reasoning_content=None,
+ reasoning=None,
+ ),
+ finish_reason="stop",
+ )
+ ],
+ usage=None,
+ )
+
+ class _Client:
+ def __init__(self, **_kwargs: Any) -> None:
+ self.chat = SimpleNamespace(completions=_Completions())
+ self.responses = SimpleNamespace()
+
+ monkeypatch.setattr(provider_module, "AsyncOpenAI", _Client)
+ provider = provider_module.OpenAICompatProvider(
+ api_key=["key-a", "key-b"],
+ api_base="https://api.example.test/v1",
+ default_model="gpt-4o-mini",
+ )
+
+ response = await provider.chat([{"role": "user", "content": "hello"}])
+
+ assert response.content == "ok"
+ assert seen_auth == ["Bearer key-a", "Bearer key-b"]
diff --git a/tests/services/test_keypool.py b/tests/services/test_keypool.py
new file mode 100644
index 000000000..246423a62
--- /dev/null
+++ b/tests/services/test_keypool.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.services.keypool import KeyPool
+
+
+def test_keypool_rotates_in_round_robin_order() -> None:
+ pool = KeyPool(["key-a", "key-b", "key-c"])
+
+ assert [pool.next() for _ in range(5)] == [
+ "key-a",
+ "key-b",
+ "key-c",
+ "key-a",
+ "key-b",
+ ]
+
+
+def test_keypool_cools_key_after_two_429s_and_restores_it(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from deeptutor.services import keypool as keypool_module
+
+ now = {"value": 100.0}
+ monkeypatch.setattr(keypool_module, "monotonic", lambda: now["value"])
+ pool = KeyPool(["key-a", "key-b"], cooldown_s=60)
+
+ assert pool.next() == "key-a"
+ pool.mark_429("key-a")
+ pool.mark_429("key-a")
+ assert [pool.next(), pool.next()] == ["key-b", "key-b"]
+
+ now["value"] = 161.0
+ assert pool.next() == "key-a"
+
+
+def test_keypool_still_serves_a_single_cooling_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A single-key setup must never be refused service.
+
+ Cooling is only useful as a hint about which key to prefer. With one key
+ there is nothing to prefer, so refusing to hand it out would turn a
+ retryable provider 429 into a hard failure for every LLM and embedding
+ call until the cooldown expires.
+ """
+ from deeptutor.services import keypool as keypool_module
+
+ now = {"value": 10.0}
+ monkeypatch.setattr(keypool_module, "monotonic", lambda: now["value"])
+ pool = KeyPool(["only-key"], cooldown_s=5)
+
+ assert pool.next() == "only-key"
+ pool.mark_429("only-key")
+ assert pool.next() == "only-key"
+ pool.mark_429("only-key")
+ assert pool.next() == "only-key"
+
+ now["value"] = 16.0
+ assert pool.next() == "only-key"
+
+
+def test_keypool_prefers_the_soonest_recovering_key_when_all_are_cooling(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from deeptutor.services import keypool as keypool_module
+
+ now = {"value": 0.0}
+ monkeypatch.setattr(keypool_module, "monotonic", lambda: now["value"])
+ pool = KeyPool(["key-a", "key-b"], cooldown_s=60)
+
+ # key-a cools at t=0 (until 60), key-b at t=10 (until 70).
+ pool.mark_429("key-a")
+ pool.mark_429("key-a")
+ now["value"] = 10.0
+ pool.mark_429("key-b")
+ pool.mark_429("key-b")
+
+ now["value"] = 20.0
+ assert pool.next() == "key-a"
diff --git a/tests/tools/test_mineru.py b/tests/tools/test_mineru.py
index bf41017be..ae18ed177 100644
--- a/tests/tools/test_mineru.py
+++ b/tests/tools/test_mineru.py
@@ -47,6 +47,19 @@ def test_resolve_mineru_config_reads_settings(monkeypatch: pytest.MonkeyPatch) -
assert auto_cfg.api_language is None # "auto" → omit the language hint
+def test_resolve_mineru_config_preserves_token_array(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ mineru_config,
+ "load_mineru_settings",
+ lambda: {"mode": "cloud", "api_token": ["tok-a", "tok-b"]},
+ )
+
+ cfg = mineru_config.resolve_mineru_config()
+
+ assert cfg.api_token == ["tok-a", "tok-b"]
+ assert cfg.api_keys == ["tok-a", "tok-b"]
+
+
# ---------------------------------------------------------------------------
# Backend dispatch
# ---------------------------------------------------------------------------
@@ -335,10 +348,10 @@ def _install_fake_httpx(monkeypatch: pytest.MonkeyPatch, *, submit, poll, downlo
def __exit__(self, *a): # noqa: ANN002
return False
- def post(self, path, json=None, timeout=None): # noqa: A002, ANN001
+ def post(self, path, json=None, timeout=None, headers=None): # noqa: A002, ANN001
return submit(path, json)
- def get(self, path, timeout=None): # noqa: ANN001
+ def get(self, path, timeout=None, headers=None): # noqa: ANN001
return poll(path)
fake = SimpleNamespace(
@@ -385,6 +398,68 @@ def test_parse_cloud_happy_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)
assert (workdir / "images" / "fig.png").exists()
+def test_parse_cloud_retries_429_with_next_token(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from types import SimpleNamespace
+
+ pdf = tmp_path / "exam.pdf"
+ pdf.write_bytes(b"%PDF-1.4 test")
+ seen_auth: list[str] = []
+
+ class FakeClient:
+ def __init__(self, *_args, **_kwargs): # noqa: ANN002, ANN003
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args): # noqa: ANN002
+ return False
+
+ def post(self, _path, json=None, timeout=None, headers=None): # noqa: A002, ANN001
+ seen_auth.append((headers or {}).get("Authorization", ""))
+ if len(seen_auth) == 1:
+ return _Resp(status=429)
+ return _Resp({"code": 0, "data": {"batch_id": "B", "file_urls": ["https://up"]}})
+
+ def get(self, _path, timeout=None, headers=None): # noqa: ANN001
+ return _Resp(
+ {
+ "code": 0,
+ "data": {
+ "extract_result": [
+ {
+ "file_name": "exam.pdf",
+ "state": "done",
+ "full_zip_url": "https://zip",
+ }
+ ]
+ },
+ }
+ )
+
+ fake_httpx = SimpleNamespace(
+ Client=FakeClient,
+ put=lambda *_args, **_kwargs: _Resp(status=200),
+ get=lambda *_args, **_kwargs: _Resp(content=_zip_bytes(), status=200),
+ HTTPError=real_httpx.HTTPError,
+ HTTPStatusError=real_httpx.HTTPStatusError,
+ )
+ monkeypatch.setattr(mineru_cloud, "httpx", fake_httpx)
+
+ workdir = mineru_cloud.parse_cloud(
+ pdf,
+ tmp_path / "out",
+ MinerUConfig(mode="cloud", api_token=["tok-a", "tok-b"]),
+ poll_interval=0,
+ timeout=10,
+ )
+
+ assert (workdir / "full.md").exists()
+ assert seen_auth == ["Bearer tok-a", "Bearer tok-b"]
+
+
def test_parse_cloud_surfaces_api_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
pdf = tmp_path / "exam.pdf"
pdf.write_bytes(b"%PDF-1.4")