Gemini Balance - Gemini API Proxy and Load Balancer

September 17, 2025 · View on GitHub

Read this document in Chinese

Gemini Balance - Gemini API Proxy and Load Balancer

snailyp%2Fgemini-balance | Trendshift

Python FastAPI Uvicorn Telegram Group

⚠️ Important: This project is licensed under the CC BY-NC 4.0 license. Any form of commercial resale service is prohibited. I have never sold this service on any platform. If you encounter someone selling this service, they are a reseller. Please do not be deceived.


📖 Project Introduction

Gemini Balance is an application built with Python FastAPI, designed to provide proxy and load balancing functions for the Google Gemini API. It allows you to manage multiple Gemini API Keys and implement key rotation, authentication, model filtering, and status monitoring through simple configuration. Additionally, the project integrates image generation and multiple image hosting upload functions, and supports proxying in the OpenAI API format.

📂 View Project Structure
app/
├── config/       # Configuration management
├── core/         # Core application logic (FastAPI instance creation, middleware, etc.)
├── database/     # Database models and connections
├── domain/       # Business domain objects
├── exception/    # Custom exceptions
├── handler/      # Request handlers
├── log/          # Logging configuration
├── main.py       # Application entry point
├── middleware/   # FastAPI middleware
├── router/       # API routes (Gemini, OpenAI, status page, etc.)
├── scheduler/    # Scheduled tasks (e.g., Key status check)
├── service/      # Business logic services (chat, Key management, statistics, etc.)
├── static/       # Static files (CSS, JS)
├── templates/    # HTML templates (e.g., Key status page)
└── utils/        # Utility functions

✨ Feature Highlights

  • Multi-Key Load Balancing: Supports configuring multiple Gemini API Keys (API_KEYS) for automatic sequential polling.
  • Visual Configuration: Configurations modified through the admin backend take effect immediately without restarting. Configuration Panel
  • Dual Protocol API Compatibility: Supports both Gemini and OpenAI CHAT API formats.
    • OpenAI Base URL: http://localhost:8000(/hf)/v1
    • Gemini Base URL: http://localhost:8000(/gemini)/v1beta
  • Image-Text Chat & Modification: Configure models with IMAGE_MODELS to support image-text chat and editing. Use the configured_model-image model name to invoke. Chat with Image Generation Modify Image
  • Web Search: Configure models with SEARCH_MODELS to support web search. Use the configured_model-search model name to invoke. Web Search
  • Key Status Monitoring: Provides a /keys_status page (authentication required) for real-time monitoring. Monitoring Panel
  • Detailed Logging: Provides detailed error logs for easy troubleshooting. Call Details Log List Log Details
  • Flexible Key Addition: Add keys in batches using the gemini_key regex, with automatic deduplication. Add Key
  • Failure Retry & Auto-Disable: Automatically retries failed API requests (MAX_RETRIES) and disables keys after excessive failures (MAX_FAILURES).
  • Comprehensive API Compatibility:
    • Embeddings API: Fully compatible with the OpenAI embeddings API format.
    • Image Generation API: Adapts the imagen-3.0-generate-002 model to the OpenAI image generation API format.
  • Automatic Model List Maintenance: Automatically fetches and syncs the latest model lists from Gemini and OpenAI.
  • Proxy Support: Supports HTTP/SOCKS5 proxies (PROXIES).
  • Docker Support: Provides Docker images for both AMD and ARM architectures.
    • Image Address: ghcr.io/snailyp/gemini-balance:latest

🚀 Quick Start

  1. Get docker-compose.yml: Download the docker-compose.yml file from the project repository.
  2. Prepare .env file: Copy .env.example to .env and configure it. Ensure DATABASE_TYPE is set to mysql and fill in the MYSQL_* details.
  3. Start Services: In the directory containing docker-compose.yml and .env, run:
    docker-compose up -d
    

Option 2: Docker Command

  1. Pull Image:
    docker pull ghcr.io/snailyp/gemini-balance:latest
    
  2. Prepare .env file: Copy .env.example to .env and configure it.
  3. Run Container:
    docker run -d -p 8000:8000 --name gemini-balance \
    -v ./data:/app/data \
    --env-file .env \
    ghcr.io/snailyp/gemini-balance:latest
    
    • -d: Detached mode.
    • -p 8000:8000: Map container port 8000 to host.
    • -v ./data:/app/data: Mount volume for persistent data.
    • --env-file .env: Load environment variables.

Option 3: Local Development

  1. Clone and Install:
    git clone https://github.com/snailyp/gemini-balance.git
    cd gemini-balance
    pip install -r requirements.txt
    
  2. Configure Environment: Copy .env.example to .env and configure it.
  3. Start Application:
    uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
    
    Access the application at http://localhost:8000.

⚙️ API Endpoints

Gemini API Format (/gemini/v1beta)

This endpoint is directly forwarded to official Gemini API format endpoint, without advanced features.

  • GET /models: List available Gemini models.
  • POST /models/{model_name}:generateContent: Generate content.
  • POST /models/{model_name}:streamGenerateContent: Stream content generation.

OpenAI API Format

Hugging Face (HF) Compatible

If you want to use advanced features, like fake streaming, please use this endpoint.

  • GET /hf/v1/models: List models.
  • POST /hf/v1/chat/completions: Chat completion.
  • POST /hf/v1/embeddings: Create text embeddings.
  • POST /hf/v1/images/generations: Generate images.

Standard OpenAI

This endpoint is directly forwarded to official OpenAI Compatible API format endpoint, without advanced features.

  • GET /openai/v1/models: List models.
  • POST /openai/v1/chat/completions: Chat completion (Recommended).
  • POST /openai/v1/embeddings: Create text embeddings.
  • POST /openai/v1/images/generations: Generate images.

📋 View Full Configuration List
Configuration ItemDescriptionDefault Value
Database
DATABASE_TYPEmysql or sqlitemysql
SQLITE_DATABASEPath for SQLite database filedefault_db
MYSQL_HOSTMySQL host addresslocalhost
MYSQL_SOCKETMySQL socket address/var/run/mysqld/mysqld.sock
MYSQL_PORTMySQL port3306
MYSQL_USERMySQL usernameyour_db_user
MYSQL_PASSWORDMySQL passwordyour_db_password
MYSQL_DATABASEMySQL database namedefaultdb
API
API_KEYSRequired, list of Gemini API keys[]
ALLOWED_TOKENSRequired, list of access tokens[]
AUTH_TOKENSuper admin token, defaults to the first of ALLOWED_TOKENSsk-123456
ADMIN_SESSION_EXPIREAdmin session expiration time in seconds (5 minutes to 24 hours)3600
TEST_MODELModel for testing key validitygemini-2.5-flash-lite
IMAGE_MODELSModels supporting image generation["gemini-2.0-flash-exp", "gemini-2.5-flash-image-preview"]
SEARCH_MODELSModels supporting web search["gemini-2.5-flash","gemini-2.5-pro"]
FILTERED_MODELSDisabled models[]
TOOLS_CODE_EXECUTION_ENABLEDEnable code execution toolfalse
SHOW_SEARCH_LINKDisplay search result links in responsetrue
SHOW_THINKING_PROCESSDisplay model's thinking processtrue
THINKING_MODELSModels supporting thinking process[]
THINKING_BUDGET_MAPBudget map for thinking function (model:budget){}
URL_NORMALIZATION_ENABLEDEnable smart URL routingfalse
URL_CONTEXT_ENABLEDEnable URL context understandingfalse
URL_CONTEXT_MODELSModels supporting URL context[]
BASE_URLGemini API base URLhttps://generativelanguage.googleapis.com/v1beta
MAX_FAILURESMax failures allowed per key3
MAX_RETRIESMax retries for failed API requests3
CHECK_INTERVAL_HOURSInterval (hours) to re-check disabled keys1
TIMEZONEApplication timezoneAsia/Shanghai
TIME_OUTRequest timeout (seconds)300
PROXIESList of proxy servers[]
Logging & Security
LOG_LEVELLog level: DEBUG, INFO, WARNING, ERRORINFO
ERROR_LOG_RECORD_REQUEST_BODYRecord request body in error logs (may contain sensitive information)false
AUTO_DELETE_ERROR_LOGS_ENABLEDAuto-delete error logstrue
AUTO_DELETE_ERROR_LOGS_DAYSError log retention period (days)7
AUTO_DELETE_REQUEST_LOGS_ENABLEDAuto-delete request logsfalse
AUTO_DELETE_REQUEST_LOGS_DAYSRequest log retention period (days)30
SAFETY_SETTINGSContent safety thresholds (JSON string)[{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"}, ...]
TTS
TTS_MODELTTS model namegemini-2.5-flash-preview-tts
TTS_VOICE_NAMETTS voice nameZephyr
TTS_SPEEDTTS speednormal
Image Generation
PAID_KEYPaid API Key for advanced featuresyour-paid-api-key
CREATE_IMAGE_MODELImage generation modelimagen-3.0-generate-002
UPLOAD_PROVIDERImage upload provider: smms, picgo, cloudflare_imgbed, aliyun_osssmms
OSS_ENDPOINTAliyun OSS public endpointoss-cn-shanghai.aliyuncs.com
OSS_ENDPOINT_INNERAliyun OSS internal endpoint (intra-VPC)oss-cn-shanghai-internal.aliyuncs.com
OSS_ACCESS_KEYAliyun AccessKey IDLTAI5txxxxxxxxxxxxxxxx
OSS_ACCESS_KEY_SECRETAliyun AccessKey SecretyXxxxxxxxxxxxxxxxxxxxxx
OSS_BUCKET_NAMEAliyun OSS bucket nameyour-bucket-name
OSS_REGIONAliyun OSS regioncn-shanghai
SMMS_SECRET_TOKENSM.MS API Tokenyour-smms-token
PICGO_API_KEYPicoGo API Keyyour-picogo-apikey
PICGO_API_URLPicoGo API Server URLhttps://www.picgo.net/api/1/upload
CLOUDFLARE_IMGBED_URLCloudFlare ImgBed upload URLhttps://xxxxxxx.pages.dev/upload
CLOUDFLARE_IMGBED_AUTH_CODECloudFlare ImgBed auth keyyour-cloudflare-imgber-auth-code
CLOUDFLARE_IMGBED_UPLOAD_FOLDERCloudFlare ImgBed upload folder""
Stream Optimizer
STREAM_OPTIMIZER_ENABLEDEnable stream output optimizationfalse
STREAM_MIN_DELAYMinimum stream output delay0.016
STREAM_MAX_DELAYMaximum stream output delay0.024
STREAM_SHORT_TEXT_THRESHOLDShort text threshold10
STREAM_LONG_TEXT_THRESHOLDLong text threshold50
STREAM_CHUNK_SIZEStream output chunk size5
Fake Stream
FAKE_STREAM_ENABLEDEnable fake streamingfalse
FAKE_STREAM_EMPTY_DATA_INTERVAL_SECONDSHeartbeat interval for fake streaming (seconds)5

🤝 Contributing

Pull Requests or Issues are welcome.

Contributors

⭐ Star History

Star History Chart

🎉 Special Thanks

🙏 Our Supporters

A special shout-out to DigitalOcean for providing the rock-solid and dependable cloud infrastructure that keeps this project humming!

DigitalOcean Logo

CDN acceleration and security protection for this project are sponsored by Tencent EdgeOne.

EdgeOne Logo

💖 Friendly Projects

🎁 Project Support

If you find this project helpful, consider supporting me via Afdian.

License

This project is licensed under the CC BY-NC 4.0 (Attribution-NonCommercial) license.