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59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# GeminiCLI to API

**Convert GeminiCLI and Antigravity to OpenAI, GEMINI, and Claude API Compatible Interfaces**

[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![License: CNC-1.0](https://img.shields.io/badge/License-CNC--1.0-red.svg)](../LICENSE)
[![Docker](https://img.shields.io/badge/docker-available-blue.svg)](https://github.com/su-kaka/gcli2api/pkgs/container/gcli2api)

[δΈ­ζ–‡](../README.md) | English

## πŸš€ Quick Deploy

[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/97VMEF?referralCode=su-kaka)
---

## ⚠️ License Declaration

**This project is licensed under the Cooperative Non-Commercial License (CNC-1.0)**

This is a strict anti-commercial open source license. Please refer to the [LICENSE](../LICENSE) file for details.

### βœ… Permitted Uses:
- Personal learning, research, and educational purposes
- Non-profit organization use
- Open source project integration (must comply with the same license)
- Academic research and publication

### ❌ Prohibited Uses:
- Any form of commercial use
- Enterprise use with annual revenue exceeding $1 million
- Venture capital-backed or publicly traded companies
- Providing paid services or products
- Commercial competitive use

---

## Core Features

### πŸ”„ API Endpoints and Format Support

**Multi-endpoint Multi-format Support**
- **OpenAI Compatible Endpoints**: `/v1/chat/completions` and `/v1/models`
  - Supports standard OpenAI format (messages structure)
  - Supports Gemini native format (contents structure)
  - Automatic format detection and conversion, no manual switching required
  - Supports multimodal input (text + images)
- **Gemini Native Endpoints**: `/v1/models/{model}:generateContent` and `streamGenerateContent`
  - Supports complete Gemini native API specifications
  - Multiple authentication methods: Bearer Token, x-goog-api-key header, URL parameter key
- **Claude Format Compatibility**: Full support for Claude API format
  - Endpoint: `/v1/messages` (follows Claude API specification)
  - Supports Claude standard messages format
  - Supports system parameter and Claude-specific features
  - Automatically converts to backend-supported format
- **Antigravity API Support**: Supports OpenAI, Gemini, and Claude formats
  - OpenAI format endpoint: `/antigravity/v1/chat/completions`
  - Gemini format endpoint: `/antigravity/v1/models/{model}:generateContent` and `streamGenerateContent`
  - Claude format endpoint: `/antigravity/v1/messages`
  - Supports all Antigravity models (Claude, Gemini, etc.)
  - Automatic model name mapping and thinking mode detection

### πŸ” Authentication and Security Management

**Flexible Password Management**
- **Separate Password Support**: API password (chat endpoints) and control panel password can be set independently
- **Multiple Authentication Methods**: Supports Authorization Bearer, x-goog-api-key header, URL parameters, etc.
- **JWT Token Authentication**: Control panel supports JWT token authentication
- **User Email Retrieval**: Automatically retrieves and displays Google account email addresses

### πŸ“Š Intelligent Credential Management System

**Advanced Credential Management**
- Multiple Google OAuth credential automatic rotation
- Enhanced stability through redundant authentication
- Load balancing and concurrent request support
- Automatic failure detection and credential disabling
- Credential usage statistics and quota management
- Support for manual enable/disable credential files
- Batch credential file operations (enable, disable, delete)

**Credential Status Monitoring**
- Real-time credential health checks
- Error code tracking (429, 403, 500, etc.)
- Automatic banning mechanism (configurable)
- Credential rotation strategy (based on call count)
- Usage statistics and quota monitoring

### 🌊 Streaming and Response Processing

**Multiple Streaming Support**
- True real-time streaming responses
- Fake streaming mode (for compatibility)
- Streaming anti-truncation feature (prevents answer truncation)
- Asynchronous task management and timeout handling

**Response Optimization**
- Thinking chain content separation
- Reasoning process (reasoning_content) handling
- Multi-turn conversation context management
- Compatibility mode (converts system messages to user messages)

### πŸŽ›οΈ Web Management Console

**Full-featured Web Interface**
- OAuth authentication flow management (supports GCLI and Antigravity dual modes)
- Credential file upload, download, and management
- Real-time log viewing (WebSocket)
- System configuration management
- Usage statistics and monitoring dashboard
- Mobile-friendly interface

**Batch Operation Support**
- ZIP file batch credential upload (GCLI and Antigravity)
- Batch enable/disable/delete credentials
- Batch user email retrieval
- Batch configuration management
- Unified batch upload interface for all credential types

### πŸ“ˆ Usage Statistics and Monitoring

**Detailed Usage Statistics**
- Call count statistics by credential file
- Gemini 2.5 Pro model specific statistics
- Daily quota management (UTC+7 reset)
- Aggregated statistics and analysis
- Custom daily limit configuration

**Real-time Monitoring**
- WebSocket real-time log streams
- System status monitoring
- Credential health status
- API call success rate statistics

### πŸ”§ Advanced Configuration and Customization

**Network and Proxy Configuration**
- HTTP/HTTPS proxy support
- Proxy endpoint configuration (OAuth, Google APIs, metadata service)
- Timeout and retry configuration
- Network error handling and recovery

**Performance and Stability Configuration**
- 429 error automatic retry (configurable interval and attempts)
- Anti-truncation maximum retry attempts
- Credential rotation strategy
- Concurrent request management

**Logging and Debugging**
- Multi-level logging system (DEBUG, INFO, WARNING, ERROR)
- Log file management
- Real-time log streams
- Log download and clearing

### πŸ”„ Environment Variables and Configuration Management

**Flexible Configuration Methods**
- TOML configuration file support
- Environment variable configuration
- Hot configuration updates (partial configuration items)
- Configuration locking (environment variable priority)

**Environment Variable Credential Support**
- `GCLI_CREDS_*` format environment variable import
- Automatic loading of environment variable credentials
- Base64 encoded credential support
- Docker container friendly

## Supported Models

All models have 1M context window capacity. Each credential file provides 1000 request quota.

### πŸ€– Base Models
- `gemini-2.5-pro`
- `gemini-3-pro-preview`

### 🧠 Thinking Models
- `gemini-2.5-pro-maxthinking`: Maximum thinking budget mode
- `gemini-2.5-pro-nothinking`: No thinking mode
- Supports custom thinking budget configuration
- Automatic separation of thinking content and final answers

### πŸ” Search-Enhanced Models
- `gemini-2.5-pro-search`: Model with integrated search functionality

### 🌊 Special Feature Variants
- **Fake Streaming Mode**: Add `-假桁式` suffix to any model name
  - Example: `gemini-2.5-pro-假桁式`
  - For scenarios requiring streaming responses but server doesn't support true streaming
- **Streaming Anti-truncation Mode**: Add `ζ΅εΌζŠ—ζˆͺζ–­/` prefix to model name
  - Example: `ζ΅εΌζŠ—ζˆͺζ–­/gemini-2.5-pro`  
  - Automatically detects response truncation and retries to ensure complete answers

### πŸ”§ Automatic Model Feature Detection
- System automatically recognizes feature identifiers in model names
- Transparently handles feature mode transitions
- Supports feature combination usage

---

## Installation Guide

### Termux Environment

**Initial Installation**
```bash
curl -o termux-install.sh "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/termux-install.sh" && chmod +x termux-install.sh && ./termux-install.sh
```

**Restart Service**
```bash
cd gcli2api
bash termux-start.sh
```

### Windows Environment

**Initial Installation**
```powershell
iex (iwr "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/install.ps1" -UseBasicParsing).Content
```

**Restart Service**
Double-click to execute `start.bat`

### Linux Environment

**Initial Installation**
```bash
curl -o install.sh "https://raw.githubusercontent.com/su-kaka/gcli2api/refs/heads/master/install.sh" && chmod +x install.sh && ./install.sh
```

**Restart Service**
```bash
cd gcli2api
bash start.sh
```

### Docker Environment

**Docker Run Command**
```bash
# Using universal password
docker run -d --name gcli2api --network host -e PASSWORD=pwd -e PORT=7861 -v $(pwd)/data/creds:/app/creds ghcr.io/su-kaka/gcli2api:latest

# Using separate passwords
docker run -d --name gcli2api --network host -e API_PASSWORD=api_pwd -e PANEL_PASSWORD=panel_pwd -e PORT=7861 -v $(pwd)/data/creds:/app/creds ghcr.io/su-kaka/gcli2api:latest
```

**Docker Compose Run Command**
1. Save the following content as `docker-compose.yml` file:
    ```yaml
    version: '3.8'

    services:
      gcli2api:
        image: ghcr.io/su-kaka/gcli2api:latest
        container_name: gcli2api
        restart: unless-stopped
        network_mode: host
        environment:
          # Using universal password (recommended for simple deployment)
          - PASSWORD=pwd
          - PORT=7861
          # Or use separate passwords (recommended for production)
          # - API_PASSWORD=your_api_password
          # - PANEL_PASSWORD=your_panel_password
        volumes:
          - ./data/creds:/app/creds
        healthcheck:
          test: ["CMD-SHELL", "python -c \"import sys, urllib.request, os; port = os.environ.get('PORT', '7861'); req = urllib.request.Request(f'http://localhost:{port}/v1/models', headers={'Authorization': 'Bearer ' + os.environ.get('PASSWORD', 'pwd')}); sys.exit(0 if urllib.request.urlopen(req, timeout=5).getcode() == 200 else 1)\""]
          interval: 30s
          timeout: 10s
          retries: 3
          start_period: 40s
    ```
2. Start the service:
    ```bash
    docker-compose up -d
    ```

---

## ⚠️ Important Notes

- The current OAuth authentication process **only supports localhost access**, meaning authentication must be completed through `http://127.0.0.1:7861/auth` (default port 7861, modifiable via PORT environment variable).
- **For deployment on cloud servers or other remote environments, please first run the service locally and complete OAuth authentication to obtain the generated json credential files (located in the `./geminicli/creds` directory), then upload these files via the auth panel.**
- **Please strictly comply with usage restrictions, only for personal learning and non-commercial purposes**

---

## Configuration Instructions

1. Visit `http://127.0.0.1:7861/auth` (default port, modifiable via PORT environment variable)
2. Complete OAuth authentication flow (default password: `pwd`, modifiable via environment variables)
   - **GCLI Mode**: For obtaining Google Cloud Gemini API credentials
   - **Antigravity Mode**: For obtaining Google Antigravity API credentials
3. Configure client:

**OpenAI Compatible Client:**
   - **Endpoint Address**: `http://127.0.0.1:7861/v1`
   - **API Key**: `pwd` (default value, modifiable via API_PASSWORD or PASSWORD environment variables)

**Gemini Native Client:**
   - **Endpoint Address**: `http://127.0.0.1:7861`
   - **Authentication Methods**:
     - `Authorization: Bearer your_api_password`
     - `x-goog-api-key: your_api_password`
     - URL parameter: `?key=your_api_password`

### 🌟 Dual Authentication Mode Support

**GCLI Authentication Mode**
- Standard Google Cloud Gemini API authentication
- Supports OAuth2.0 authentication flow
- Automatically enables required Google Cloud APIs

**Antigravity Authentication Mode**
- Dedicated authentication for Google Antigravity API
- Independent credential management system
- Supports batch upload and management
- Completely isolated from GCLI credentials

**Unified Management Interface**
- Manage both credential types in the "Batch Upload" tab
- Upper section: GCLI credential batch upload (blue theme)
- Lower section: Antigravity credential batch upload (green theme)
- Separate credential management tabs for each type

## πŸ’Ύ Data Storage Mode

### 🌟 Storage Backend Support

gcli2api supports two storage backends: **Local SQLite (Default)** and **MongoDB (Cloud Distributed Storage)**

### πŸ“ Local SQLite Storage (Default)

**Default Storage Method**
- No configuration required, works out of the box
- Data is stored in a local SQLite database
- Suitable for single-machine deployment and personal use
- Automatically creates and manages database files

### πŸƒ MongoDB Cloud Storage Mode

**Cloud Distributed Storage Solution**

When multi-instance deployment or cloud storage is needed, MongoDB storage mode can be enabled.

### βš™οΈ Enable MongoDB Mode

**Step 1: Configure MongoDB Connection**
```bash
# Local MongoDB
export MONGODB_URI="mongodb://localhost:27017"

# MongoDB Atlas cloud service
export MONGODB_URI="mongodb+srv://username:password@cluster.mongodb.net"

# MongoDB with authentication
export MONGODB_URI="mongodb://admin:password@localhost:27017/admin"

# Optional: Custom database name (default: gcli2api)
export MONGODB_DATABASE="my_gcli_db"
```

**Step 2: Start Application**
```bash
# Application will automatically detect MongoDB configuration and use MongoDB storage
python web.py
```

**Docker Environment using MongoDB**
```bash
# Single MongoDB deployment
docker run -d --name gcli2api \
  -e MONGODB_URI="mongodb://mongodb:27017" \
  -e API_PASSWORD=your_password \
  --network your_network \
  ghcr.io/su-kaka/gcli2api:latest

# Using MongoDB Atlas
docker run -d --name gcli2api \
  -e MONGODB_URI="mongodb+srv://user:pass@cluster.mongodb.net/gcli2api" \
  -e API_PASSWORD=your_password \
  -p 7861:7861 \
  ghcr.io/su-kaka/gcli2api:latest
```

**Docker Compose Example**
```yaml
version: '3.8'

services:
  mongodb:
    image: mongo:7
    container_name: gcli2api-mongodb
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password123
    volumes:
      - mongodb_data:/data/db
    ports:
      - "27017:27017"

  gcli2api:
    image: ghcr.io/su-kaka/gcli2api:latest
    container_name: gcli2api
    restart: unless-stopped
    depends_on:
      - mongodb
    environment:
      - MONGODB_URI=mongodb://admin:password123@mongodb:27017/admin
      - MONGODB_DATABASE=gcli2api
      - API_PASSWORD=your_api_password
      - PORT=7861
    ports:
      - "7861:7861"

volumes:
  mongodb_data:
```

### πŸ› οΈ Troubleshooting

**Common Issue Solutions**

```bash
# Check MongoDB connection
python mongodb_setup.py check

# View detailed status information
python mongodb_setup.py status

# Verify data migration results
python -c "
import asyncio
from src.storage_adapter import get_storage_adapter

async def test():
    storage = await get_storage_adapter()
    info = await storage.get_backend_info()
    print(f'Current mode: {info[\"backend_type\"]}')
    if info['backend_type'] == 'mongodb':
        print(f'Database: {info.get(\"database_name\", \"Unknown\")}')

asyncio.run(test())
"
```

**Migration Failure Handling**
```bash
# If migration is interrupted, re-run
python mongodb_setup.py migrate

# To rollback to local SQLite mode, remove MONGODB_URI environment variable
unset MONGODB_URI
# Then export data from MongoDB
python mongodb_setup.py export
```

### πŸ”§ Advanced Configuration

**MongoDB Connection Optimization**
```bash
# Connection pool and timeout configuration
export MONGODB_URI="mongodb://localhost:27017?maxPoolSize=10&serverSelectionTimeoutMS=5000"

# Replica set configuration
export MONGODB_URI="mongodb://host1:27017,host2:27017,host3:27017/gcli2api?replicaSet=myReplicaSet"

# Read-write separation configuration
export MONGODB_URI="mongodb://localhost:27017/gcli2api?readPreference=secondaryPreferred"
```

## πŸ—οΈ Technical Architecture

### Core Module Description

**Authentication and Credential Management** (`src/auth.py`, `src/credential_manager.py`)
- OAuth 2.0 authentication flow management
- Multi-credential file status management and rotation
- Automatic failure detection and recovery
- JWT token generation and validation

**API Routing and Conversion** (`src/openai_router.py`, `src/gemini_router.py`, `src/openai_transfer.py`)
- OpenAI and Gemini format bidirectional conversion
- Multimodal input processing (text+images)
- Thinking chain content separation and processing
- Streaming response management

**Network and Proxy** (`src/httpx_client.py`, `src/google_chat_api.py`)
- Unified HTTP client management
- Proxy configuration and hot update support
- Timeout and retry strategies
- Asynchronous request pool management

**State Management** (`src/state_manager.py`, `src/usage_stats.py`)
- Atomic state operations
- Usage statistics and quota management
- File locking and concurrency safety
- Data persistence (TOML format)

**Task Management** (`src/task_manager.py`)
- Global asynchronous task lifecycle management
- Resource cleanup and memory management
- Graceful shutdown and exception handling

**Web Console** (`src/web_routes.py`)
- RESTful API endpoints
- WebSocket real-time communication
- Mobile device adaptation detection
- Batch operation support

### Advanced Feature Implementation

**Streaming Anti-truncation Mechanism** (`src/anti_truncation.py`)
- Response truncation pattern detection
- Automatic retry and state recovery
- Context connection management

**Format Detection and Conversion** (`src/format_detector.py`)
- Automatic request format detection (OpenAI vs Gemini)
- Seamless format conversion
- Parameter mapping and validation

**User Agent Simulation** (`src/utils.py`)
- GeminiCLI format user agent generation
- Platform detection and client metadata
- API compatibility guarantee

### Environment Variable Configuration

**Basic Configuration**
- `PORT`: Service port (default: 7861)
- `HOST`: Server listen address (default: 0.0.0.0)

**Password Configuration**
- `API_PASSWORD`: Chat API access password (default: inherits PASSWORD or pwd)
- `PANEL_PASSWORD`: Control panel access password (default: inherits PASSWORD or pwd)  
- `PASSWORD`: Universal password, overrides the above two when set (default: pwd)

**Performance and Stability Configuration**
- `CALLS_PER_ROTATION`: Number of calls before each credential rotation (default: 10)
- `RETRY_429_ENABLED`: Enable 429 error automatic retry (default: true)
- `RETRY_429_MAX_RETRIES`: Maximum retry attempts for 429 errors (default: 3)
- `RETRY_429_INTERVAL`: Retry interval for 429 errors, in seconds (default: 1.0)
- `ANTI_TRUNCATION_MAX_ATTEMPTS`: Maximum retry attempts for anti-truncation (default: 3)

**Network and Proxy Configuration**
- `PROXY`: HTTP/HTTPS proxy address (format: `http://host:port`)
- `OAUTH_PROXY_URL`: OAuth authentication proxy endpoint
- `GOOGLEAPIS_PROXY_URL`: Google APIs proxy endpoint
- `METADATA_SERVICE_URL`: Metadata service proxy endpoint

**Automation Configuration**
- `AUTO_BAN`: Enable automatic credential banning (default: true)
- `AUTO_LOAD_ENV_CREDS`: Automatically load environment variable credentials at startup (default: false)

**Compatibility Configuration**
- `COMPATIBILITY_MODE`: Enable compatibility mode, converts system messages to user messages (default: false)

**Logging Configuration**
- `LOG_LEVEL`: Log level (DEBUG/INFO/WARNING/ERROR, default: INFO)
- `LOG_FILE`: Log file path (default: gcli2api.log)

**Storage Configuration**

**SQLite Configuration (Default)**
- No configuration required, automatically uses local SQLite database
- Database files are automatically created in the project directory

**MongoDB Configuration (Optional Cloud Storage)**
- `MONGODB_URI`: MongoDB connection string (enables MongoDB mode when set)
- `MONGODB_DATABASE`: MongoDB database name (default: gcli2api)

**Docker Usage Example**
```bash
# Using universal password
docker run -d --name gcli2api \
  -e PASSWORD=mypassword \
  -e PORT=11451 \
  -e GOOGLE_CREDENTIALS="$(cat credential.json | base64 -w 0)" \
  ghcr.io/su-kaka/gcli2api:latest

# Using separate passwords
docker run -d --name gcli2api \
  -e API_PASSWORD=my_api_password \
  -e PANEL_PASSWORD=my_panel_password \
  -e PORT=11451 \
  -e GOOGLE_CREDENTIALS="$(cat credential.json | base64 -w 0)" \
  ghcr.io/su-kaka/gcli2api:latest
```

Note: When credential environment variables are set, the system will prioritize using credentials from environment variables and ignore files in the `creds` directory.

### API Usage Methods

This service supports multiple complete sets of API endpoints:

#### 1. OpenAI Compatible Endpoints (GCLI)

**Endpoint:** `/v1/chat/completions`  
**Authentication:** `Authorization: Bearer your_api_password`

Supports two request formats with automatic detection and processing:

**OpenAI Format:**
```json
{
  "model": "gemini-2.5-pro",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant"},
    {"role": "user", "content": "Hello"}
  ],
  "temperature": 0.7,
  "stream": true
}
```

**Gemini Native Format:**
```json
{
  "model": "gemini-2.5-pro",
  "contents": [
    {"role": "user", "parts": [{"text": "Hello"}]}
  ],
  "systemInstruction": {"parts": [{"text": "You are a helpful assistant"}]},
  "generationConfig": {
    "temperature": 0.7
  }
}
```

#### 2. Gemini Native Endpoints (GCLI)

**Non-streaming Endpoint:** `/v1/models/{model}:generateContent`  
**Streaming Endpoint:** `/v1/models/{model}:streamGenerateContent`  
**Model List:** `/v1/models`

**Authentication Methods (choose one):**
- `Authorization: Bearer your_api_password`
- `x-goog-api-key: your_api_password`  
- URL parameter: `?key=your_api_password`

**Request Examples:**
```bash
# Using x-goog-api-key header
curl -X POST "http://127.0.0.1:7861/v1/models/gemini-2.5-pro:generateContent" \
  -H "x-goog-api-key: your_api_password" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello"}]}
    ]
  }'

# Using URL parameter
curl -X POST "http://127.0.0.1:7861/v1/models/gemini-2.5-pro:streamGenerateContent?key=your_api_password" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello"}]}
    ]
  }'
```

#### 3. Claude API Format Endpoints

**Endpoint:** `/v1/messages`
**Authentication:** `x-api-key: your_api_password` or `Authorization: Bearer your_api_password`

**Request Example:**
```bash
curl -X POST "http://127.0.0.1:7861/v1/messages" \
  -H "x-api-key: your_api_password" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-2.5-pro",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Hello, Claude!"}
    ]
  }'
```

**Support for system parameter:**
```json
{
  "model": "gemini-2.5-pro",
  "max_tokens": 1024,
  "system": "You are a helpful assistant",
  "messages": [
    {"role": "user", "content": "Hello"}
  ]
}
```

**Notes:**
- Fully compatible with Claude API format specification
- Automatically converts to Gemini format for backend calls
- Supports all Claude standard parameters
- Response format follows Claude API specification

#### 4. Antigravity API Endpoints

**Supports three formats: OpenAI, Gemini, and Claude**

##### Antigravity OpenAI Format Endpoints

**Endpoint:** `/antigravity/v1/chat/completions`
**Authentication:** `Authorization: Bearer your_api_password`

**Request Example:**
```bash
curl -X POST "http://127.0.0.1:7861/antigravity/v1/chat/completions" \
  -H "Authorization: Bearer your_api_password" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "messages": [
      {"role": "user", "content": "Hello"}
    ],
    "stream": true
  }'
```

##### Antigravity Gemini Format Endpoints

**Non-streaming Endpoint:** `/antigravity/v1/models/{model}:generateContent`
**Streaming Endpoint:** `/antigravity/v1/models/{model}:streamGenerateContent`

**Authentication Methods (choose one):**
- `Authorization: Bearer your_api_password`
- `x-goog-api-key: your_api_password`
- URL parameter: `?key=your_api_password`

**Request Examples:**
```bash
# Gemini format non-streaming request
curl -X POST "http://127.0.0.1:7861/antigravity/v1/models/claude-sonnet-4-5:generateContent" \
  -H "x-goog-api-key: your_api_password" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello"}]}
    ],
    "generationConfig": {
      "temperature": 0.7
    }
  }'

# Gemini format streaming request
curl -X POST "http://127.0.0.1:7861/antigravity/v1/models/gemini-2.5-flash:streamGenerateContent?key=your_api_password" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "Hello"}]}
    ]
  }'
```

##### Antigravity Claude Format Endpoints

**Endpoint:** `/antigravity/v1/messages`
**Authentication:** `x-api-key: your_api_password`

**Request Example:**
```bash
curl -X POST "http://127.0.0.1:7861/antigravity/v1/messages" \
  -H "x-api-key: your_api_password" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Hello"}
    ]
  }'
```

**Supported Antigravity Models:**
- Claude series: `claude-sonnet-4-5`, `claude-opus-4-5`, etc.
- Gemini series: `gemini-2.5-flash`, `gemini-2.5-pro`, etc.
- Automatically supports thinking models

**Gemini Native Example:**
```python
from io import BytesIO
from PIL import Image
from google.genai import Client
from google.genai.types import HttpOptions
from google.genai import types
# The client gets the API key from the environment variable `GEMINI_API_KEY`.

client = Client(
            api_key="pwd",
            http_options=HttpOptions(base_url="http://127.0.0.1:7861"),
        )

prompt = (
    """
    Draw a cat
    """
)

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=[prompt],
    config=types.GenerateContentConfig(
        image_config=types.ImageConfig(
            aspect_ratio="16:9",
        )
    )
)
for part in response.candidates[0].content.parts:
    if part.text is not None:
        print(part.text)
    elif part.inline_data is not None:
        image = Image.open(BytesIO(part.inline_data.data))
        image.save("generated_image.png")

```

**Notes:**
- OpenAI endpoints return OpenAI-compatible format
- Gemini endpoints return Gemini native format
- Claude endpoints return Claude-compatible format
- All endpoints use the same API password

## πŸ“‹ Complete API Reference

### Web Console API

**Authentication Endpoints**
- `POST /auth/login` - User login
- `POST /auth/start` - Start GCLI OAuth authentication
- `POST /auth/antigravity/start` - Start Antigravity OAuth authentication
- `POST /auth/callback` - Handle OAuth callback
- `GET /auth/status/{project_id}` - Check authentication status
- `GET /auth/antigravity/credentials` - Get Antigravity credentials

**GCLI Credential Management Endpoints**
- `GET /creds/status` - Get all GCLI credential statuses
- `POST /creds/action` - Single GCLI credential operation (enable/disable/delete)
- `POST /creds/batch-action` - Batch GCLI credential operations
- `POST /auth/upload` - Batch upload GCLI credential files (supports ZIP)
- `GET /creds/download/{filename}` - Download GCLI credential file
- `GET /creds/download-all` - Package download all GCLI credentials
- `POST /creds/fetch-email/{filename}` - Get GCLI user email
- `POST /creds/refresh-all-emails` - Batch refresh GCLI user emails

**Antigravity Credential Management Endpoints**
- `GET /antigravity/creds/status` - Get all Antigravity credential statuses
- `POST /antigravity/creds/action` - Single Antigravity credential operation (enable/disable/delete)
- `POST /antigravity/creds/batch-action` - Batch Antigravity credential operations
- `POST /antigravity/auth/upload` - Batch upload Antigravity credential files (supports ZIP)
- `GET /antigravity/creds/download/{filename}` - Download Antigravity credential file
- `GET /antigravity/creds/download-all` - Package download all Antigravity credentials
- `POST /antigravity/creds/fetch-email/{filename}` - Get Antigravity user email
- `POST /antigravity/creds/refresh-all-emails` - Batch refresh Antigravity user emails

**Configuration Management Endpoints**
- `GET /config/get` - Get current configuration
- `POST /config/save` - Save configuration

**Environment Variable Credential Endpoints**
- `POST /auth/load-env-creds` - Load environment variable credentials
- `DELETE /auth/env-creds` - Clear environment variable credentials
- `GET /auth/env-creds-status` - Get environment variable credential status

**Log Management Endpoints**
- `POST /auth/logs/clear` - Clear logs
- `GET /auth/logs/download` - Download log file
- `WebSocket /auth/logs/stream` - Real-time log stream

**Usage Statistics Endpoints**
- `GET /usage/stats` - Get usage statistics
- `GET /usage/aggregated` - Get aggregated statistics
- `POST /usage/update-limits` - Update usage limits
- `POST /usage/reset` - Reset usage statistics

### Chat API Features

**Multimodal Support**
```json
{
  "model": "gemini-2.5-pro",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "Describe this image"},
        {
          "type": "image_url",
          "image_url": {
            "url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABA..."
          }
        }
      ]
    }
  ]
}
```

**Thinking Mode Support**
```json
{
  "model": "gemini-2.5-pro-maxthinking",
  "messages": [
    {"role": "user", "content": "Complex math problem"}
  ]
}
```

Response will include separated thinking content:
```json
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Final answer",
      "reasoning_content": "Detailed thought process..."
    }
  }]
}
```

**Streaming Anti-truncation Usage**
```json
{
  "model": "ζ΅εΌζŠ—ζˆͺζ–­/gemini-2.5-pro",
  "messages": [
    {"role": "user", "content": "Write a long article"}
  ],
  "stream": true
}
```

**Compatibility Mode**
```bash
# Enable compatibility mode
export COMPATIBILITY_MODE=true
```
In this mode, all `system` messages are converted to `user` messages, improving compatibility with certain clients.

---

## License and Disclaimer

This project is for learning and research purposes only. Using this project indicates that you agree to:
- Not use this project for any commercial purposes
- Bear all risks and responsibilities of using this project
- Comply with relevant terms of service and legal regulations

The project authors are not responsible for any direct or indirect losses arising from the use of this project.