Yay!
This commit is contained in:
commit
237d0c65ba
18 changed files with 1174 additions and 0 deletions
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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue