smoothapi-py 1.5.0__tar.gz → 1.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/.gitignore +2 -0
  2. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/PKG-INFO +45 -1
  3. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/README.md +44 -0
  4. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/pyproject.toml +1 -1
  5. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/smooth_api/__init__.py +189 -21
  6. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/smooth_api/config.py +93 -0
  7. smoothapi_py-1.6.0/smooth_api/key_pool.py +222 -0
  8. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/smooth_api/state.py +11 -0
  9. smoothapi_py-1.6.0/smooth_api/utils.py +50 -0
  10. smoothapi_py-1.6.0/tests/test_key_rotation.py +185 -0
  11. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_resilience.py +2 -2
  12. smoothapi_py-1.5.0/smooth_api/utils.py +0 -13
  13. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/CHANGELOG.md +0 -0
  14. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/LICENSE +0 -0
  15. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/smooth_api/dedup.py +0 -0
  16. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/conftest.py +0 -0
  17. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_backoff.py +0 -0
  18. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_concurrency.py +0 -0
  19. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_deduplication.py +0 -0
  20. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_deprecation.py +0 -0
  21. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_edge_cases.py +0 -0
  22. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_enhanced_circuit_breaker.py +0 -0
  23. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_exceptions.py +0 -0
  24. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_hooks.py +0 -0
  25. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_isolation.py +0 -0
  26. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_mock_response.py +0 -0
  27. {smoothapi_py-1.5.0 → smoothapi_py-1.6.0}/tests/test_timeout.py +0 -0
@@ -41,6 +41,8 @@ Thumbs.db
41
41
  *.swp
42
42
  *.swo
43
43
  .agent
44
+ *.sh
45
+ *.ps1
44
46
 
45
47
  # ─── Rust ──────────────────────────────────────────────────
46
48
  **/target/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: smoothapi-py
3
- Version: 1.5.0
3
+ Version: 1.6.0
4
4
  Summary: API protection library — exponential backoff and circuit breaker
5
5
  Project-URL: Homepage, https://smoothapi.org
6
6
  Project-URL: Issues, https://github.com/AryanSharma48/smoothAPI/issues
@@ -34,6 +34,7 @@ pip install smoothapi-py
34
34
  - **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
35
35
  - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on retryable codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
36
36
  - **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
37
+ - **Multi-Env API Key Pool & Failover:** Automatically discovers multiple keys from environment variables (by prefix or list), injects `Authorization: Bearer <key>`, and immediately switches keys on `429`/`402`/`403` with a 1-day default cooldown.
37
38
  - **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
38
39
  - **Request Timeouts:** Configurable timeouts to automatically abort requests that hang indefinitely (async only).
39
40
 
@@ -240,6 +241,49 @@ config = SmoothConfig(
240
241
  * **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
241
242
  * **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
242
243
 
244
+ ### Multi-Env API Key Pool & Automatic Failover
245
+
246
+ When calling rate-limited or quota-capped APIs (such as OpenAI, Anthropic, or Gemini), configure `api_keys` to automatically inject `Authorization: Bearer <key>` into `headers` and rotate to the next healthy key whenever a key hits `429` (Rate Limit), `402` (Quota Exceeded), or `403` (Forbidden/Key Limit).
247
+
248
+ **1. Auto-discover from `.env` by prefix (1-line decorator):**
249
+
250
+ ```python
251
+ import requests
252
+ from smooth_api import smooth_api
253
+
254
+ # Automatically loads OPENAI_KEY_1, OPENAI_KEY_2, ... in natural order
255
+ @smooth_api(api_keys="OPENAI_KEY_")
256
+ def ask_llm(prompt: str, headers: dict | None = None):
257
+ r = requests.post(
258
+ "https://api.openai.com/v1/chat/completions",
259
+ headers=headers,
260
+ json={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": prompt}]},
261
+ )
262
+ r.raise_for_status()
263
+ return r.json()
264
+ ```
265
+
266
+ **2. Explicit list or custom `ApiKeyConfig`:**
267
+
268
+ ```python
269
+ from smooth_api import smooth_api, SmoothConfig, ApiKeyConfig, get_active_api_key
270
+
271
+ config = SmoothConfig(
272
+ api_keys=ApiKeyConfig(
273
+ keys=["OPENAI_KEY_1", "OPENAI_KEY_2"], # Env var names or raw key strings
274
+ cooldown_ms=86_400_000, # Default: 1 day (24h), or Retry-After on 429
275
+ rotate_on_status=[429, 402, 403],
276
+ on_key_rotate=lambda ev: print(
277
+ f"Rotated {ev.from_label} -> {ev.to_label} (HTTP {ev.status}, cooldown {ev.cooldown_ms}ms)"
278
+ ),
279
+ )
280
+ )
281
+ ```
282
+
283
+ * **Automatic Header Injection**: If the decorated function accepts a `headers` argument (or `**kwargs`), `Authorization: Bearer <key>` is merged automatically. SDK wrappers that don't accept `headers` can call `get_active_api_key()` or `get_auth_headers()` inside the decorated function.
284
+ * **Zero-Wait Failover**: Switching to the next healthy key retries immediately without waiting for exponential backoff or tripping the circuit breaker.
285
+ * **1-Day Default Cooldown**: Exhausted keys are quarantined for `86,400,000 ms` (24 hours) by default—or the server's `Retry-After` duration on `429`—and automatically recover once the cooldown expires.
286
+
243
287
  ### Lifecycle Event Hooks
244
288
 
245
289
  SmoothAPI supports lifecycle event hooks to easily attach logging, metrics, alerting, or telemetry:
@@ -16,6 +16,7 @@ pip install smoothapi-py
16
16
  - **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
17
17
  - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on retryable codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
18
18
  - **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
19
+ - **Multi-Env API Key Pool & Failover:** Automatically discovers multiple keys from environment variables (by prefix or list), injects `Authorization: Bearer <key>`, and immediately switches keys on `429`/`402`/`403` with a 1-day default cooldown.
19
20
  - **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
20
21
  - **Request Timeouts:** Configurable timeouts to automatically abort requests that hang indefinitely (async only).
21
22
 
@@ -222,6 +223,49 @@ config = SmoothConfig(
222
223
  * **Settlement**: Once a call completes, the next call with the same key triggers a fresh execution.
223
224
  * **Sync Functions**: Deduplication only works with async-decorated functions. Sync functions are unaffected.
224
225
 
226
+ ### Multi-Env API Key Pool & Automatic Failover
227
+
228
+ When calling rate-limited or quota-capped APIs (such as OpenAI, Anthropic, or Gemini), configure `api_keys` to automatically inject `Authorization: Bearer <key>` into `headers` and rotate to the next healthy key whenever a key hits `429` (Rate Limit), `402` (Quota Exceeded), or `403` (Forbidden/Key Limit).
229
+
230
+ **1. Auto-discover from `.env` by prefix (1-line decorator):**
231
+
232
+ ```python
233
+ import requests
234
+ from smooth_api import smooth_api
235
+
236
+ # Automatically loads OPENAI_KEY_1, OPENAI_KEY_2, ... in natural order
237
+ @smooth_api(api_keys="OPENAI_KEY_")
238
+ def ask_llm(prompt: str, headers: dict | None = None):
239
+ r = requests.post(
240
+ "https://api.openai.com/v1/chat/completions",
241
+ headers=headers,
242
+ json={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": prompt}]},
243
+ )
244
+ r.raise_for_status()
245
+ return r.json()
246
+ ```
247
+
248
+ **2. Explicit list or custom `ApiKeyConfig`:**
249
+
250
+ ```python
251
+ from smooth_api import smooth_api, SmoothConfig, ApiKeyConfig, get_active_api_key
252
+
253
+ config = SmoothConfig(
254
+ api_keys=ApiKeyConfig(
255
+ keys=["OPENAI_KEY_1", "OPENAI_KEY_2"], # Env var names or raw key strings
256
+ cooldown_ms=86_400_000, # Default: 1 day (24h), or Retry-After on 429
257
+ rotate_on_status=[429, 402, 403],
258
+ on_key_rotate=lambda ev: print(
259
+ f"Rotated {ev.from_label} -> {ev.to_label} (HTTP {ev.status}, cooldown {ev.cooldown_ms}ms)"
260
+ ),
261
+ )
262
+ )
263
+ ```
264
+
265
+ * **Automatic Header Injection**: If the decorated function accepts a `headers` argument (or `**kwargs`), `Authorization: Bearer <key>` is merged automatically. SDK wrappers that don't accept `headers` can call `get_active_api_key()` or `get_auth_headers()` inside the decorated function.
266
+ * **Zero-Wait Failover**: Switching to the next healthy key retries immediately without waiting for exponential backoff or tripping the circuit breaker.
267
+ * **1-Day Default Cooldown**: Exhausted keys are quarantined for `86,400,000 ms` (24 hours) by default—or the server's `Retry-After` duration on `429`—and automatically recover once the cooldown expires.
268
+
225
269
  ### Lifecycle Event Hooks
226
270
 
227
271
  SmoothAPI supports lifecycle event hooks to easily attach logging, metrics, alerting, or telemetry:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smoothapi-py"
7
- version = "1.5.0"
7
+ version = "1.6.0"
8
8
  description = "API protection library — exponential backoff and circuit breaker"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -9,6 +9,7 @@ from typing import Any
9
9
  from urllib.parse import urlparse
10
10
 
11
11
  from .config import (
12
+ ApiKeyConfig,
12
13
  BackoffConfig,
13
14
  CircuitBreakerConfig,
14
15
  CircuitKeyFn,
@@ -16,12 +17,21 @@ from .config import (
16
17
  CircuitStateChangeEvent,
17
18
  DeduplicationConfig,
18
19
  FailureContext,
20
+ KeyRotationEvent,
19
21
  PartitionBy,
20
22
  RetryContext,
21
23
  SmoothConfig,
22
24
  SuccessContext,
23
25
  )
24
26
  from .dedup import RequestDeduplicator
27
+ from .key_pool import (
28
+ ApiKeyPool,
29
+ _active_api_key_var,
30
+ can_accept_headers_kwarg,
31
+ get_active_api_key,
32
+ get_auth_headers,
33
+ inject_bearer_kwargs,
34
+ )
25
35
  from .state import CircuitBreakerState
26
36
  from .utils import calculate_backoff, sleep_backoff
27
37
 
@@ -103,17 +113,21 @@ def _get_status_code(err: Exception) -> int | None:
103
113
  return None
104
114
 
105
115
 
116
+ def _get_retry_after_from_response(resp: Any) -> float | None:
117
+ if resp is not None and hasattr(resp, "headers") and resp.headers is not None:
118
+ retry_after = resp.headers.get("Retry-After")
119
+ if retry_after is not None:
120
+ trimmed = str(retry_after).strip()
121
+ if trimmed.isascii() and trimmed.isdigit():
122
+ delay = int(trimmed)
123
+ if delay >= 0:
124
+ return float(delay)
125
+ return None
126
+
127
+
106
128
  def _get_retry_after_delay(err: Exception) -> float | None:
107
129
  if hasattr(err, "response") and err.response is not None:
108
- if hasattr(err.response, "headers"):
109
- retry_after = err.response.headers.get("Retry-After")
110
- if retry_after is not None:
111
- try:
112
- delay = float(retry_after)
113
- if delay > 0:
114
- return delay
115
- except ValueError:
116
- pass
130
+ return _get_retry_after_from_response(err.response)
117
131
  return None
118
132
 
119
133
 
@@ -139,7 +153,17 @@ class MockResponse:
139
153
  pass
140
154
 
141
155
 
142
- def smooth_api(config: SmoothConfig):
156
+ def smooth_api(
157
+ config: SmoothConfig | None = None,
158
+ *,
159
+ api_keys: ApiKeyConfig | list[str] | str | None = None,
160
+ **config_kwargs: Any,
161
+ ):
162
+ if config is None:
163
+ config = SmoothConfig(api_keys=api_keys, **config_kwargs)
164
+ elif api_keys is not None and config.api_keys is None:
165
+ config.api_keys = SmoothConfig(api_keys=api_keys).api_keys
166
+
143
167
  def decorator(fn):
144
168
  # One breaker per decorated function, shared across all calls to fn.
145
169
  breaker = CircuitBreakerState(config.circuit_breaker, config.on_circuit_state_change)
@@ -153,6 +177,8 @@ def smooth_api(config: SmoothConfig):
153
177
  if config.deduplication is not None
154
178
  else None
155
179
  )
180
+ key_pool = ApiKeyPool(config.api_keys) if config.api_keys is not None else None
181
+ accepts_headers = can_accept_headers_kwarg(fn) if key_pool is not None else False
156
182
 
157
183
  if inspect.iscoroutinefunction(fn):
158
184
  @functools.wraps(fn)
@@ -182,18 +208,62 @@ def smooth_api(config: SmoothConfig):
182
208
  # or attach to an already-running Future.
183
209
  async def _execute():
184
210
  last_err: Exception | None = None
211
+ prev_delay: float | None = None
185
212
  attempt_count = 0
213
+ attempt = 0
214
+ key_rotations_used = 0
215
+ max_key_rotations = max(0, key_pool.size - 1) if key_pool is not None else 0
186
216
 
187
- for attempt in range(config.backoff.max_retries + 1):
217
+ while attempt <= config.backoff.max_retries:
188
218
  attempt_count = attempt + 1
219
+ active_key = key_pool.acquire_key() if key_pool is not None else None
220
+ call_kwargs = (
221
+ inject_bearer_kwargs(kwargs, active_key.value, accepts_headers)
222
+ if active_key is not None
223
+ else kwargs
224
+ )
225
+ token = (
226
+ _active_api_key_var.set(active_key.value)
227
+ if active_key is not None
228
+ else None
229
+ )
189
230
  try:
190
- if config.timeout_ms is not None:
191
- result = await asyncio.wait_for(fn(*args, **kwargs), timeout=config.timeout_ms / 1000.0)
192
- else:
193
- result = await fn(*args, **kwargs)
231
+ try:
232
+ if config.timeout_ms is not None:
233
+ result = await asyncio.wait_for(
234
+ fn(*args, **call_kwargs),
235
+ timeout=config.timeout_ms / 1000.0,
236
+ )
237
+ else:
238
+ result = await fn(*args, **call_kwargs)
239
+ finally:
240
+ if token is not None:
241
+ _active_api_key_var.reset(token)
194
242
 
195
243
  status = getattr(result, "status_code", None)
196
244
  res_url = url or _extract_url(args, kwargs, result)
245
+
246
+ if (
247
+ key_pool is not None
248
+ and active_key is not None
249
+ and key_pool.should_rotate_on_status(status)
250
+ ):
251
+ next_key, rot_event = key_pool.quarantine_and_rotate(
252
+ active_key.index,
253
+ int(status), # type: ignore[arg-type]
254
+ _get_retry_after_from_response(result),
255
+ res_url,
256
+ key,
257
+ )
258
+ if rot_event is not None:
259
+ if config.api_keys and config.api_keys.on_key_rotate:
260
+ _safe_invoke(config.api_keys.on_key_rotate, rot_event)
261
+ if config.on_key_rotate:
262
+ _safe_invoke(config.on_key_rotate, rot_event)
263
+ if next_key is not None and key_rotations_used < max_key_rotations:
264
+ key_rotations_used += 1
265
+ continue
266
+
197
267
  if status is not None and status >= 400:
198
268
  if config.on_failure:
199
269
  _safe_invoke(config.on_failure, FailureContext(
@@ -234,6 +304,28 @@ def smooth_api(config: SmoothConfig):
234
304
  except Exception as err:
235
305
  status = _get_status_code(err)
236
306
  err_url = url or _extract_url(args, kwargs, err)
307
+
308
+ if (
309
+ key_pool is not None
310
+ and active_key is not None
311
+ and key_pool.should_rotate_on_status(status)
312
+ ):
313
+ next_key, rot_event = key_pool.quarantine_and_rotate(
314
+ active_key.index,
315
+ int(status), # type: ignore[arg-type]
316
+ _get_retry_after_delay(err),
317
+ err_url,
318
+ key,
319
+ )
320
+ if rot_event is not None:
321
+ if config.api_keys and config.api_keys.on_key_rotate:
322
+ _safe_invoke(config.api_keys.on_key_rotate, rot_event)
323
+ if config.on_key_rotate:
324
+ _safe_invoke(config.on_key_rotate, rot_event)
325
+ if next_key is not None and key_rotations_used < max_key_rotations:
326
+ key_rotations_used += 1
327
+ continue
328
+
237
329
  # Non-retryable HTTP errors (e.g. 400, 401, 404) bubble up immediately.
238
330
  if status is not None and status not in config.retry_on:
239
331
  if config.fallback_on_non_retryable:
@@ -281,11 +373,12 @@ def smooth_api(config: SmoothConfig):
281
373
  breaker.record_failure(key)
282
374
  last_err = err
283
375
  if attempt < config.backoff.max_retries:
284
- delay = calculate_backoff(attempt, config.backoff)
376
+ delay = calculate_backoff(attempt, config.backoff, prev_delay)
285
377
  if status == 429:
286
378
  retry_after_delay = _get_retry_after_delay(err)
287
379
  if retry_after_delay is not None:
288
380
  delay = retry_after_delay
381
+ prev_delay = delay
289
382
  if config.on_retry:
290
383
  ctx = RetryContext(
291
384
  attempt=attempt + 1,
@@ -298,6 +391,7 @@ def smooth_api(config: SmoothConfig):
298
391
  )
299
392
  _safe_invoke(config.on_retry, ctx)
300
393
  await asyncio.sleep(delay)
394
+ attempt += 1
301
395
  continue
302
396
 
303
397
  # If retries are exhausted and it's an HTTP error, return the response instead of raising
@@ -314,6 +408,7 @@ def smooth_api(config: SmoothConfig):
314
408
  is_circuit_open=False,
315
409
  ))
316
410
  return err.response
411
+ attempt += 1
317
412
 
318
413
  if config.on_failure:
319
414
  _safe_invoke(config.on_failure, FailureContext(
@@ -335,6 +430,7 @@ def smooth_api(config: SmoothConfig):
335
430
  breaker.release_probe(key)
336
431
 
337
432
  wrapper.circuit_breaker = breaker
433
+ wrapper.key_pool = key_pool
338
434
  return wrapper
339
435
 
340
436
  else:
@@ -368,15 +464,57 @@ def smooth_api(config: SmoothConfig):
368
464
  raise RuntimeError(f'Circuit breaker is OPEN for: {key}')
369
465
 
370
466
  last_err: Exception | None = None
467
+ prev_delay: float | None = None
371
468
  attempt_count = 0
469
+ attempt = 0
470
+ key_rotations_used = 0
471
+ max_key_rotations = max(0, key_pool.size - 1) if key_pool is not None else 0
372
472
 
373
473
  try:
374
- for attempt in range(config.backoff.max_retries + 1):
474
+ while attempt <= config.backoff.max_retries:
375
475
  attempt_count = attempt + 1
476
+ active_key = key_pool.acquire_key() if key_pool is not None else None
477
+ call_kwargs = (
478
+ inject_bearer_kwargs(kwargs, active_key.value, accepts_headers)
479
+ if active_key is not None
480
+ else kwargs
481
+ )
482
+ token = (
483
+ _active_api_key_var.set(active_key.value)
484
+ if active_key is not None
485
+ else None
486
+ )
376
487
  try:
377
- result = fn(*args, **kwargs)
488
+ try:
489
+ result = fn(*args, **call_kwargs)
490
+ finally:
491
+ if token is not None:
492
+ _active_api_key_var.reset(token)
493
+
378
494
  status = getattr(result, "status_code", None)
379
495
  res_url = url or _extract_url(args, kwargs, result)
496
+
497
+ if (
498
+ key_pool is not None
499
+ and active_key is not None
500
+ and key_pool.should_rotate_on_status(status)
501
+ ):
502
+ next_key, rot_event = key_pool.quarantine_and_rotate(
503
+ active_key.index,
504
+ int(status), # type: ignore[arg-type]
505
+ _get_retry_after_from_response(result),
506
+ res_url,
507
+ key,
508
+ )
509
+ if rot_event is not None:
510
+ if config.api_keys and config.api_keys.on_key_rotate:
511
+ _safe_invoke(config.api_keys.on_key_rotate, rot_event)
512
+ if config.on_key_rotate:
513
+ _safe_invoke(config.on_key_rotate, rot_event)
514
+ if next_key is not None and key_rotations_used < max_key_rotations:
515
+ key_rotations_used += 1
516
+ continue
517
+
380
518
  if status is not None and status >= 400:
381
519
  if config.on_failure:
382
520
  _safe_invoke(config.on_failure, FailureContext(
@@ -405,6 +543,28 @@ def smooth_api(config: SmoothConfig):
405
543
  except Exception as err:
406
544
  status = _get_status_code(err)
407
545
  err_url = url or _extract_url(args, kwargs, err)
546
+
547
+ if (
548
+ key_pool is not None
549
+ and active_key is not None
550
+ and key_pool.should_rotate_on_status(status)
551
+ ):
552
+ next_key, rot_event = key_pool.quarantine_and_rotate(
553
+ active_key.index,
554
+ int(status), # type: ignore[arg-type]
555
+ _get_retry_after_delay(err),
556
+ err_url,
557
+ key,
558
+ )
559
+ if rot_event is not None:
560
+ if config.api_keys and config.api_keys.on_key_rotate:
561
+ _safe_invoke(config.api_keys.on_key_rotate, rot_event)
562
+ if config.on_key_rotate:
563
+ _safe_invoke(config.on_key_rotate, rot_event)
564
+ if next_key is not None and key_rotations_used < max_key_rotations:
565
+ key_rotations_used += 1
566
+ continue
567
+
408
568
  if status is not None and status not in config.retry_on:
409
569
  if config.fallback_on_non_retryable:
410
570
  import sys
@@ -451,11 +611,11 @@ def smooth_api(config: SmoothConfig):
451
611
  breaker.record_failure(key)
452
612
  last_err = err
453
613
  if attempt < config.backoff.max_retries:
454
- delay = calculate_backoff(attempt, config.backoff)
455
- if status == 429:
456
- retry_after_delay = _get_retry_after_delay(err)
614
+ delay = calculate_backoff(attempt, config.backoff, prev_delay)
615
+ retry_after_delay = _get_retry_after_delay(err) if status == 429 else None
457
616
  if status == 429 and retry_after_delay is not None:
458
617
  delay = retry_after_delay
618
+ prev_delay = delay
459
619
  if config.on_retry:
460
620
  ctx = RetryContext(
461
621
  attempt=attempt + 1,
@@ -468,6 +628,7 @@ def smooth_api(config: SmoothConfig):
468
628
  )
469
629
  _safe_invoke(config.on_retry, ctx)
470
630
  sleep_backoff(delay)
631
+ attempt += 1
471
632
  continue
472
633
 
473
634
  if status is not None and hasattr(err, 'response'):
@@ -483,6 +644,7 @@ def smooth_api(config: SmoothConfig):
483
644
  is_circuit_open=False,
484
645
  ))
485
646
  return err.response
647
+ attempt += 1
486
648
 
487
649
  if config.on_failure:
488
650
  _safe_invoke(config.on_failure, FailureContext(
@@ -499,6 +661,7 @@ def smooth_api(config: SmoothConfig):
499
661
  breaker.release_probe(key)
500
662
 
501
663
  wrapper.circuit_breaker = breaker
664
+ wrapper.key_pool = key_pool
502
665
  return wrapper
503
666
 
504
667
  return decorator
@@ -507,6 +670,11 @@ def smooth_api(config: SmoothConfig):
507
670
  __all__ = [
508
671
  'smooth_api',
509
672
  'SmoothConfig',
673
+ 'ApiKeyConfig',
674
+ 'ApiKeyPool',
675
+ 'KeyRotationEvent',
676
+ 'get_active_api_key',
677
+ 'get_auth_headers',
510
678
  'CircuitBreakerConfig',
511
679
  'BackoffConfig',
512
680
  'DeduplicationConfig',
@@ -50,11 +50,15 @@ class RetryContext:
50
50
  return self.delay_ms / 1000.0
51
51
 
52
52
 
53
+ JitterStrategy = Literal['none', 'full', 'equal', 'decorrelated']
54
+
55
+
53
56
  @dataclass
54
57
  class BackoffConfig:
55
58
  base_delay: float = 0.1 # seconds, doubles each attempt before jitter
56
59
  max_delay: float = 30.0 # ceiling on the pre-jitter exponential
57
60
  max_retries: int = 3
61
+ jitter: JitterStrategy = 'equal'
58
62
 
59
63
 
60
64
  @dataclass
@@ -158,6 +162,85 @@ class FailureContext:
158
162
  return self.is_circuit_open
159
163
 
160
164
 
165
+ @dataclass
166
+ class KeyRotationEvent:
167
+ from_index: int
168
+ from_label: str
169
+ to_index: int
170
+ to_label: str
171
+ status: int
172
+ cooldown_ms: int
173
+ url: str = ""
174
+ domain: str = ""
175
+
176
+ @property
177
+ def fromIndex(self) -> int:
178
+ return self.from_index
179
+
180
+ @property
181
+ def fromLabel(self) -> str:
182
+ return self.from_label
183
+
184
+ @property
185
+ def toIndex(self) -> int:
186
+ return self.to_index
187
+
188
+ @property
189
+ def toLabel(self) -> str:
190
+ return self.to_label
191
+
192
+ @property
193
+ def cooldownMs(self) -> int:
194
+ return self.cooldown_ms
195
+
196
+
197
+ ONE_DAY_MS = 24 * 60 * 60 * 1000 # 86_400_000 ms (1 day)
198
+
199
+
200
+ @dataclass
201
+ class ApiKeyConfig:
202
+ keys: list[str] = field(default_factory=list)
203
+ env_names: list[str] = field(default_factory=list)
204
+ env_prefix: Optional[str] = None
205
+ cooldown_ms: int = ONE_DAY_MS
206
+ rotate_on_status: list[int] = field(default_factory=lambda: [429, 402, 403])
207
+ env: Optional[dict[str, str]] = None
208
+ on_key_rotate: Optional[Callable[[KeyRotationEvent], Any]] = None
209
+
210
+ # CamelCase aliases for cross-language compatibility
211
+ envNames: Optional[list[str]] = None
212
+ envPrefix: Optional[str] = None
213
+ cooldownMs: Optional[int] = None
214
+ rotateOnStatus: Optional[list[int]] = None
215
+ onKeyRotate: Optional[Callable[[KeyRotationEvent], Any]] = None
216
+
217
+ def __post_init__(self):
218
+ if self.envNames is not None:
219
+ self.env_names = self.envNames
220
+ if self.envPrefix is not None:
221
+ self.env_prefix = self.envPrefix
222
+ if self.cooldownMs is not None:
223
+ self.cooldown_ms = self.cooldownMs
224
+ if self.rotateOnStatus is not None:
225
+ self.rotate_on_status = self.rotateOnStatus
226
+ if self.on_key_rotate is None and self.onKeyRotate is not None:
227
+ self.on_key_rotate = self.onKeyRotate
228
+
229
+
230
+ def normalize_api_key_config(
231
+ raw: ApiKeyConfig | list[str] | str | None,
232
+ ) -> Optional[ApiKeyConfig]:
233
+ if raw is None:
234
+ return None
235
+ if isinstance(raw, ApiKeyConfig):
236
+ return raw
237
+ if isinstance(raw, str):
238
+ return ApiKeyConfig(env_prefix=raw)
239
+ if isinstance(raw, (list, tuple)):
240
+ return ApiKeyConfig(keys=list(raw))
241
+ raise TypeError(f"Unsupported api_keys configuration type: {type(raw)!r}")
242
+
243
+
161
244
  @dataclass
162
245
  class SmoothConfig:
163
246
  backoff: BackoffConfig = field(default_factory=BackoffConfig)
@@ -172,21 +255,31 @@ class SmoothConfig:
172
255
  deduplication: Optional[DeduplicationConfig] = None
173
256
  # Maximum duration in milliseconds before a request attempt is aborted.
174
257
  timeout_ms: Optional[int] = None
258
+ # Multi-key / multi-environment API key pool with automatic failover on rate/quota limits.
259
+ api_keys: Optional[ApiKeyConfig | list[str] | str] = None
260
+ apiKeys: Optional[ApiKeyConfig | list[str] | str] = None
175
261
  # Lifecycle event hooks
176
262
  on_retry: Optional[Callable[[RetryContext], Any]] = None
177
263
  on_circuit_state_change: Optional[Callable[[CircuitStateChangeEvent], Any]] = None
264
+ on_key_rotate: Optional[Callable[[KeyRotationEvent], Any]] = None
178
265
  on_success: Optional[Callable[[SuccessContext], Any]] = None
179
266
  on_failure: Optional[Callable[[FailureContext], Any]] = None
180
267
  onRetry: Optional[Callable[[RetryContext], Any]] = None
181
268
  onCircuitStateChange: Optional[Callable[[CircuitStateChangeEvent], Any]] = None
269
+ onKeyRotate: Optional[Callable[[KeyRotationEvent], Any]] = None
182
270
  onSuccess: Optional[Callable[[SuccessContext], Any]] = None
183
271
  onFailure: Optional[Callable[[FailureContext], Any]] = None
184
272
 
185
273
  def __post_init__(self):
274
+ if self.api_keys is None and self.apiKeys is not None:
275
+ self.api_keys = self.apiKeys
276
+ self.api_keys = normalize_api_key_config(self.api_keys)
186
277
  if self.on_retry is None and self.onRetry is not None:
187
278
  self.on_retry = self.onRetry
188
279
  if self.on_circuit_state_change is None and self.onCircuitStateChange is not None:
189
280
  self.on_circuit_state_change = self.onCircuitStateChange
281
+ if self.on_key_rotate is None and self.onKeyRotate is not None:
282
+ self.on_key_rotate = self.onKeyRotate
190
283
  if self.on_success is None and self.onSuccess is not None:
191
284
  self.on_success = self.onSuccess
192
285
  if self.on_failure is None and self.onFailure is not None:
@@ -0,0 +1,222 @@
1
+ from __future__ import annotations
2
+
3
+ import contextvars
4
+ from dataclasses import dataclass
5
+ import inspect
6
+ import os
7
+ import re
8
+ import threading
9
+ import time
10
+ from typing import Any, Callable
11
+
12
+ from .config import ApiKeyConfig, KeyRotationEvent, ONE_DAY_MS, normalize_api_key_config
13
+
14
+ _active_api_key_var: contextvars.ContextVar[str | None] = contextvars.ContextVar(
15
+ "smooth_api_active_key", default=None
16
+ )
17
+
18
+
19
+ def get_active_api_key() -> str | None:
20
+ """Return the active API key for the current @smooth_api execution context."""
21
+ return _active_api_key_var.get()
22
+
23
+
24
+ def get_auth_headers(extra_headers: dict[str, str] | None = None) -> dict[str, str]:
25
+ """Return headers dict with 'Authorization: Bearer <active_key>' merged with extra_headers."""
26
+ headers = dict(extra_headers) if extra_headers else {}
27
+ key = _active_api_key_var.get()
28
+ if key:
29
+ headers["Authorization"] = f"Bearer {key}"
30
+ return headers
31
+
32
+
33
+ @dataclass
34
+ class ResolvedApiKey:
35
+ index: int
36
+ label: str
37
+ value: str
38
+ cooldown_until: float = 0.0 # epoch seconds
39
+
40
+
41
+ def _mask_key(raw: str, index: int) -> str:
42
+ trimmed = raw.strip()
43
+ if len(trimmed) <= 8:
44
+ return f"key#{index}"
45
+ return f"{trimmed[:4]}...{trimmed[-4:]}"
46
+
47
+
48
+ def _natural_sort_key(text: str) -> list[Any]:
49
+ return [int(tok) if tok.isdigit() else tok.lower() for tok in re.split(r"(\d+)", text)]
50
+
51
+
52
+ class ApiKeyPool:
53
+ def __init__(self, config: ApiKeyConfig | list[str] | str):
54
+ resolved_cfg = normalize_api_key_config(config)
55
+ assert resolved_cfg is not None
56
+ self._config = resolved_cfg
57
+ self._default_cooldown_s = (resolved_cfg.cooldown_ms or ONE_DAY_MS) / 1000.0
58
+ self._rotate_statuses = set(resolved_cfg.rotate_on_status or [429, 402, 403])
59
+ self._lock = threading.RLock()
60
+ self._current_index = 0
61
+ self._entries = self._resolve_keys(resolved_cfg)
62
+
63
+ if not self._entries:
64
+ raise ValueError(
65
+ "[smoothAPI] ApiKeyPool requires at least one valid API key from keys, env_names, or env_prefix."
66
+ )
67
+
68
+ def _resolve_keys(self, config: ApiKeyConfig) -> list[ResolvedApiKey]:
69
+ env_map = config.env if config.env is not None else os.environ
70
+ resolved: list[ResolvedApiKey] = []
71
+ seen_values: set[str] = set()
72
+
73
+ def add_entry(val: str | None, label: str | None = None) -> None:
74
+ if not val:
75
+ return
76
+ trimmed = val.strip()
77
+ if not trimmed or trimmed in seen_values:
78
+ return
79
+ seen_values.add(trimmed)
80
+ idx = len(resolved)
81
+ resolved.append(
82
+ ResolvedApiKey(
83
+ index=idx,
84
+ label=label if label is not None else _mask_key(trimmed, idx),
85
+ value=trimmed,
86
+ cooldown_until=0.0,
87
+ )
88
+ )
89
+
90
+ if config.keys:
91
+ for item in config.keys:
92
+ if not item:
93
+ continue
94
+ env_val = env_map.get(item)
95
+ if isinstance(env_val, str) and env_val.strip():
96
+ add_entry(env_val, label=item)
97
+ else:
98
+ add_entry(item)
99
+
100
+ if config.env_names:
101
+ for env_name in config.env_names:
102
+ if not env_name:
103
+ continue
104
+ add_entry(env_map.get(env_name), label=env_name)
105
+
106
+ if config.env_prefix:
107
+ prefix = config.env_prefix
108
+ matching_names = sorted(
109
+ (
110
+ k
111
+ for k, v in env_map.items()
112
+ if k.startswith(prefix) and isinstance(v, str) and v.strip()
113
+ ),
114
+ key=_natural_sort_key,
115
+ )
116
+ for env_name in matching_names:
117
+ add_entry(env_map.get(env_name), label=env_name)
118
+
119
+ return resolved
120
+
121
+ @property
122
+ def size(self) -> int:
123
+ return len(self._entries)
124
+
125
+ def should_rotate_on_status(self, status: int | None) -> bool:
126
+ return status is not None and status in self._rotate_statuses
127
+
128
+ def acquire_key(self, now: float | None = None) -> ResolvedApiKey | None:
129
+ now_s = time.time() if now is None else now
130
+ with self._lock:
131
+ total = len(self._entries)
132
+ for offset in range(total):
133
+ idx = (self._current_index + offset) % total
134
+ entry = self._entries[idx]
135
+ if entry.cooldown_until <= now_s:
136
+ self._current_index = idx
137
+ return entry
138
+ return None
139
+
140
+ def quarantine_and_rotate(
141
+ self,
142
+ failed_index: int,
143
+ status: int,
144
+ retry_after_seconds: float | None,
145
+ url: str,
146
+ domain: str,
147
+ now: float | None = None,
148
+ ) -> tuple[ResolvedApiKey | None, KeyRotationEvent | None]:
149
+ now_s = time.time() if now is None else now
150
+ with self._lock:
151
+ if failed_index < 0 or failed_index >= len(self._entries):
152
+ return self.acquire_key(now_s), None
153
+
154
+ failed_entry = self._entries[failed_index]
155
+ cooldown_s = self._default_cooldown_s
156
+ if status == 429 and retry_after_seconds is not None and retry_after_seconds > 0:
157
+ cooldown_s = float(retry_after_seconds)
158
+
159
+ failed_entry.cooldown_until = now_s + cooldown_s
160
+ cooldown_ms = int(round(cooldown_s * 1000.0))
161
+
162
+ total = len(self._entries)
163
+ for offset in range(1, total):
164
+ candidate_idx = (failed_index + offset) % total
165
+ candidate = self._entries[candidate_idx]
166
+ if candidate.cooldown_until <= now_s:
167
+ self._current_index = candidate_idx
168
+ event = KeyRotationEvent(
169
+ from_index=failed_entry.index,
170
+ from_label=failed_entry.label,
171
+ to_index=candidate.index,
172
+ to_label=candidate.label,
173
+ status=status,
174
+ cooldown_ms=cooldown_ms,
175
+ url=url,
176
+ domain=domain,
177
+ )
178
+ return candidate, event
179
+
180
+ return None, None
181
+
182
+ def get_stats(self, now: float | None = None) -> list[dict[str, Any]]:
183
+ now_s = time.time() if now is None else now
184
+ with self._lock:
185
+ return [
186
+ {
187
+ "index": entry.index,
188
+ "label": entry.label,
189
+ "is_available": entry.cooldown_until <= now_s,
190
+ "cooldown_remaining_ms": max(
191
+ 0, int(round((entry.cooldown_until - now_s) * 1000.0))
192
+ ),
193
+ "is_active": entry.index == self._current_index and entry.cooldown_until <= now_s,
194
+ }
195
+ for entry in self._entries
196
+ ]
197
+
198
+
199
+ def can_accept_headers_kwarg(fn: Callable[..., Any]) -> bool:
200
+ try:
201
+ sig = inspect.signature(fn)
202
+ for param in sig.parameters.values():
203
+ if param.name == "headers" or param.kind == inspect.Parameter.VAR_KEYWORD:
204
+ return True
205
+ return False
206
+ except (ValueError, TypeError):
207
+ return False
208
+
209
+
210
+ def inject_bearer_kwargs(
211
+ kwargs: dict[str, Any],
212
+ api_key: str,
213
+ accepts_headers: bool,
214
+ ) -> dict[str, Any]:
215
+ if "headers" in kwargs or accepts_headers:
216
+ new_kwargs = dict(kwargs)
217
+ existing = new_kwargs.get("headers")
218
+ headers_copy = dict(existing) if isinstance(existing, dict) else {}
219
+ headers_copy["Authorization"] = f"Bearer {api_key}"
220
+ new_kwargs["headers"] = headers_copy
221
+ return new_kwargs
222
+ return kwargs
@@ -216,6 +216,17 @@ class CircuitBreakerState:
216
216
  if event:
217
217
  self._notify_state_change(event)
218
218
 
219
+ def get_stored_state(self, domain: str) -> CircuitState:
220
+ with self._lock:
221
+ return self._get_or_create(domain).state
222
+
223
+ def get_state_at(self, domain: str, now_ms: float) -> CircuitState:
224
+ with self._lock:
225
+ entry = self._get_or_create(domain)
226
+ if entry.state == 'OPEN' and ((now_ms / 1000.0) - entry.last_failure_time) > self._config.cooldown_ms / 1000:
227
+ return 'HALF_OPEN'
228
+ return entry.state
229
+
219
230
  def get_state(self, domain: str) -> CircuitState:
220
231
  with self._lock:
221
232
  entry = self._get_or_create(domain)
@@ -0,0 +1,50 @@
1
+ import random
2
+ import time
3
+
4
+
5
+ def _compute_capped_delay(base_delay: float, max_delay: float, attempt: int) -> float:
6
+ if base_delay <= 0.0 or max_delay <= 0.0:
7
+ return 0.0
8
+ if base_delay >= max_delay:
9
+ return max_delay
10
+ remaining = max(0, int(attempt))
11
+ current = base_delay
12
+ while remaining > 0 and current < max_delay:
13
+ step = min(remaining, 52)
14
+ current *= 2.0 ** step
15
+ remaining -= step
16
+ return min(max_delay, current)
17
+
18
+
19
+ def calculate_backoff(
20
+ attempt: int,
21
+ config,
22
+ prev_delay: float | None = None,
23
+ random_factor: float | None = None,
24
+ ) -> float:
25
+ base_delay = max(0.0, float(config.base_delay))
26
+ max_delay = max(0.0, float(config.max_delay))
27
+ capped = _compute_capped_delay(base_delay, max_delay, attempt)
28
+ if capped == 0.0:
29
+ return 0.0
30
+
31
+ factor = (
32
+ max(0.0, min(1.0, float(random_factor)))
33
+ if random_factor is not None
34
+ else random.random()
35
+ )
36
+ strategy = getattr(config, "jitter", "equal") or "equal"
37
+ if strategy == "none":
38
+ return capped
39
+ if strategy == "full":
40
+ return capped * factor
41
+ if strategy == "decorrelated":
42
+ base = prev_delay if prev_delay is not None else base_delay
43
+ upper_bound = max(base_delay, base * 3.0)
44
+ return min(max_delay, base_delay + (upper_bound - base_delay) * factor)
45
+ half = capped / 2.0
46
+ return half + half * factor
47
+
48
+
49
+ def sleep_backoff(seconds: float) -> None:
50
+ time.sleep(seconds)
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import pytest
5
+ import requests
6
+
7
+ from smooth_api import (
8
+ ApiKeyConfig,
9
+ ApiKeyPool,
10
+ BackoffConfig,
11
+ KeyRotationEvent,
12
+ SmoothConfig,
13
+ get_active_api_key,
14
+ smooth_api,
15
+ )
16
+
17
+
18
+ def _make_http_error(status: int, retry_after: str | None = None) -> requests.HTTPError:
19
+ resp = requests.Response()
20
+ resp.status_code = status
21
+ if retry_after is not None:
22
+ resp.headers["Retry-After"] = retry_after
23
+ err = requests.HTTPError(f"HTTP {status}", response=resp)
24
+ return err
25
+
26
+
27
+ def test_key_pool_resolves_keys_env_names_and_natural_prefix():
28
+ mock_env = {
29
+ "LLM_KEY_10": "sk-prefix-10",
30
+ "LLM_KEY_2": "sk-prefix-2",
31
+ "LLM_KEY_1": "sk-prefix-1",
32
+ "EXPLICIT_ENV_KEY": "sk-explicit-env",
33
+ }
34
+
35
+ pool = ApiKeyPool(
36
+ ApiKeyConfig(
37
+ keys=["EXPLICIT_ENV_KEY", "sk-direct-literal-9999"],
38
+ env_prefix="LLM_KEY_",
39
+ env=mock_env,
40
+ )
41
+ )
42
+
43
+ assert pool.size == 5
44
+ stats = pool.get_stats()
45
+ assert [s["label"] for s in stats] == [
46
+ "EXPLICIT_ENV_KEY",
47
+ "sk-d...9999",
48
+ "LLM_KEY_1",
49
+ "LLM_KEY_2",
50
+ "LLM_KEY_10",
51
+ ]
52
+
53
+
54
+ def test_sync_decorator_injects_bearer_and_rotates_on_429():
55
+ auth_seen: list[str] = []
56
+ events: list[KeyRotationEvent] = []
57
+
58
+ cfg = SmoothConfig(
59
+ backoff=BackoffConfig(base_delay=0.005, max_delay=0.02, max_retries=1, jitter="none"),
60
+ api_keys=ApiKeyConfig(
61
+ keys=["OPENAI_KEY_1", "OPENAI_KEY_2"],
62
+ env={
63
+ "OPENAI_KEY_1": "sk-first-key",
64
+ "OPENAI_KEY_2": "sk-second-key",
65
+ },
66
+ on_key_rotate=lambda ev: events.append(ev),
67
+ ),
68
+ )
69
+
70
+ @smooth_api(cfg)
71
+ def call_llm(url: str, headers: dict[str, str] | None = None) -> dict[str, str]:
72
+ auth = (headers or {}).get("Authorization", "")
73
+ auth_seen.append(auth)
74
+ if auth == "Bearer sk-first-key":
75
+ raise _make_http_error(429, retry_after="12")
76
+ return {"ok": "true", "auth": auth}
77
+
78
+ res = call_llm("https://api.openai.com/v1/chat/completions")
79
+ assert res["ok"] == "true"
80
+ assert auth_seen == ["Bearer sk-first-key", "Bearer sk-second-key"]
81
+ assert len(events) == 1
82
+ assert events[0].from_label == "OPENAI_KEY_1"
83
+ assert events[0].to_label == "OPENAI_KEY_2"
84
+ assert events[0].status == 429
85
+ assert events[0].cooldown_ms == 12_000
86
+
87
+ # Subsequent call immediately uses OPENAI_KEY_2 while OPENAI_KEY_1 is quarantined
88
+ res2 = call_llm("https://api.openai.com/v1/chat/completions")
89
+ assert res2["auth"] == "Bearer sk-second-key"
90
+ assert len(auth_seen) == 3
91
+
92
+
93
+ def test_sync_rotation_on_402_403_and_cooldown_recovery():
94
+ auth_seen: list[str] = []
95
+ call_count = 0
96
+
97
+ cfg = SmoothConfig(
98
+ backoff=BackoffConfig(base_delay=0.005, max_delay=0.02, max_retries=1, jitter="none"),
99
+ api_keys=ApiKeyConfig(
100
+ env_prefix="ANTHROPIC_KEY_",
101
+ cooldown_ms=30,
102
+ env={
103
+ "ANTHROPIC_KEY_1": "sk-ant-1111",
104
+ "ANTHROPIC_KEY_2": "sk-ant-2222",
105
+ },
106
+ ),
107
+ )
108
+
109
+ @smooth_api(cfg)
110
+ def call_claude(url: str) -> str:
111
+ nonlocal call_count
112
+ call_count += 1
113
+ active = get_active_api_key()
114
+ auth_seen.append(f"Bearer {active}")
115
+ if call_count == 1:
116
+ raise _make_http_error(402)
117
+ if call_count == 3:
118
+ raise _make_http_error(403)
119
+ return "ok"
120
+
121
+ assert call_claude("https://api.anthropic.com/v1/messages") == "ok"
122
+ assert auth_seen == ["Bearer sk-ant-1111", "Bearer sk-ant-2222"]
123
+
124
+ time.sleep(0.045)
125
+
126
+ assert call_claude("https://api.anthropic.com/v1/messages") == "ok"
127
+ assert auth_seen == [
128
+ "Bearer sk-ant-1111",
129
+ "Bearer sk-ant-2222",
130
+ "Bearer sk-ant-2222",
131
+ "Bearer sk-ant-1111",
132
+ ]
133
+
134
+
135
+ @pytest.mark.asyncio
136
+ async def test_async_decorator_rotates_keys_on_429():
137
+ auth_seen: list[str] = []
138
+ events: list[KeyRotationEvent] = []
139
+
140
+ cfg = SmoothConfig(
141
+ backoff=BackoffConfig(base_delay=0.005, max_delay=0.02, max_retries=1, jitter="none"),
142
+ api_keys=ApiKeyConfig(
143
+ keys=["sk-async-key-1111", "sk-async-key-2222"],
144
+ cooldown_ms=5000,
145
+ ),
146
+ on_key_rotate=lambda ev: events.append(ev),
147
+ )
148
+
149
+ @smooth_api(cfg)
150
+ async def async_llm(url: str, headers: dict[str, str] | None = None) -> str:
151
+ auth = (headers or {}).get("Authorization", "")
152
+ auth_seen.append(auth)
153
+ if auth == "Bearer sk-async-key-1111":
154
+ raise _make_http_error(429)
155
+ return "success"
156
+
157
+ result = await async_llm("https://api.openai.com/v1/responses")
158
+ assert result == "success"
159
+ assert auth_seen == ["Bearer sk-async-key-1111", "Bearer sk-async-key-2222"]
160
+ assert len(events) == 1
161
+ assert events[0].from_index == 0
162
+ assert events[0].to_index == 1
163
+
164
+
165
+ def test_shorthand_decorator_and_one_day_default_cooldown(monkeypatch):
166
+ monkeypatch.setenv("QUICK_OPENAI_1", "sk-fast-1")
167
+ monkeypatch.setenv("QUICK_OPENAI_2", "sk-fast-2")
168
+ seen_auth: list[str] = []
169
+ events: list[KeyRotationEvent] = []
170
+
171
+ @smooth_api(api_keys="QUICK_OPENAI_", on_key_rotate=events.append)
172
+ def ask_llm(url: str, headers: dict[str, str] | None = None):
173
+ auth = (headers or {}).get("Authorization", "")
174
+ seen_auth.append(auth)
175
+ if auth == "Bearer sk-fast-1":
176
+ raise _make_http_error(429)
177
+ resp = requests.Response()
178
+ resp.status_code = 200
179
+ return resp
180
+
181
+ res = ask_llm("https://api.openai.com/v1/chat/completions")
182
+ assert res.status_code == 200
183
+ assert seen_auth == ["Bearer sk-fast-1", "Bearer sk-fast-2"]
184
+ assert len(events) == 1
185
+ assert events[0].cooldown_ms == 86_400_000
@@ -82,7 +82,7 @@ def test_retry_respects_retry_after_header_sync():
82
82
 
83
83
  class MockResponse:
84
84
  status_code = 429
85
- headers = {"Retry-After": "0.1"}
85
+ headers = {"Retry-After": "1"}
86
86
  reason = "Too Many Requests"
87
87
 
88
88
  class MockResponseSuccess:
@@ -124,7 +124,7 @@ async def test_retry_respects_retry_after_header_async():
124
124
 
125
125
  class MockResponse:
126
126
  status_code = 429
127
- headers = {"Retry-After": "0.1"}
127
+ headers = {"Retry-After": "1"}
128
128
  reason = "Too Many Requests"
129
129
 
130
130
  class MockResponseSuccess:
@@ -1,13 +0,0 @@
1
- import time
2
- import random
3
-
4
- def calculate_backoff(attempt: int, config) -> float:
5
- exponential = config.base_delay * (2 ** attempt)
6
- capped = min(config.max_delay, exponential)
7
- return random.uniform(0, capped)
8
-
9
-
10
- def sleep_backoff(seconds: float) -> None:
11
- time.sleep(seconds)
12
-
13
-
File without changes
File without changes