Yay!
This commit is contained in:
commit
237d0c65ba
18 changed files with 1174 additions and 0 deletions
44
.dockerignore
Normal file
44
.dockerignore
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
npm-debug.log
|
||||||
|
yarn-error.log
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# Environment variables
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Git
|
||||||
|
.git/
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
# Docker
|
||||||
|
Dockerfile
|
||||||
|
docker-compose.yml
|
||||||
|
.dockerignore
|
||||||
|
|
||||||
|
# Documentation
|
||||||
|
README.md
|
||||||
|
*.md
|
||||||
|
|
||||||
|
# Test files
|
||||||
|
test-api.sh
|
||||||
|
example-client.js
|
||||||
15
.env.example
Normal file
15
.env.example
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
# API password that clients must use as the API key
|
||||||
|
API_PASSWORD=your_secure_password_here
|
||||||
|
|
||||||
|
# Gemini API keys (comma-separated)
|
||||||
|
GEMINI_API_KEYS=key1,key2,key3
|
||||||
|
|
||||||
|
# Server configuration
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
LOG_DIR=./logs
|
||||||
|
|
||||||
|
# Cloudflare Tunnel configuration (for Docker deployment)
|
||||||
|
# Get your tunnel token from: https://dash.cloudflare.com/
|
||||||
|
CLOUDFLARE_TUNNEL_TOKEN=your_cloudflare_tunnel_token_here
|
||||||
25
.gitignore
vendored
Normal file
25
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
package-lock.json
|
||||||
|
yarn.lock
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# Environment variables
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
47
Dockerfile
Normal file
47
Dockerfile
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
# Multi-stage build for smaller final image
|
||||||
|
FROM node:18-alpine AS builder
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install all dependencies (including dev dependencies for build)
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build TypeScript
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Production stage
|
||||||
|
FROM node:18-alpine AS production
|
||||||
|
|
||||||
|
# Install wget for health checks
|
||||||
|
RUN apk add --no-cache wget
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy package files
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Install only production dependencies
|
||||||
|
RUN npm ci --only=production
|
||||||
|
|
||||||
|
# Copy built files from builder stage
|
||||||
|
COPY --from=builder /app/dist ./dist
|
||||||
|
|
||||||
|
# Create logs directory
|
||||||
|
RUN mkdir -p /app/logs
|
||||||
|
|
||||||
|
# Expose the application port
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
# Set environment to production
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Start the application
|
||||||
|
CMD ["node", "dist/index.js"]
|
||||||
8
GeiminiRevolver.code-workspace
Normal file
8
GeiminiRevolver.code-workspace
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
{
|
||||||
|
"folders": [
|
||||||
|
{
|
||||||
|
"path": "."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {}
|
||||||
|
}
|
||||||
293
README.md
Normal file
293
README.md
Normal file
|
|
@ -0,0 +1,293 @@
|
||||||
|
# GeiminiRevolver
|
||||||
|
|
||||||
|
An OpenAI v1 compatible API endpoint that rotates Gemini API keys to avoid rate limiting. Built with TypeScript and Node.js.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- 🔐 **Password-based API key authentication** - Clients must provide a configured password as their API key
|
||||||
|
- 🔄 **Automatic API key rotation** - Rotates across multiple Gemini API keys to avoid rate limiting
|
||||||
|
- 📝 **Request/response logging** - Logs all API requests and responses to JSON files
|
||||||
|
- 🎯 **OpenAI v1 compatible** - Drop-in replacement for OpenAI API endpoints
|
||||||
|
- ⚡ **Rate limit handling** - Automatically handles rate limiting and rotates to available keys
|
||||||
|
- 🐳 **Docker support** - Containerized deployment with Docker and Docker Compose
|
||||||
|
- 🌐 **Cloudflare Tunnel integration** - Securely expose your API via Cloudflare tunnel
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Node.js (v18 or higher)
|
||||||
|
- npm or yarn
|
||||||
|
- Gemini API keys (get free keys from [Google AI Studio](https://makersuite.google.com/app/apikey))
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone the repository and navigate to the project directory
|
||||||
|
|
||||||
|
2. Install dependencies:
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Configure environment variables:
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Edit `.env` with your configuration:
|
||||||
|
```env
|
||||||
|
API_PASSWORD=your_secure_password_here
|
||||||
|
GEMINI_API_KEYS=key1,key2,key3
|
||||||
|
PORT=3000
|
||||||
|
LOG_DIR=./logs
|
||||||
|
```
|
||||||
|
|
||||||
|
### Running the Server
|
||||||
|
|
||||||
|
Development mode with auto-reload:
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Production mode:
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
## Docker Deployment
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Docker and Docker Compose installed
|
||||||
|
- Cloudflare account (for tunnel setup)
|
||||||
|
|
||||||
|
### Cloudflare Tunnel Setup
|
||||||
|
|
||||||
|
1. **Create a Cloudflare Tunnel:**
|
||||||
|
- Go to [Cloudflare Zero Trust Dashboard](https://dash.cloudflare.com/)
|
||||||
|
- Navigate to Access > Tunnels
|
||||||
|
- Create a new tunnel and copy the tunnel token
|
||||||
|
|
||||||
|
2. **Configure the tunnel:**
|
||||||
|
- Add your domain to the tunnel ingress rules
|
||||||
|
- Set the service to point to `http://geimini-revolver:3000`
|
||||||
|
|
||||||
|
### Docker Deployment
|
||||||
|
|
||||||
|
1. **Configure environment variables:**
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Edit `.env` with your configuration:**
|
||||||
|
```env
|
||||||
|
API_PASSWORD=your_secure_password_here
|
||||||
|
GEMINI_API_KEYS=key1,key2,key3
|
||||||
|
CLOUDFLARE_TUNNEL_TOKEN=your_cloudflare_tunnel_token_here
|
||||||
|
CLOUDFLARE_DOMAIN=your-domain.com
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Build and start with Docker Compose:**
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Check status:**
|
||||||
|
```bash
|
||||||
|
docker-compose ps
|
||||||
|
docker-compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **Stop the services:**
|
||||||
|
```bash
|
||||||
|
docker-compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker Commands
|
||||||
|
|
||||||
|
- **Build only:** `docker-compose build`
|
||||||
|
- **Rebuild without cache:** `docker-compose build --no-cache`
|
||||||
|
- **View logs:** `docker-compose logs -f geimini-revolver`
|
||||||
|
- **Restart services:** `docker-compose restart`
|
||||||
|
- **Stop and remove containers:** `docker-compose down -v`
|
||||||
|
|
||||||
|
### Accessing the API
|
||||||
|
|
||||||
|
With Cloudflare tunnel running, your API will be accessible at:
|
||||||
|
- `https://your-domain.com/v1/chat/completions`
|
||||||
|
- `https://your-domain.com/v1/models`
|
||||||
|
- `https://your-domain.com/health`
|
||||||
|
|
||||||
|
Use the same authentication method with your configured `API_PASSWORD`.
|
||||||
|
|
||||||
|
## API Usage
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
Use your configured `API_PASSWORD` as the Bearer token:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:3000/v1/chat/completions \
|
||||||
|
-H "Authorization: Bearer your_secure_password_here" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"model": "gemini-flash-lite-latest",
|
||||||
|
"messages": [
|
||||||
|
{"role": "user", "content": "Hello, how are you?"}
|
||||||
|
]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Endpoints
|
||||||
|
|
||||||
|
#### `POST /v1/chat/completions`
|
||||||
|
Create chat completions (OpenAI v1 compatible)
|
||||||
|
|
||||||
|
**Request body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model": "gemini-flash-lite-latest",
|
||||||
|
"messages": [
|
||||||
|
{"role": "user", "content": "Your message here"}
|
||||||
|
],
|
||||||
|
"temperature": 0.7,
|
||||||
|
"max_tokens": 1024
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "chatcmpl-req_1234567890_abc123",
|
||||||
|
"object": "chat.completion",
|
||||||
|
"created": 1234567890,
|
||||||
|
"model": "gemini-flash-lite-latest",
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"index": 0,
|
||||||
|
"message": {
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "Response from Gemini"
|
||||||
|
},
|
||||||
|
"finish_reason": "stop"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"usage": {
|
||||||
|
"prompt_tokens": 10,
|
||||||
|
"completion_tokens": 20,
|
||||||
|
"total_tokens": 30
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `GET /v1/models`
|
||||||
|
List available models
|
||||||
|
|
||||||
|
#### `GET /health`
|
||||||
|
Health check endpoint with key rotation statistics
|
||||||
|
|
||||||
|
## Logging
|
||||||
|
|
||||||
|
All requests and responses are logged to JSON files in the configured `LOG_DIR`. Log files are named by date: `api-logs-YYYY-MM-DD.json`
|
||||||
|
|
||||||
|
Each log entry contains:
|
||||||
|
- timestamp
|
||||||
|
- request ID
|
||||||
|
- type (request/response/error)
|
||||||
|
- full request/response data
|
||||||
|
|
||||||
|
## Key Rotation Strategy
|
||||||
|
|
||||||
|
The system uses a round-robin rotation strategy with rate limit awareness:
|
||||||
|
|
||||||
|
1. Keys are rotated in sequence
|
||||||
|
2. Rate-limited keys are temporarily skipped
|
||||||
|
3. If all keys are rate-limited, the least recently used key is selected
|
||||||
|
4. Request counts and last-used timestamps are tracked for monitoring
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Environment Variable | Description | Default |
|
||||||
|
|---------------------|-------------|---------|
|
||||||
|
| `API_PASSWORD` | Password clients must use as API key | (required) |
|
||||||
|
| `GEMINI_API_KEYS` | Comma-separated list of Gemini API keys | (required) |
|
||||||
|
| `PORT` | Server port | 3000 |
|
||||||
|
| `LOG_DIR` | Directory for log files | ./logs |
|
||||||
|
| `CLOUDFLARE_TUNNEL_TOKEN` | Cloudflare tunnel token (Docker only) | (required for Docker) |
|
||||||
|
| `CLOUDFLARE_DOMAIN` | Domain for Cloudflare tunnel (Docker only) | (required for Docker) |
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
GeiminiRevolver/
|
||||||
|
├── src/
|
||||||
|
│ ├── index.ts # Main server entry point
|
||||||
|
│ ├── config.ts # Configuration management
|
||||||
|
│ ├── auth.ts # Authentication middleware
|
||||||
|
│ ├── keyRotation.ts # API key rotation logic
|
||||||
|
│ ├── logger.ts # Request/response logging
|
||||||
|
│ ├── routes.ts # API route handlers
|
||||||
|
│ └── openaiTypes.ts # OpenAI type definitions
|
||||||
|
├── logs/ # Log files (created at runtime)
|
||||||
|
├── dist/ # Compiled JavaScript (created at build)
|
||||||
|
├── .env # Environment variables (not in git)
|
||||||
|
├── .env.example # Environment variables template
|
||||||
|
├── .dockerignore # Docker ignore rules
|
||||||
|
├── Dockerfile # Docker image configuration
|
||||||
|
├── docker-compose.yml # Docker Compose configuration
|
||||||
|
├── cloudflared-config.yml # Cloudflare tunnel configuration
|
||||||
|
├── package.json # Project dependencies
|
||||||
|
├── tsconfig.json # TypeScript configuration
|
||||||
|
├── test-api.sh # API testing script
|
||||||
|
├── example-client.js # Example client implementation
|
||||||
|
└── README.md # This file
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Notes
|
||||||
|
|
||||||
|
- Never commit `.env` file to version control
|
||||||
|
- Use strong passwords for `API_PASSWORD`
|
||||||
|
- Rotate your Gemini API keys regularly
|
||||||
|
- Keep the server behind proper authentication in production
|
||||||
|
- Log files may contain sensitive data - secure them appropriately
|
||||||
|
- When using Cloudflare Tunnel, enable additional authentication in Cloudflare Access
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Docker Issues
|
||||||
|
|
||||||
|
**Container won't start:**
|
||||||
|
```bash
|
||||||
|
docker-compose logs geimini-revolver
|
||||||
|
```
|
||||||
|
|
||||||
|
**Port conflicts:**
|
||||||
|
- Change the port mapping in `docker-compose.yml` or stop other services using port 3000
|
||||||
|
|
||||||
|
**Permission issues with logs:**
|
||||||
|
- Ensure the `./logs` directory has proper write permissions
|
||||||
|
|
||||||
|
**Cloudflare tunnel connection issues:**
|
||||||
|
- Verify your `CLOUDFLARE_TUNNEL_TOKEN` is correct
|
||||||
|
- Check that the tunnel is active in your Cloudflare dashboard
|
||||||
|
- Ensure the domain is properly configured in Cloudflare DNS
|
||||||
|
|
||||||
|
### Application Issues
|
||||||
|
|
||||||
|
**Rate limiting still occurring:**
|
||||||
|
- Add more Gemini API keys to your configuration
|
||||||
|
- Check the health endpoint for key usage statistics
|
||||||
|
- Consider implementing additional rate limiting at the application level
|
||||||
|
|
||||||
|
**Authentication failures:**
|
||||||
|
- Verify the `API_PASSWORD` matches between client and server
|
||||||
|
- Check that the Authorization header format is correct: `Bearer <password>`
|
||||||
|
|
||||||
|
**TypeScript build errors:**
|
||||||
|
- Ensure all dependencies are installed: `npm install`
|
||||||
|
- Clear build cache: `rm -rf dist/ && npm run build`
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
47
docker-compose.yml
Normal file
47
docker-compose.yml
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
# Main application
|
||||||
|
geimini-revolver:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: geimini-revolver
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
environment:
|
||||||
|
- API_PASSWORD=${API_PASSWORD}
|
||||||
|
- GEMINI_API_KEYS=${GEMINI_API_KEYS}
|
||||||
|
- PORT=3000
|
||||||
|
- LOG_DIR=/app/logs
|
||||||
|
- NODE_ENV=production
|
||||||
|
volumes:
|
||||||
|
# Persist logs to host
|
||||||
|
- ./logs:/app/logs
|
||||||
|
networks:
|
||||||
|
- geimini-network
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 40s
|
||||||
|
|
||||||
|
# Cloudflare Tunnel
|
||||||
|
cloudflared:
|
||||||
|
image: cloudflare/cloudflared:latest
|
||||||
|
container_name: cloudflared-tunnel
|
||||||
|
restart: unless-stopped
|
||||||
|
command: tunnel run
|
||||||
|
environment:
|
||||||
|
- TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN}
|
||||||
|
networks:
|
||||||
|
- geimini-network
|
||||||
|
depends_on:
|
||||||
|
geimini-revolver:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
networks:
|
||||||
|
geimini-network:
|
||||||
|
driver: bridge
|
||||||
84
example-client.js
Normal file
84
example-client.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
// Example client for using the GeiminiRevolver API
|
||||||
|
// This demonstrates how to use the OpenAI v1 compatible endpoint
|
||||||
|
|
||||||
|
const API_BASE_URL = 'http://localhost:3000';
|
||||||
|
const API_PASSWORD = 'change_this_secure_password'; // Change this to your configured password
|
||||||
|
|
||||||
|
async function chatCompletion(messages) {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/v1/chat/completions`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${API_PASSWORD}`,
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: 'gemini-flash-lite-latest',
|
||||||
|
messages: messages,
|
||||||
|
temperature: 0.7,
|
||||||
|
max_tokens: 1024
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json();
|
||||||
|
throw new Error(error.error?.message || 'Request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listModels() {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/v1/models`, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${API_PASSWORD}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json();
|
||||||
|
throw new Error(error.error?.message || 'Request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getHealth() {
|
||||||
|
const response = await fetch(`${API_BASE_URL}/health`);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Example usage
|
||||||
|
async function main() {
|
||||||
|
try {
|
||||||
|
console.log('Testing GeiminiRevolver API...\n');
|
||||||
|
|
||||||
|
// Check health
|
||||||
|
console.log('1. Health check:');
|
||||||
|
const health = await getHealth();
|
||||||
|
console.log(JSON.stringify(health, null, 2));
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
// List models
|
||||||
|
console.log('2. Available models:');
|
||||||
|
const models = await listModels();
|
||||||
|
console.log(JSON.stringify(models, null, 2));
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
// Chat completion
|
||||||
|
console.log('3. Chat completion:');
|
||||||
|
const chatResponse = await chatCompletion([
|
||||||
|
{ role: 'user', content: 'What is 2+2? Answer with just the number.' }
|
||||||
|
]);
|
||||||
|
console.log(JSON.stringify(chatResponse, null, 2));
|
||||||
|
console.log();
|
||||||
|
|
||||||
|
console.log('✓ All tests passed!');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run the example
|
||||||
|
main();
|
||||||
28
package.json
Normal file
28
package.json
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
{
|
||||||
|
"name": "geimini-revolver",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "OpenAI v1 compatible API endpoint for Gemini API key rotation",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"dev": "ts-node src/index.ts",
|
||||||
|
"watch": "tsc --watch"
|
||||||
|
},
|
||||||
|
"keywords": ["openai", "gemini", "api", "rotation"],
|
||||||
|
"author": "",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@google/generative-ai": "^0.21.0",
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/express": "^4.17.21",
|
||||||
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/node": "^20.10.0",
|
||||||
|
"typescript": "^5.3.3",
|
||||||
|
"ts-node": "^10.9.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
52
src/auth.ts
Normal file
52
src/auth.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import { config } from './config';
|
||||||
|
import { requestLogger } from './logger';
|
||||||
|
|
||||||
|
export const authenticateApiKey = (req: Request, res: Response, next: NextFunction): void => {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader) {
|
||||||
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path });
|
||||||
|
res.status(401).json({
|
||||||
|
error: {
|
||||||
|
message: 'Missing Authorization header',
|
||||||
|
type: 'invalid_request_error',
|
||||||
|
code: 'missing_api_key'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenAI format: "Bearer <api_key>"
|
||||||
|
const parts = authHeader.split(' ');
|
||||||
|
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
||||||
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
requestLogger.logError(requestId, { message: 'Invalid Authorization format', path: req.path });
|
||||||
|
res.status(401).json({
|
||||||
|
error: {
|
||||||
|
message: 'Invalid Authorization format. Expected: Bearer <api_key>',
|
||||||
|
type: 'invalid_request_error',
|
||||||
|
code: 'invalid_api_key_format'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const providedKey = parts[1];
|
||||||
|
|
||||||
|
if (providedKey !== config.apiPassword) {
|
||||||
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
requestLogger.logError(requestId, { message: 'Invalid API key', path: req.path });
|
||||||
|
res.status(401).json({
|
||||||
|
error: {
|
||||||
|
message: 'Invalid API key',
|
||||||
|
type: 'invalid_request_error',
|
||||||
|
code: 'invalid_api_key'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
};
|
||||||
19
src/config.ts
Normal file
19
src/config.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
apiPassword: process.env.API_PASSWORD || 'default_password',
|
||||||
|
geminiApiKeys: (process.env.GEMINI_API_KEYS || '').split(',').filter(key => key.trim()),
|
||||||
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
|
logDir: process.env.LOG_DIR || './logs',
|
||||||
|
model: 'gemini-flash-lite-latest'
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!config.apiPassword || config.apiPassword === 'default_password') {
|
||||||
|
console.warn('WARNING: Using default API password. Please set API_PASSWORD in .env file');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.geminiApiKeys.length === 0) {
|
||||||
|
throw new Error('No Gemini API keys configured. Please set GEMINI_API_KEYS in .env file');
|
||||||
|
}
|
||||||
47
src/index.ts
Normal file
47
src/index.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
import express, { Application } from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import { config } from './config';
|
||||||
|
import { authenticateApiKey } from './auth';
|
||||||
|
import routes from './routes';
|
||||||
|
|
||||||
|
const app: Application = express();
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// Request logging middleware
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Apply authentication to all API routes
|
||||||
|
app.use('/v1', authenticateApiKey);
|
||||||
|
|
||||||
|
// Routes
|
||||||
|
app.use('/', routes);
|
||||||
|
|
||||||
|
// Error handling middleware
|
||||||
|
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||||
|
console.error('Unhandled error:', err);
|
||||||
|
res.status(500).json({
|
||||||
|
error: {
|
||||||
|
message: 'Internal server error',
|
||||||
|
type: 'server_error',
|
||||||
|
code: 'internal_error'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
const PORT = config.port;
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`🚀 OpenAI v1 Compatible API Server running on port ${PORT}`);
|
||||||
|
console.log(`📝 Using model: ${config.model}`);
|
||||||
|
console.log(`🔑 Configured ${config.geminiApiKeys.length} Gemini API keys for rotation`);
|
||||||
|
console.log(`📁 Logging to: ${config.logDir}`);
|
||||||
|
console.log(`🔒 API requires password authentication`);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default app;
|
||||||
80
src/keyRotation.ts
Normal file
80
src/keyRotation.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
import { GoogleGenerativeAI } from '@google/generative-ai';
|
||||||
|
import { config } from './config';
|
||||||
|
|
||||||
|
interface KeyUsage {
|
||||||
|
key: string;
|
||||||
|
lastUsed: number;
|
||||||
|
requestCount: number;
|
||||||
|
rateLimitedUntil?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
class KeyRotationManager {
|
||||||
|
private keys: KeyUsage[] = [];
|
||||||
|
private currentIndex = 0;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.initializeKeys();
|
||||||
|
}
|
||||||
|
|
||||||
|
private initializeKeys(): void {
|
||||||
|
this.keys = config.geminiApiKeys.map(key => ({
|
||||||
|
key: key.trim(),
|
||||||
|
lastUsed: 0,
|
||||||
|
requestCount: 0
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private isRateLimited(keyUsage: KeyUsage): boolean {
|
||||||
|
if (!keyUsage.rateLimitedUntil) return false;
|
||||||
|
return Date.now() < keyUsage.rateLimitedUntil;
|
||||||
|
}
|
||||||
|
|
||||||
|
private markRateLimited(keyUsage: KeyUsage, durationMs: number = 60000): void {
|
||||||
|
keyUsage.rateLimitedUntil = Date.now() + durationMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
getNextAvailableKey(): string {
|
||||||
|
const now = Date.now();
|
||||||
|
let attempts = 0;
|
||||||
|
const maxAttempts = this.keys.length * 2;
|
||||||
|
|
||||||
|
while (attempts < maxAttempts) {
|
||||||
|
const keyUsage = this.keys[this.currentIndex];
|
||||||
|
|
||||||
|
if (!this.isRateLimited(keyUsage)) {
|
||||||
|
keyUsage.lastUsed = now;
|
||||||
|
keyUsage.requestCount++;
|
||||||
|
this.currentIndex = (this.currentIndex + 1) % this.keys.length;
|
||||||
|
return keyUsage.key;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.currentIndex = (this.currentIndex + 1) % this.keys.length;
|
||||||
|
attempts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If all keys are rate limited, return the least recently used one
|
||||||
|
const sortedKeys = [...this.keys].sort((a, b) => a.lastUsed - b.lastUsed);
|
||||||
|
const selectedKey = sortedKeys[0];
|
||||||
|
selectedKey.lastUsed = now;
|
||||||
|
selectedKey.requestCount++;
|
||||||
|
return selectedKey.key;
|
||||||
|
}
|
||||||
|
|
||||||
|
markKeyAsRateLimited(apiKey: string, durationMs?: number): void {
|
||||||
|
const keyUsage = this.keys.find(k => k.key === apiKey);
|
||||||
|
if (keyUsage) {
|
||||||
|
this.markRateLimited(keyUsage, durationMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getKeyStats(): KeyUsage[] {
|
||||||
|
return [...this.keys];
|
||||||
|
}
|
||||||
|
|
||||||
|
createGenerativeAI(): GoogleGenerativeAI {
|
||||||
|
const apiKey = this.getNextAvailableKey();
|
||||||
|
return new GoogleGenerativeAI(apiKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const keyRotationManager = new KeyRotationManager();
|
||||||
86
src/logger.ts
Normal file
86
src/logger.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { config } from './config';
|
||||||
|
|
||||||
|
interface LogEntry {
|
||||||
|
timestamp: string;
|
||||||
|
requestId: string;
|
||||||
|
type: 'request' | 'response' | 'error';
|
||||||
|
data: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class RequestLogger {
|
||||||
|
private logDir: string;
|
||||||
|
private currentLogFile: string;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.logDir = config.logDir;
|
||||||
|
this.ensureLogDirectory();
|
||||||
|
this.currentLogFile = this.getLogFileName();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureLogDirectory(): void {
|
||||||
|
if (!fs.existsSync(this.logDir)) {
|
||||||
|
fs.mkdirSync(this.logDir, { recursive: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getLogFileName(): string {
|
||||||
|
const date = new Date().toISOString().split('T')[0];
|
||||||
|
return path.join(this.logDir, `api-logs-${date}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateLogFileIfNeeded(): void {
|
||||||
|
const newLogFile = this.getLogFileName();
|
||||||
|
if (newLogFile !== this.currentLogFile) {
|
||||||
|
this.currentLogFile = newLogFile;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeLog(entry: LogEntry): void {
|
||||||
|
this.updateLogFileIfNeeded();
|
||||||
|
|
||||||
|
const logLine = JSON.stringify(entry) + '\n';
|
||||||
|
fs.appendFileSync(this.currentLogFile, logLine, 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
logRequest(requestId: string, data: any): void {
|
||||||
|
const entry: LogEntry = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
requestId,
|
||||||
|
type: 'request',
|
||||||
|
data
|
||||||
|
};
|
||||||
|
this.writeLog(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
logResponse(requestId: string, data: any): void {
|
||||||
|
const entry: LogEntry = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
requestId,
|
||||||
|
type: 'response',
|
||||||
|
data
|
||||||
|
};
|
||||||
|
this.writeLog(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
logError(requestId: string, error: any): void {
|
||||||
|
const entry: LogEntry = {
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
requestId,
|
||||||
|
type: 'error',
|
||||||
|
data: {
|
||||||
|
message: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
...error
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this.writeLog(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
generateRequestId(): string {
|
||||||
|
return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const requestLogger = new RequestLogger();
|
||||||
51
src/openaiTypes.ts
Normal file
51
src/openaiTypes.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
// OpenAI v1 API compatible types
|
||||||
|
|
||||||
|
export interface OpenAIMessage {
|
||||||
|
role: 'system' | 'user' | 'assistant';
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIChatRequest {
|
||||||
|
model: string;
|
||||||
|
messages: OpenAIMessage[];
|
||||||
|
temperature?: number;
|
||||||
|
max_tokens?: number;
|
||||||
|
top_p?: number;
|
||||||
|
stream?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIChoice {
|
||||||
|
index: number;
|
||||||
|
message: {
|
||||||
|
role: 'assistant';
|
||||||
|
content: string;
|
||||||
|
};
|
||||||
|
finish_reason: 'stop' | 'length' | 'content_filter';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIUsage {
|
||||||
|
prompt_tokens: number;
|
||||||
|
completion_tokens: number;
|
||||||
|
total_tokens: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIChatResponse {
|
||||||
|
id: string;
|
||||||
|
object: 'chat.completion';
|
||||||
|
created: number;
|
||||||
|
model: string;
|
||||||
|
choices: OpenAIChoice[];
|
||||||
|
usage: OpenAIUsage;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIModel {
|
||||||
|
id: string;
|
||||||
|
object: 'model';
|
||||||
|
created: number;
|
||||||
|
owned_by: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenAIModelsResponse {
|
||||||
|
object: 'list';
|
||||||
|
data: OpenAIModel[];
|
||||||
|
}
|
||||||
180
src/routes.ts
Normal file
180
src/routes.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
import { Router, Request, Response } from 'express';
|
||||||
|
import { GoogleGenerativeAI } from '@google/generative-ai';
|
||||||
|
import { keyRotationManager } from './keyRotation';
|
||||||
|
import { requestLogger } from './logger';
|
||||||
|
import { config } from './config';
|
||||||
|
import {
|
||||||
|
OpenAIChatRequest,
|
||||||
|
OpenAIChatResponse,
|
||||||
|
OpenAIModelsResponse
|
||||||
|
} from './openaiTypes';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// Convert OpenAI format to Gemini format
|
||||||
|
function convertToGeminiMessages(messages: any[]): any[] {
|
||||||
|
return messages
|
||||||
|
.filter(msg => msg.role !== 'system') // Gemini doesn't have system messages
|
||||||
|
.map(msg => ({
|
||||||
|
role: msg.role === 'assistant' ? 'model' : 'user',
|
||||||
|
parts: [{ text: msg.content }]
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert Gemini response to OpenAI format
|
||||||
|
function convertToOpenAIResponse(geminiResponse: any, model: string, requestId: string): OpenAIChatResponse {
|
||||||
|
const content = geminiResponse.response?.candidates?.[0]?.content?.parts?.[0]?.text || '';
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `chatcmpl-${requestId}`,
|
||||||
|
object: 'chat.completion',
|
||||||
|
created: Math.floor(Date.now() / 1000),
|
||||||
|
model: model,
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
index: 0,
|
||||||
|
message: {
|
||||||
|
role: 'assistant',
|
||||||
|
content: content
|
||||||
|
},
|
||||||
|
finish_reason: 'stop'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
usage: {
|
||||||
|
prompt_tokens: geminiResponse.response?.usageMetadata?.promptTokenCount || 0,
|
||||||
|
completion_tokens: geminiResponse.response?.usageMetadata?.candidatesTokenCount || 0,
|
||||||
|
total_tokens: geminiResponse.response?.usageMetadata?.totalTokenCount || 0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /v1/chat/completions
|
||||||
|
router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body: OpenAIChatRequest = req.body;
|
||||||
|
|
||||||
|
// Log the request
|
||||||
|
requestLogger.logRequest(requestId, {
|
||||||
|
path: req.path,
|
||||||
|
method: req.method,
|
||||||
|
body: body
|
||||||
|
});
|
||||||
|
|
||||||
|
// Validate request
|
||||||
|
if (!body.messages || !Array.isArray(body.messages)) {
|
||||||
|
throw new Error('Invalid or missing messages array');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get Gemini client with rotated key
|
||||||
|
const genAI = keyRotationManager.createGenerativeAI();
|
||||||
|
const model = genAI.getGenerativeModel({ model: config.model });
|
||||||
|
|
||||||
|
// Convert messages
|
||||||
|
const geminiMessages = convertToGeminiMessages(body.messages);
|
||||||
|
|
||||||
|
// Start chat
|
||||||
|
const chat = model.startChat({
|
||||||
|
history: geminiMessages.slice(0, -1),
|
||||||
|
generationConfig: {
|
||||||
|
temperature: body.temperature || 0.7,
|
||||||
|
maxOutputTokens: body.max_tokens || 1024,
|
||||||
|
topP: body.top_p || 0.8
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get the last user message
|
||||||
|
const lastMessage = geminiMessages[geminiMessages.length - 1];
|
||||||
|
if (!lastMessage || lastMessage.role !== 'user') {
|
||||||
|
throw new Error('Last message must be from user');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate response
|
||||||
|
const result = await chat.sendMessage(lastMessage.parts[0].text);
|
||||||
|
const response = await result.response;
|
||||||
|
|
||||||
|
// Convert to OpenAI format
|
||||||
|
const openaiResponse = convertToOpenAIResponse({ response }, body.model, requestId);
|
||||||
|
|
||||||
|
// Log the response
|
||||||
|
requestLogger.logResponse(requestId, {
|
||||||
|
statusCode: 200,
|
||||||
|
response: openaiResponse
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json(openaiResponse);
|
||||||
|
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Error in chat completion:', error);
|
||||||
|
|
||||||
|
// Log the error
|
||||||
|
requestLogger.logError(requestId, {
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check if it's a rate limit error
|
||||||
|
if (error.message?.includes('RATE_LIMIT_EXCEEDED') || error.status === 429) {
|
||||||
|
res.status(429).json({
|
||||||
|
error: {
|
||||||
|
message: 'Rate limit exceeded. Please try again later.',
|
||||||
|
type: 'rate_limit_error',
|
||||||
|
code: 'rate_limit_exceeded'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res.status(500).json({
|
||||||
|
error: {
|
||||||
|
message: error.message || 'Internal server error',
|
||||||
|
type: 'server_error',
|
||||||
|
code: 'internal_error'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /v1/models
|
||||||
|
router.get('/v1/models', (req: Request, res: Response) => {
|
||||||
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
|
||||||
|
requestLogger.logRequest(requestId, {
|
||||||
|
path: req.path,
|
||||||
|
method: req.method
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelsResponse: OpenAIModelsResponse = {
|
||||||
|
object: 'list',
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
id: config.model,
|
||||||
|
object: 'model',
|
||||||
|
created: Math.floor(Date.now() / 1000),
|
||||||
|
owned_by: 'google'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
requestLogger.logResponse(requestId, {
|
||||||
|
statusCode: 200,
|
||||||
|
response: modelsResponse
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json(modelsResponse);
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /health
|
||||||
|
router.get('/health', (req: Request, res: Response) => {
|
||||||
|
const keyStats = keyRotationManager.getKeyStats();
|
||||||
|
res.json({
|
||||||
|
status: 'healthy',
|
||||||
|
keys: keyStats.map(k => ({
|
||||||
|
lastUsed: new Date(k.lastUsed).toISOString(),
|
||||||
|
requestCount: k.requestCount,
|
||||||
|
rateLimited: k.rateLimitedUntil ? true : false
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
50
test-api.sh
Executable file
50
test-api.sh
Executable file
|
|
@ -0,0 +1,50 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Test script for GeiminiRevolver API
|
||||||
|
|
||||||
|
echo "Testing GeiminiRevolver API..."
|
||||||
|
|
||||||
|
# Check if server is running
|
||||||
|
echo "1. Checking if server is running on port 3000..."
|
||||||
|
if curl -s http://localhost:3000/health > /dev/null; then
|
||||||
|
echo "✓ Server is running"
|
||||||
|
else
|
||||||
|
echo "✗ Server is not running. Start it with: npm run dev"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Test health endpoint
|
||||||
|
echo "2. Testing health endpoint..."
|
||||||
|
curl -s http://localhost:3000/health | jq '.'
|
||||||
|
|
||||||
|
# Test models endpoint (should fail without auth)
|
||||||
|
echo "3. Testing models endpoint without authentication (should fail)..."
|
||||||
|
curl -s http://localhost:3000/v1/models | jq '.'
|
||||||
|
|
||||||
|
# Test models endpoint with authentication
|
||||||
|
echo "4. Testing models endpoint with authentication..."
|
||||||
|
API_PASSWORD="change_this_secure_password"
|
||||||
|
curl -s http://localhost:3000/v1/models \
|
||||||
|
-H "Authorization: Bearer $API_PASSWORD" | jq '.'
|
||||||
|
|
||||||
|
# Test chat completions endpoint
|
||||||
|
echo "5. Testing chat completions endpoint..."
|
||||||
|
curl -s http://localhost:3000/v1/chat/completions \
|
||||||
|
-H "Authorization: Bearer $API_PASSWORD" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"model": "gemini-flash-lite-latest",
|
||||||
|
"messages": [
|
||||||
|
{"role": "user", "content": "Say hello in one word."}
|
||||||
|
]
|
||||||
|
}' | jq '.'
|
||||||
|
|
||||||
|
echo "6. Checking log files..."
|
||||||
|
if [ -d "./logs" ]; then
|
||||||
|
echo "✓ Log directory exists"
|
||||||
|
ls -la ./logs/
|
||||||
|
else
|
||||||
|
echo "✗ Log directory not found"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Test completed!"
|
||||||
18
tsconfig.json
Normal file
18
tsconfig.json
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"module": "commonjs",
|
||||||
|
"lib": ["ES2020"],
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"ignoreDeprecations": "6.0"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist"]
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue