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
123456789# Gemini Proxy Configuration# Set your Google Cloud Project ID here to skip automatic detectionGEMINI_PROJECT_ID=# Optional: Set a custom port (default is 8888)GEMINI_PORT=8888# Authentication password for the proxy (default is 123456)GEMINI_AUTH_PASSWORD=123456123456789101112131415# Required: Authentication password for API accessGEMINI_AUTH_PASSWORD=123456# 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"}# 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)
123456MIT LicenseCopyright (c) 2025 gzzhongqiPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to deal123456MIT LicenseCopyright (c) 2024 Gemini CLI to API ProxyPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to deal
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229# Gemini CLI to API ProxyA 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`)## Installation1. Clone or download this repository2. Install the required dependencies:```bashpip install -r requirements.txt```## Setup and Usage### First Time Setup1. **(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 fileGEMINI_PROJECT_ID=your-project-id# Optional: Change the default portGEMINI_PORT=8888```2. **Start the proxy server:**```bashpython gemini_proxy.py```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 use4. **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 ID### Regular UsageAfter 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.```### Using with API ClientsConfigure 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 SettingsThe 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:- `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.## AuthenticationThe proxy supports multiple authentication methods for maximum compatibility:- **Default Password:** `123456`- **Configuration:** Set `GEMINI_AUTH_PASSWORD` in `.env` file to change the password### Authentication Methods1. **API Key (Query Parameter)** - Compatible with standard Gemini clients:```bashcurl -X POST "http://localhost:8888/v1/models/gemini-pro:generateContent?key=123456" \-H "Content-Type: application/json" \-d '{"contents": [{"parts": [{"text": "Hello!"}]}]}'```2. **Bearer Token** - Standard API token format:```bashcurl -X POST http://localhost:8888/v1/models/gemini-pro:generateContent \-H "Authorization: Bearer 123456" \-H "Content-Type: application/json" \-d '{"contents": [{"parts": [{"text": "Hello!"}]}]}'```3. **HTTP Basic Authentication** - Traditional username/password:```bashcurl -u "user:123456" -X POST http://localhost:8888/v1/models/gemini-pro:generateContent \-H "Content-Type: application/json" \-d '{"contents": [{"parts": [{"text": "Hello!"}]}]}'```**Python examples:**```pythonimport requestsfrom requests.auth import HTTPBasicAuth# Method 1: Query parameterresponse = requests.post("http://localhost:8888/v1/models/gemini-pro:generateContent?key=123456",json={"contents": [{"parts": [{"text": "Hello!"}]}]})# Method 2: Bearer tokenresponse = requests.post("http://localhost:8888/v1/models/gemini-pro:generateContent",headers={"Authorization": "Bearer 123456"},json={"contents": [{"parts": [{"text": "Hello!"}]}]})# Method 3: Basic authresponse = requests.post("http://localhost:8888/v1/models/gemini-pro:generateContent",auth=HTTPBasicAuth("user", "123456"),json={"contents": [{"parts": [{"text": "Hello!"}]}]})```## ConfigurationThe 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)You can create a `.env` file in the same directory as the script to configure the proxy:```bash# Set your Google Cloud Project ID to skip automatic detectionGEMINI_PROJECT_ID=my-gcp-project-123# Set a custom port (default is 8888)GEMINI_PORT=9000# Set authentication password (default is 123456)GEMINI_AUTH_PASSWORD=your-secure-password```**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## Security Notes- **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## API CompatibilityThis proxy converts between:- **Input:** Standard Gemini API format- **Output:** Standard Gemini API responses- **Internal:** Google's Cloud Code Assist API formatThe conversion is transparent to API clients.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183---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"}```## 📡 API Endpoints### OpenAI-Compatible Endpoints- `POST /v1/chat/completions` - Chat completions (streaming & non-streaming)- `GET /v1/models` - List available models### 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### Utility Endpoints- `GET /health` - Health check for container orchestration## 🔐 AuthenticationThe API supports multiple authentication methods:1. **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`## 🐳 Docker Usage```bash# 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```### Docker Compose```bash# Default setup (port 8888)docker-compose up -d# Hugging Face setup (port 7860)docker-compose --profile hf up -d geminicli2api-hf```## 🤗 Hugging Face SpacesThis project is configured for Hugging Face Spaces deployment: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)The Space will automatically build and deploy using the included Dockerfile.## 📝 OpenAI API Example```pythonimport openai# Configure client to use your proxyclient = openai.OpenAI(base_url="http://localhost:8888/v1", # or 7860 for HFapi_key="your_password" # Your GEMINI_AUTH_PASSWORD)# 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)for chunk in response:print(chunk.choices[0].delta.content, end="")```## 🔧 Native Gemini API Example```pythonimport requestsheaders = {"Authorization": "Bearer your_password","Content-Type": "application/json"}data = {"contents": [{"role": "user","parts": [{"text": "Hello, how are you?"}]}]}response = requests.post("http://localhost:8888/v1beta/models/gemini-2.0-flash-exp:generateContent", # or 7860 for HFheaders=headers,json=data)print(response.json())```## 🎯 Supported Models- `gemini-2.0-flash-exp`- `gemini-1.5-flash`- `gemini-1.5-flash-8b`- `gemini-1.5-pro`- `gemini-1.0-pro`## 📄 LicenseMIT License - see LICENSE file for details.## 🤝 ContributingContributions are welcome! Please feel free to submit a Pull Request.
123456fastapiuvicornrequestspython-dotenvgoogle-auth-oauthlibasyncio123456fastapiuvicorn[standard]requestspython-dotenvgoogle-auth-oauthlibpydantic
12345import uvicornfrom src.main import appif __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8888)12345678import osimport uvicornfrom src.main import appif __name__ == "__main__":host = os.getenv("HOST", "0.0.0.0")port = int(os.getenv("PORT", "8888"))uvicorn.run(app, host=host, port=port)
21 unmodified lines22232425262752 unmodified lines80818283848530 unmodified lines1161171181191201211221231241251261271281291301311324 unmodified lines1371381391401411421437 unmodified lines15115215315415515651 unmodified lines20820921021121221398 unmodified lines31231331431531631731831932032132232321 unmodified linescredentials = Noneuser_project_id = Noneonboarding_complete = Falsesecurity = HTTPBasic()52 unmodified lines)def save_credentials(creds, project_id=None):creds_data = {"client_id": CLIENT_ID,30 unmodified linesdef get_credentials():"""Loads credentials matching gemini-cli OAuth2 flow."""global credentialsif credentials and credentials.token:return credentialsenv_creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")if env_creds and os.path.exists(env_creds):try:with open(env_creds, "r") as f:creds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)if credentials.refresh_token:try:4 unmodified linesreturn credentialsexcept Exception as e:pass # Fall through to file-based credentialsif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:7 unmodified linescreds_data["scopes"] = creds_data["scope"].split()credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)if credentials.refresh_token:try:51 unmodified linestry:flow.fetch_token(code=auth_code)credentials = flow.credentialssave_credentials(credentials)print("Authentication successful! Credentials saved.")return credentials98 unmodified linessave_credentials(creds, user_project_id)return user_project_idgemini_env_project_id = os.getenv("GEMINI_PROJECT_ID")if gemini_env_project_id:user_project_id = gemini_env_project_idsave_credentials(creds, user_project_id)return user_project_idif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:21 unmodified lines2223242526272852 unmodified lines818283848586878889909130 unmodified lines1221231241251261271281291301311321331341351361371381394 unmodified lines1441451461471481491501517 unmodified lines15916016116216316416516651 unmodified lines21821922022122222322498 unmodified lines32332432532632732821 unmodified linescredentials = Noneuser_project_id = Noneonboarding_complete = Falsecredentials_from_env = False # Track if credentials came from environment variablesecurity = 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 variableif credentials_from_env:returncreds_data = {"client_id": CLIENT_ID,30 unmodified linesdef get_credentials():"""Loads credentials matching gemini-cli OAuth2 flow."""global credentials, credentials_from_envif credentials and credentials.token:return credentials# Check for credentials in environment variable (JSON string)env_creds_json = os.getenv("GEMINI_CREDENTIALS")if env_creds_json:try:creds_data = json.loads(env_creds_json)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)credentials_from_env = True # Mark as environment credentialsif credentials.refresh_token:try:4 unmodified linesreturn credentialsexcept 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 linescreds_data["scopes"] = creds_data["scope"].split()credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)# Mark as environment credentials if GOOGLE_APPLICATION_CREDENTIALS was usedcredentials_from_env = bool(os.getenv("GOOGLE_APPLICATION_CREDENTIALS"))if credentials.refresh_token:try:51 unmodified linestry:flow.fetch_token(code=auth_code)credentials = flow.credentialscredentials_from_env = False # Mark as file-based credentialssave_credentials(credentials)print("Authentication successful! Credentials saved.")return credentials98 unmodified linessave_credentials(creds, user_project_id)return user_project_idif os.path.exists(CREDENTIAL_FILE):try:with open(CREDENTIAL_FILE, "r") as f:
20 unmodified lines2122232425262720 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")# AuthenticationGEMINI_AUTH_PASSWORD = os.getenv("GEMINI_AUTH_PASSWORD", "123456")20 unmodified lines2122232425262720 unmodified lines# File PathsSCRIPT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))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 lines484950515247 unmodified lines})app.include_router(openai_router)app.include_router(gemini_router)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