Commit ·
cb01b8b
1
Parent(s): db708af
hf test
Browse filesFiles changed (8)
- .env.example+13-7
- LICENSE+1-1
- README.md+142-188
- requirements.txt+2-2
- run.py+4-1
- src/auth.py+17-12
- src/config.py+1-1
- src/main.py+6
1231235645689789101112131415# Gemini Proxy Configuration# Set your Google Cloud Project ID here to skip automatic detectionGEMINI_PROJECT_ID=# Required: Authentication password for API accessGEMINI_AUTH_PASSWORD=123456
# Optional: Set a custom port (default is 8888)GEMINI_PORT=8888# Option 1: Credentials as JSON string (highest priority - overrides file-based credentials)# GEMINI_CREDENTIALS={"client_id":"your-client-id","client_secret":"your-client-secret","token":"your-access-token","refresh_token":"your-refresh-token","scopes":["https://www.googleapis.com/auth/cloud-platform"],"token_uri":"https://oauth2.googleapis.com/token"}
# Authentication password for the proxy (default is 123456)GEMINI_AUTH_PASSWORD=123456# Option 2: Path to credentials file (only used if GEMINI_CREDENTIALS is not set)GOOGLE_APPLICATION_CREDENTIALS=oauth_creds.json
# Optional: Google Cloud Project ID (if not in credentials)# GOOGLE_CLOUD_PROJECT=your-project-id
# Server configuration (optional)# HOST=0.0.0.0# PORT=8888 # Default compatibility port (use 7860 for Hugging Face)1233456MIT License
Copyright (c) 2025 gzzhongqiCopyright (c) 2024 Gemini CLI to API Proxy
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to deal123456789101112131415161718191234567891011121314151617181920212223242526272829303132333435363738394041424344454647482122232425495027515253542955565758596031323334353637383961626341424344646546474849505166675354555668697071725873746075626364656667687677787980818283848586878889909192937194957374759677787980818283848586878889909798999293949596979899100101100101102103103104104105106106107108109110111112113108109110111112113114115116117118119120121115116123124125126127128117118130119132133120121135136137138122123124125126127141142143144145128129130131132133134135136148149150151152153137138139140156141142158159160161162163164143144145166146147148149150168169170151152153154155156157158159172173160161162163164165175176166167168179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213169170215171172173174175176217218219220177178222179180224225226227181182229183# Gemini CLI to API Proxy
A proxy server that converts Google's Gemini CLI authentication to standard API format, allowing you to use Gemini models with any Gemini API client.
## Features
- OAuth 2.0 authentication with Google Cloud- Automatic project ID detection and caching- Support for both streaming and non-streaming requests- Converts Google's internal API format to standard Gemini API format- Credential caching for seamless restarts
## Prerequisites
- Python 3.7 or higher- Google Cloud account with Gemini API access- Required Python packages (see `requirements.txt`)
## Installation---title: Gemini CLI to API Proxyemoji: 🤖colorFrom: bluecolorTo: purplesdk: dockerpinned: falselicense: mitapp_port: 7860---
# Gemini CLI to API Proxy (geminicli2api)
A FastAPI-based proxy server that converts the Gemini CLI tool into both OpenAI-compatible and native Gemini API endpoints. This allows you to leverage Google's free Gemini API quota through familiar OpenAI API interfaces or direct Gemini API calls.
## 🚀 Features
- **OpenAI-Compatible API**: Drop-in replacement for OpenAI's chat completions API- **Native Gemini API**: Direct proxy to Google's Gemini API- **Streaming Support**: Real-time streaming responses for both API formats- **Multimodal Support**: Text and image inputs- **Authentication**: Multiple auth methods (Bearer, Basic, API key)- **Docker Ready**: Containerized for easy deployment- **Hugging Face Spaces**: Ready for deployment on Hugging Face
## 🔧 Environment Variables
### Required- `GEMINI_AUTH_PASSWORD`: Authentication password for API access
### Optional Credential Sources (choose one)- `GEMINI_CREDENTIALS`: JSON string containing Google OAuth credentials- `GOOGLE_APPLICATION_CREDENTIALS`: Path to Google OAuth credentials file- `GOOGLE_CLOUD_PROJECT`: Google Cloud project ID- `GEMINI_PROJECT_ID`: Alternative project ID variable
### Example Credentials JSON```json{ "client_id": "your-client-id", "client_secret": "your-client-secret", "token": "your-access-token", "refresh_token": "your-refresh-token", "scopes": ["https://www.googleapis.com/auth/cloud-platform"], "token_uri": "https://oauth2.googleapis.com/token"}```
1. Clone or download this repository2. Install the required dependencies: ```bash pip install -r requirements.txt ```## 📡 API Endpoints
## Setup and Usage### OpenAI-Compatible Endpoints- `POST /v1/chat/completions` - Chat completions (streaming & non-streaming)- `GET /v1/models` - List available models
### First Time Setup### Native Gemini Endpoints - `GET /v1beta/models` - List Gemini models- `POST /v1beta/models/{model}:generateContent` - Generate content- `POST /v1beta/models/{model}:streamGenerateContent` - Stream content- All other Gemini API endpoints are proxied through
1. **(Optional) Configure your settings:** If you know your Google Cloud project ID, you can set it in the `.env` file to skip automatic detection: ```bash # Edit the .env file GEMINI_PROJECT_ID=your-project-id # Optional: Change the default port GEMINI_PORT=8888 ```### Utility Endpoints- `GET /health` - Health check for container orchestration
2. **Start the proxy server:** ```bash python gemini_proxy.py ```## 🔐 Authentication
3. **Authenticate with Google:** - On first run, the proxy will display an authentication URL - Open the URL in your browser and sign in with your Google account - Grant the necessary permissions - The browser will show "Authentication successful!" when complete - The proxy will automatically save your credentials for future useThe API supports multiple authentication methods:
4. **Project ID Detection:** - If `GEMINI_PROJECT_ID` is set in the `.env` file, it will be used - Otherwise, the proxy will automatically detect and cache your Google Cloud project ID - This only happens once - subsequent runs will use the cached project ID1. **Bearer Token**: `Authorization: Bearer YOUR_PASSWORD`2. **Basic Auth**: `Authorization: Basic base64(username:YOUR_PASSWORD)`3. **Query Parameter**: `?key=YOUR_PASSWORD`4. **Google Header**: `x-goog-api-key: YOUR_PASSWORD`
### Regular Usage## 🐳 Docker Usage
After initial setup, simply run:```bashpython gemini_proxy.py```
The proxy server will start on `http://localhost:8888` and display:```Starting Gemini proxy server on http://localhost:8888Send your Gemini API requests to this address.# Build the imagedocker build -t geminicli2api .
# Run on default port 8888 (compatibility)docker run -p 8888:8888 \ -e GEMINI_AUTH_PASSWORD=your_password \ -e GEMINI_CREDENTIALS='{"client_id":"...","token":"..."}' \ -e PORT=8888 \ geminicli2api
# Run on port 7860 (Hugging Face compatible)docker run -p 7860:7860 \ -e GEMINI_AUTH_PASSWORD=your_password \ -e GEMINI_CREDENTIALS='{"client_id":"...","token":"..."}' \ -e PORT=7860 \ geminicli2api```
### Using with API Clients### Docker Compose
Configure your Gemini API client to use `http://localhost:8888` as the base URL. The proxy accepts standard Gemini API requests and handles the authentication automatically.
Example request:```bashcurl -X POST "http://localhost:8888/v1/models/gemini-pro:generateContent?key=123456" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "parts": [{"text": "Hello, how are you?"}] }] }'```
**Note:** The proxy supports multiple authentication methods. The `key` query parameter is the most compatible with standard Gemini clients.
### Safety Settings
The proxy automatically sets default safety settings to `BLOCK_NONE` for all categories if no safety settings are specified in the request. This provides maximum flexibility for content generation. The default categories are:# Default setup (port 8888)docker-compose up -d
- `HARM_CATEGORY_HARASSMENT`- `HARM_CATEGORY_HATE_SPEECH`- `HARM_CATEGORY_SEXUALLY_EXPLICIT`- `HARM_CATEGORY_DANGEROUS_CONTENT`
You can override these defaults by including your own `safetySettings` in the request payload.
## Authentication
The proxy supports multiple authentication methods for maximum compatibility:# Hugging Face setup (port 7860)docker-compose --profile hf up -d geminicli2api-hf```
- **Default Password:** `123456`- **Configuration:** Set `GEMINI_AUTH_PASSWORD` in `.env` file to change the password## 🤗 Hugging Face Spaces
### Authentication MethodsThis project is configured for Hugging Face Spaces deployment:
1. **API Key (Query Parameter)** - Compatible with standard Gemini clients: ```bash curl -X POST "http://localhost:8888/v1/models/gemini-pro:generateContent?key=123456" \ -H "Content-Type: application/json" \ -d '{"contents": [{"parts": [{"text": "Hello!"}]}]}' ```1. Fork this repository2. Create a new Space on Hugging Face3. Connect your repository4. Set the required environment variables in Space settings: - `GEMINI_AUTH_PASSWORD` - `GEMINI_CREDENTIALS` (or other credential source)
2. **Bearer Token** - Standard API token format: ```bash curl -X POST http://localhost:8888/v1/models/gemini-pro:generateContent \ -H "Authorization: Bearer 123456" \ -H "Content-Type: application/json" \ -d '{"contents": [{"parts": [{"text": "Hello!"}]}]}' ```The Space will automatically build and deploy using the included Dockerfile.
3. **HTTP Basic Authentication** - Traditional username/password: ```bash curl -u "user:123456" -X POST http://localhost:8888/v1/models/gemini-pro:generateContent \ -H "Content-Type: application/json" \ -d '{"contents": [{"parts": [{"text": "Hello!"}]}]}' ```## 📝 OpenAI API Example
**Python examples:**```pythonimport requestsfrom requests.auth import HTTPBasicAuthimport openai
# Method 1: Query parameterresponse = requests.post( "http://localhost:8888/v1/models/gemini-pro:generateContent?key=123456", json={"contents": [{"parts": [{"text": "Hello!"}]}]}# Configure client to use your proxyclient = openai.OpenAI( base_url="http://localhost:8888/v1", # or 7860 for HF api_key="your_password" # Your GEMINI_AUTH_PASSWORD)
# Method 2: Bearer tokenresponse = requests.post( "http://localhost:8888/v1/models/gemini-pro:generateContent", headers={"Authorization": "Bearer 123456"}, json={"contents": [{"parts": [{"text": "Hello!"}]}]}# Use like normal OpenAI APIresponse = client.chat.completions.create( model="gemini-2.0-flash-exp", messages=[ {"role": "user", "content": "Hello, how are you?"} ], stream=True)
# Method 3: Basic authresponse = requests.post( "http://localhost:8888/v1/models/gemini-pro:generateContent", auth=HTTPBasicAuth("user", "123456"), json={"contents": [{"parts": [{"text": "Hello!"}]}]})for chunk in response: print(chunk.choices[0].delta.content, end="")```
## Configuration## 🔧 Native Gemini API Example
The proxy uses the following configuration:- **Port:** 8888 (default, configurable via `.env`)- **Credential file:** `oauth_creds.json` (automatically created)- **Configuration file:** `.env` (optional settings)- **Scopes:** Cloud Platform, User Info (email/profile), OpenID
### Configuration File (.env)```pythonimport requests
You can create a `.env` file in the same directory as the script to configure the proxy:headers = { "Authorization": "Bearer your_password", "Content-Type": "application/json"}
```bash# Set your Google Cloud Project ID to skip automatic detectionGEMINI_PROJECT_ID=my-gcp-project-123data = { "contents": [ { "role": "user", "parts": [{"text": "Hello, how are you?"}] } ]}
# Set a custom port (default is 8888)GEMINI_PORT=9000response = requests.post( "http://localhost:8888/v1beta/models/gemini-2.0-flash-exp:generateContent", # or 7860 for HF headers=headers, json=data)
# Set authentication password (default is 123456)GEMINI_AUTH_PASSWORD=your-secure-passwordprint(response.json())```
**Note:** The `.env` file is automatically excluded from version control via `.gitignore`.
## File Structure
- `gemini_proxy.py` - Main proxy server- `oauth_creds.json` - Cached OAuth credentials and project ID (auto-generated)- `requirements.txt` - Python dependencies- `.env` - Configuration file (optional, create as needed)- `.gitignore` - Prevents credential and config files from being committed
## Troubleshooting
### Port Already in UseIf you see "error while attempting to bind on address", another instance is already running. Stop the existing process or use a different port.
### Authentication Issues (Google OAuth)- Delete `oauth_creds.json` and restart to re-authenticate- Ensure your Google account has access to Google Cloud and Gemini API- Check that the required scopes are granted during authentication
### Authentication Issues (Proxy Access)- If you get 401 Unauthorized errors, check your authentication method- Default password is `123456` unless changed in `.env` file- Try different authentication methods: - Query parameter: `?key=123456` - Bearer token: `Authorization: Bearer 123456` - Basic auth: `Authorization: Basic base64(user:123456)`- Most Gemini clients work best with the query parameter method (`?key=password`)
### Project ID Issues- The proxy automatically detects your project ID on first run- If detection fails, you can manually set `GEMINI_PROJECT_ID` in the `.env` file- Check your Google Cloud project permissions if auto-detection fails- Delete `oauth_creds.json` to force re-detection- Project ID in `.env` file takes priority over cached and auto-detected project IDs## 🎯 Supported Models
## Security Notes- `gemini-2.0-flash-exp`- `gemini-1.5-flash`- `gemini-1.5-flash-8b`- `gemini-1.5-pro`- `gemini-1.0-pro`
- **Never commit `oauth_creds.json`** - it contains sensitive authentication tokens- The `.gitignore` file is configured to prevent accidental commits- Credentials are stored locally and refreshed automatically when expired- The proxy runs on localhost only for security## 📄 License
## API CompatibilityMIT License - see LICENSE file for details.
This proxy converts between:- **Input:** Standard Gemini API format- **Output:** Standard Gemini API responses- **Internal:** Google's Cloud Code Assist API format## 🤝 Contributing
The conversion is transparent to API clients.Contributions are welcome! Please feel free to submit a Pull Request.12234566fastapiuvicornuvicorn[standard]requestspython-dotenvgoogle-auth-oauthlibasynciopydantic123456758import osimport uvicornfrom src.main import app
if __name__ == "__main__": host = os.getenv("HOST", "0.0.0.0") port = int(os.getenv("PORT", "8888")) uvicorn.run(app, host="0.0.0.0", port=8888) uvicorn.run(app, host=host, port=port)21 unmodified lines2223242526272852 unmodified lines818283848586878889909130 unmodified lines1221231241191251261271281291241251301311321331271281341351361371381394 unmodified lines1441451461401471481491501517 unmodified lines15916016116216316416516651 unmodified lines21821922022122222322498 unmodified lines32332432531531631731831932032632732821 unmodified linescredentials = Noneuser_project_id = Noneonboarding_complete = Falsecredentials_from_env = False # Track if credentials came from environment variable
security = HTTPBasic()
52 unmodified lines )
def save_credentials(creds, project_id=None): global credentials_from_env # Don't save to file if credentials came from environment variable if credentials_from_env: return creds_data = { "client_id": CLIENT_ID,30 unmodified lines
def get_credentials(): """Loads credentials matching gemini-cli OAuth2 flow.""" global credentials global credentials, credentials_from_env if credentials and credentials.token: return credentials env_creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") if env_creds and os.path.exists(env_creds): # Check for credentials in environment variable (JSON string) env_creds_json = os.getenv("GEMINI_CREDENTIALS") if env_creds_json: try: with open(env_creds, "r") as f: creds_data = json.load(f) creds_data = json.loads(env_creds_json) credentials = Credentials.from_authorized_user_info(creds_data, SCOPES) credentials_from_env = True # Mark as environment credentials
if credentials.refresh_token: try:4 unmodified lines return credentials except Exception as e: pass # Fall through to file-based credentials
# Check for credentials file (CREDENTIAL_FILE now includes GOOGLE_APPLICATION_CREDENTIALS path if set) if os.path.exists(CREDENTIAL_FILE): try: with open(CREDENTIAL_FILE, "r") as f:7 unmodified lines creds_data["scopes"] = creds_data["scope"].split() credentials = Credentials.from_authorized_user_info(creds_data, SCOPES) # Mark as environment credentials if GOOGLE_APPLICATION_CREDENTIALS was used credentials_from_env = bool(os.getenv("GOOGLE_APPLICATION_CREDENTIALS"))
if credentials.refresh_token: try:51 unmodified lines try: flow.fetch_token(code=auth_code) credentials = flow.credentials credentials_from_env = False # Mark as file-based credentials save_credentials(credentials) print("Authentication successful! Credentials saved.") return credentials98 unmodified lines save_credentials(creds, user_project_id) return user_project_id
gemini_env_project_id = os.getenv("GEMINI_PROJECT_ID") if gemini_env_project_id: user_project_id = gemini_env_project_id save_credentials(creds, user_project_id) return user_project_id
if os.path.exists(CREDENTIAL_FILE): try: with open(CREDENTIAL_FILE, "r") as f:20 unmodified lines212223242425262720 unmodified lines
# File PathsSCRIPT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))CREDENTIAL_FILE = os.path.join(SCRIPT_DIR, "oauth_creds.json")CREDENTIAL_FILE = os.path.join(SCRIPT_DIR, os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "oauth_creds.json"))
# AuthenticationGEMINI_AUTH_PASSWORD = os.getenv("GEMINI_AUTH_PASSWORD", "123456")47 unmodified lines484950515253545556575847 unmodified lines } )
# Health check endpoint for Docker/Hugging Face@app.get("/health")async def health_check(): """Health check endpoint for container orchestration.""" return {"status": "healthy", "service": "geminicli2api"}
app.include_router(openai_router)app.include_router(gemini_router).env.example+13-7
LICENSE+1-1
README.md+142-188
requirements.txt+2-2
run.py+4-1
src/auth.py+17-12
src/config.py+1-1
src/main.py+6