Files
DeepTutor/deeptutor/services/keypool.py
Bingxi Zhao (Frank) bd80a4d28a release: v1.5.17
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.

Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).

Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).

Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.

Two defects found by the release gate and fixed here:

- Six partner routes — the four channel-onboarding endpoints and both
  WeChat QR endpoints — kept the _auth-only mount they had inherited
  from the blanket admin gate, so any signed-in account could start a
  QR login for someone else's partner and write a bot token into its
  channel config. All six now declare _MANAGEABLE, and a sweep test
  asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
  landed, but ten call sites pass it somewhere that takes one key; a
  list would have rendered into an Authorization header verbatim.
  keypool.primary_api_key reduces at each boundary.

Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
2026-08-25 02:24:35 +08:00

75 lines
3.1 KiB
Python

"""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
def primary_api_key(value: str | list[str] | None) -> str | None:
"""The one key to use where a pool cannot be rotated.
A configured credential became ``str | list[str]`` when key rotation
landed, but most consumers take a single key: an auth header, an SDK
client built once, a pipeline handed a credential. Passing the list
through would render as ``"['sk-a', 'sk-b']"`` in an ``Authorization``
header — a 401 whose cause is invisible. Reduce at the boundary instead,
and reduce in one place so every such boundary agrees which key is first.
"""
if isinstance(value, list):
return value[0] if value else None
return value or None
__all__ = ["KeyPool", "primary_api_key"]