gemini-key-rotator
v1.0.0
Published
A Node.js utility for resilient interaction with the Google Gemini API. It handles automatic rotation across a pool of API keys to bypass rate limits (429) and quota exhaustion, and supports model fallback cascades (e.g., trying `gemini-2.5-flash` first,
Readme
Gemini Key Rotator
A Node.js utility for resilient interaction with the Google Gemini API. It handles automatic rotation across a pool of API keys to bypass rate limits (429) and quota exhaustion, and supports model fallback cascades (e.g., trying gemini-2.5-flash first, then falling back to gemini-2.0-flash-lite).
Installation
npm install gemini-key-rotatorUsage
const GeminiKeyRotator = require('gemini-key-rotator');
const fetch = require('node-fetch'); // Ensure node-fetch v2 is installed or use global fetch in Node 18+
// 1. Initialize with an array of Gemini API keys
const rotator = new GeminiKeyRotator([
'AIzaSyYourKey1...',
'AIzaSyYourKey2...',
'AIzaSyYourKey3...'
], {
minGapMs: 1500, // Minimum time between calls to avoid spamming
maxConsecutiveErrors: 3, // How many errors before a key is put on cooldown
models: ['gemini-2.5-flash', 'gemini-2.0-flash', 'gemini-2.0-flash-lite'] // Model fallback order
});
// 2. Prepare your Gemini API payload
const payload = {
contents: [{
parts: [{ text: "Explain quantum computing in simple terms." }]
}]
};
// 3. Execute the request
// The rotator will automatically handle key rotation and model fallback if it encounters 429s or errors
rotator.executeWithRetry(fetch, payload)
.then(response => console.log(response.candidates[0].content.parts[0].text))
.catch(error => console.error("All keys exhausted:", error));Features
- Multi-Key Pool: Distribute requests across multiple keys.
- Smart Cooldown: Temporarily skips keys that return consecutive errors (429/403/500).
- Model Fallback: If all keys hit rate limits on the primary model, it automatically cascades to the next model in your list.
- Pacing (Rate Limiting): Enforces a minimum gap between requests to smooth out API traffic.
Scripts Included
The repository also includes create_api_keys.js, a Playwright script to automate the extraction of Gemini API keys from Google AI Studio.
