How rhythamtech/keymesh works
Purpose and Public Surface
KeyMesh is a Python 3.12+ library that multiplexes AI-provider API credentials across concurrent workloads. It is provider-agnostic at its core; callers either manage key lifecycle directly or use OpenAI HTTP-client adapters. Public exports are centralized in keymesh/__init__.py; runnable usage appears in example.py and examples/openai_handler_example.py.
Dual Runtime Model
The package maintains parallel async and synchronous/thread-safe implementations rather than adapting one runtime to the other:
• Async orchestration: keymesh/pool/pool.py, keymesh/state/key_state.py, keymesh/storage/base.py
• Sync orchestration: keymesh/pool/sync_pool.py, keymesh/state/sync_key_state.py, keymesh/storage/sync_base.py
This is the primary boundary: async callers await pool/storage/state operations, while threaded callers use synchronous equivalents and locks.
Pool Orchestration
KeyPool and SyncKeyPool are the central lifecycle coordinators in keymesh/pool/pool.py and keymesh/pool/sync_pool.py. Their control flow is:
1. Acquire an eligible, non-cooled-down key through a scheduler.
2. Track active request state.
3. On successful completion, release the key and update latency/health metrics.
4. On rate limiting or failures, cool down or mark the key failed.
Pool exhaustion, cooldown eligibility, and lifecycle errors are surfaced through keymesh/exceptions.py.
Key State, Health, and Concurrency
Per-credential operational state is maintained by keymesh/state/key_state.py and keymesh/state/sync_key_state.py. State tracks active requests, cooldown timing, failure behavior, success/health signals, and latency statistics. Concurrency primitives are isolated in keymesh/concurrency/semaphores.py, enabling high-frequency acquisition without relying on mutable global client API keys.
Scheduling Layer
Schedulers are stateless selection policies behind the abstraction in keymesh/scheduler/base.py. Implementations choose among currently eligible key states:
• Rotation: keymesh/scheduler/round_robin.py
• Load-aware selection: keymesh/scheduler/least_busy.py
• Configured preference/capacity: keymesh/scheduler/weighted.py
The pool owns eligibility and lifecycle mutation; schedulers decide only which candidate to select.
Cooldown, Metrics, and Persistence
Rate-limit recovery is separated into keymesh/cooldown/manager.py, including cooldown duration handling such as Retry-After processing. Aggregate/per-pool observability lives in keymesh/metrics/pool_metrics.py, including EMA latency and success/failure health inputs. State persistence is abstracted through storage contracts and implementations:
• Async: keymesh/storage/base.py, keymesh/storage/memory.py, keymesh/storage/json_storage.py
• Sync: keymesh/storage/sync_base.py, keymesh/storage/sync_json.py
Memory storage is runtime-local; JSON storage provides local-file persistence. No database or remote control plane is represented.
HTTP Integration Boundary
keymesh/integrations/openai_handler.py provides httpx.Client and httpx.AsyncClient-based handlers for the OpenAI SDK (optional dependency). At the transport boundary, handlers acquire a key, inject it into the request Authorization header, time the request, then release, cool down on HTTP 429, or mark failures. This is the only provider-specific integration and avoids shared-client credential mutation while delegating actual API calls to OpenAI/httpx.
Main entry points: pool.py KeyPool · sync_pool.py SyncKeyPool · openai_handler.py OpenAI handlers · base.py Async storage contract
Components 18
Async runtime
- KeyPool · Acquires, releases, cools down, and fails credential state.
keymesh/pool/pool.py - KeyState · Tracks request activity, health, cooldown, and latency.
keymesh/state/key_state.py - Async storage contract
keymesh/storage/base.py - Memory storage
keymesh/storage/memory.py - JSON storage
keymesh/storage/json_storage.py
Sync runtime
- SyncKeyPool · Synchronous counterpart to the async pool.
keymesh/pool/sync_pool.py - SyncKeyState · Uses synchronous state and locking semantics.
keymesh/state/sync_key_state.py - Sync storage contract
keymesh/storage/sync_base.py - Sync JSON storage
keymesh/storage/sync_json.py
Shared policies
- Scheduler abstraction · Selects from candidates made eligible by pools.
keymesh/scheduler/base.py - Selection policies
keymesh/scheduler/round_robin.py - Cooldown manager · Handles cooldown durations and Retry-After values.
keymesh/cooldown/manager.py - Pool metrics · Aggregates EMA latency and success/failure signals.
keymesh/metrics/pool_metrics.py - Concurrency primitives · Supports high-frequency credential acquisition.
keymesh/concurrency/semaphores.py - Lifecycle exceptions · Reports exhaustion, eligibility, and lifecycle failures.
keymesh/exceptions.py
OpenAI integration
- OpenAI handlers · Injects credentials and reports HTTP outcomes to pools.
keymesh/integrations/openai_handler.py - OpenAI API · Actual requests are delegated through OpenAI/httpx.
Other components
- Public exports
keymesh/__init__.py
Connections 23
- Public exports → KeyPool: exports
- Public exports → SyncKeyPool: exports
- OpenAI handlers → KeyPool: acquire and report
- OpenAI handlers → SyncKeyPool: acquire and report
- OpenAI handlers → OpenAI API: sends requests
- KeyPool → KeyState: mutates lifecycle
- SyncKeyPool → SyncKeyState: mutates lifecycle
- KeyPool → Scheduler abstraction: selects eligible key
- SyncKeyPool → Scheduler abstraction: selects eligible key
- Selection policies → Scheduler abstraction: implements
- KeyPool → Cooldown manager: applies rate-limit recovery
- SyncKeyPool → Cooldown manager: applies rate-limit recovery
- KeyPool → Pool metrics: records outcomes
- SyncKeyPool → Pool metrics: records outcomes
- KeyPool → Concurrency primitives: coordinates acquisition
- SyncKeyPool → Concurrency primitives: coordinates acquisition
- KeyPool → Async storage contract: persists state
- Async storage contract → Memory storage: implemented by
- Async storage contract → JSON storage: implemented by
- SyncKeyPool → Sync storage contract: persists state
- Sync storage contract → Sync JSON storage: implemented by
- KeyPool → Lifecycle exceptions: raises
- SyncKeyPool → Lifecycle exceptions: raises