Skip to main content

tiny-claude-recycler

Rotate a pool of Claude OAuth subscription tokens. Fall back to a regular Anthropic API key when they're all rate-limited. Zero runtime dependencies.

from claude_agent_sdk import query
from tcr import recycler, Secret

recycler.master_key  = Secret("sk-ant-api03-...")
recycler.oauth_keys  = [Secret("sk-ant-oat01-..."), Secret("sk-ant-oat01-...")]

@recycler.cycle(retries=3)
def ask(prompt):
    return query(prompt=prompt)   # SDK reads env on this call, after our swap

That's it. Use claude_agent_sdk (or anthropic) as normal.

What it does on every call

  1. Sets CLAUDE_CODE_OAUTH_TOKEN to the next pool key.
  2. Clears ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN — both outrank OAuth in Claude Code's auth precedence and would silently override our token.
  3. Runs your function.
  4. On exception → marks the key failed, advances the round-robin cursor, retries up to retries times.
  5. After retries failures → swaps to master (ANTHROPIC_API_KEY set, OAuth cleared) and runs once more.

State (failures, cursor, cooldowns) is preserved on the module-level singleton, so the next call resumes where the last one left off. With 9 keys and retries=3 you naturally burn through them in batches of 3.

API

@recycler.cycle(
    retries            = 3,           # OAuth attempts before master fallback
    fallback_to_master = True,        # False → re-raise the last OAuth error
    cooldown_seconds   = 60.0,        # failed keys are skipped for this long
    exceptions         = (Exception,) # which exceptions trigger cycling
)

Works on def and async def. Inspect / reset:

recycler.state_snapshot()  # {idx: {failures, last_error, cooldown_until, available, ...}}
recycler.reset_state()

Secret redacts its value in repr/str so tokens stay out of tracebacks and logs.

Production tips

Narrow the exception tuple. The default (Exception,) would burn keys on bugs. Use the curated helpers (lazy imports — only load if you call them):

from tcr import anthropic_exceptions, claude_agent_sdk_exceptions

@recycler.cycle(exceptions=anthropic_exceptions())   # 401/403/429/5xx/timeout/conn
def ask(prompt): ...

anthropic_exceptions() is verified against the SDK source: AuthenticationError, PermissionDeniedError, RateLimitError, OverloadedError, InternalServerError, ServiceUnavailableError, DeadlineExceededError, APIConnectionError, APITimeoutError.

Construct your Anthropic client inside the wrapped function (the import itself can be at module top — it's only the Anthropic() call that captures the env var). A long-lived client built before the decorator runs already pinned to whatever key was set at construction time and won't see swaps.

from anthropic import Anthropic            # import: anywhere is fine
from tcr import recycler, anthropic_exceptions

@recycler.cycle(retries=3, exceptions=anthropic_exceptions())
def ask(prompt):
    return Anthropic().messages.create(    # construction: must be inside
        model="claude-opus-4-7",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}],
    )

For claude_agent_sdk, this caveat doesn't apply — every query(...) call spawns a fresh subprocess that reads env at spawn time.

Known sharp edges (it's a little sketchy, by design)

  • Process-global env. Two decorated calls running concurrently across threads can race on CLAUDE_CODE_OAUTH_TOKEN. Either serialize Claude calls, or run one event loop / thread.
  • apiKeyHelper in ~/.claude/settings.json outranks OAuth and can't be cleared from env. If you use one, the recycler is a no-op for claude_agent_sdk.
  • Bedrock/Vertex/Foundry flags route requests away from Anthropic entirely. Don't set those if you want the recycler to do anything.
  • No proactive quota check. Anthropic doesn't expose subscription consumption via the API; this lib reacts to failures, it can't predict them.

Install

pip install -e ".[dev]"
pytest

Metadata

Release files for tiny-claude-recycler 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tiny-claude-recycler 0.1.0
File Size Uploaded Provenance Actions
tiny_claude_recycler-0.1.0.tar.gz 10.0 kB With provenance Details for tiny_claude_recycler-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tiny-claude-recycler 0.1.0
File Interpreter ABI Platform Actions
tiny_claude_recycler-0.1.0-py3-none-any.whl Python 3 none any Details for tiny_claude_recycler-0.1.0-py3-none-any.whl

Total release size: 18.6 kB

Release files / tiny_claude_recycler-0.1.0.tar.gz

Download URL tiny_claude_recycler-0.1.0.tar.gz
Size 10.0 kB
Tags Source
SHA-256 checksum
How to use checksums
33dfca32fc9d4939bf51f30b6291539cd292d3ba857471658dfd8847b0ed7973
BLAKE2b-256 checksum
How to use checksums
828b2587714991cd751a0f89960d73317c498d924190409a26b82d52eff5e363
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 14, 2026.

Transparency log

Release files / tiny_claude_recycler-0.1.0-py3-none-any.whl

Download URL tiny_claude_recycler-0.1.0-py3-none-any.whl
Size 8.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
55c1b3be2a39565ca317049983cc06e02aee1ef82eb7c01332b565cc12d8bbe3
BLAKE2b-256 checksum
How to use checksums
adec7a9ccd19c09263184afca740c3d89a2675223245f6d2223ce8167b570dc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 14, 2026.

Transparency log

Security for tiny-claude-recycler 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for tiny_claude_recycler-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 14, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page