File size: 17,690 Bytes
935f280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
from fastapi import FastAPI, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import openai
from typing import List, Optional, Union
import logging
import httpx
import uuid
import time
import json
from datetime import datetime, timezone
import requests
import uvicorn
import random

logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

MAX_RETRIES = 3

class ChatRequest(BaseModel):
    messages: List[dict]
    model: str
    temperature: Optional[float] = 0.7
    stream: Optional[bool] = False
    tools: Optional[List[dict]] = []
    tool_choice: Optional[str] = "auto"

class EmbeddingRequest(BaseModel):
    input: Union[str, List[str]]
    model: str
    encoding_format: Optional[str] = "float"

async def verify_authorization(authorization: str = Header(None)):
    print("Authorization header:", authorization)  
    if not authorization:
        logger.error("Missing Authorization header")
        raise HTTPException(status_code=401, detail="Missing Authorization header")
    if not authorization.startswith("Bearer "):
        logger.error("Invalid Authorization header format")
        raise HTTPException(
            status_code=401, detail="Invalid Authorization header format"
        )
    token = authorization.replace("Bearer ", "")
    return token

def get_openai_models(api_keys):
    api_key = random.choice(api_keys)
    try:
        client = openai.OpenAI(api_key=api_key)
        models = client.models.list()
        return models.model_dump()
    except Exception as e:
        logger.error(f"Error getting models from OpenAI with key {api_key}: {e}")
        return {"error": str(e)}

def get_gemini_models(api_keys):
    api_key = random.choice(api_keys)
    base_url = "https://generativelanguage.googleapis.com/v1beta"
    url = f"{base_url}/models?key={api_key}"

    try:
        response = requests.get(url)
        if response.status_code == 200:
            gemini_models = response.json()
            return convert_to_openai_models_format(gemini_models)
        else:
            logger.error(f"Error getting models from Gemini with key {api_key}: {response.status_code} - {response.text}")
            return {"error": f"Gemini API error: {response.status_code} - {response.text}"}

    except requests.RequestException as e:
        logger.error(f"Request failed: {e}")
        return {"error": f"Request failed: {e}"}

def convert_to_openai_models_format(gemini_models):
    openai_format = {"object": "list", "data": []}

    for model in gemini_models.get("models", []):
        openai_model = {
            "id": model["name"].split("/")[-1],
            "object": "model",
            "created": int(datetime.now(timezone.utc).timestamp()),
            "owned_by": "google",
            "permission": [],
            "root": model["name"],
            "parent": None,
        }
        openai_format["data"].append(openai_model)

    return openai_format

def convert_messages_to_gemini_format(messages):
    gemini_messages = []
    for msg in messages:
        role = "user" if msg["role"] == "user" else "model"
        parts = []
        if isinstance(msg["content"], str):
            parts.append({"text": msg["content"]})
        elif isinstance(msg["content"], list):
            for content in msg["content"]:
                if isinstance(content, str):
                    parts.append({"text": content})
                elif isinstance(content, dict) and content["type"] == "text":
                    parts.append({"text": content["text"]})
                elif isinstance(content, dict) and content["type"] == "image_url":
                    image_url = content["image_url"]["url"]
                    if image_url.startswith("data:image"):
                        parts.append(
                            {
                                "inline_data": {
                                    "mime_type": "image/jpeg",
                                    "data": image_url.split(",")[1],
                                }
                            }
                        )
                    else:
                        parts.append(
                            {
                                "image_url": {
                                    "url": image_url,
                                }
                            }
                        )
        gemini_messages.append({"role": role, "parts": parts})
    return gemini_messages

async def convert_gemini_response_to_openai(response, model, stream=False):
    if stream:
        chunk = response
        if not chunk["candidates"]:
            return None

        return {
            "id": "chatcmpl-" + str(uuid.uuid4()),
            "object": "chat.completion.chunk",
            "created": int(time.time()),
            "model": model,
            "choices": [
                {
                    "index": 0,
                    "delta": {
                        "content": chunk["candidates"][0]["content"]["parts"][0]["text"]
                    },
                    "finish_reason": None,
                }
            ],
        }
    else:
        content = response["candidates"][0]["content"]["parts"][0]["text"]
        return {
            "id": "chatcmpl-" + str(uuid.uuid4()),
            "object": "chat.completion",
            "created": int(time.time()),
            "model": model,
            "choices": [
                {
                    "index": 0,
                    "message": {
                        "role": "assistant",
                        "content": content,
                    },
                    "finish_reason": "stop",
                }
            ],
            "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
        }

@app.get("/v1/models")
@app.get("/hf/v1/models")
async def list_models(authorization: str = Header(None)):
    token = await verify_authorization(authorization)
    api_keys = [key.strip() for key in token.split(',')]
    
    all_models = []
    error_messages = []
    
    for api_key in api_keys:
      if api_key.startswith("sk-"):
          response = get_openai_models([api_key])
      else:
          response = get_gemini_models([api_key])
      
      if "error" in response:
        error_messages.append(response["error"])
      else:
        if isinstance(response, dict) and 'data' in response:
          all_models.extend(response['data'])
        else:
          logger.warning(f"Unexpected response format from model list API for key {api_key}: {response}")
    
    if error_messages and not all_models:
      raise HTTPException(status_code=500, detail=f"Errors encountered: {', '.join(error_messages)}")
    
    return {"data": all_models, "object": "list"}

@app.post("/v1/chat/completions")
@app.post("/hf/v1/chat/completions")
async def chat_completion(request: ChatRequest, authorization: str = Header(None)):
    token = await verify_authorization(authorization)
    api_keys = [key.strip() for key in token.split(',')]
    logger.info(f"Chat completion request - Model: {request.model}")

    retries = 0

    while retries < MAX_RETRIES:
        api_key = random.choice(api_keys)
        try:
            logger.info(f"Attempt {retries + 1} with API key: {api_key}")

            if api_key.startswith("sk-"):
                client = openai.OpenAI(api_key=api_key)

                if request.stream:
                    logger.info("Streaming response enabled")
                    
                    async def generate():
                        try:
                            stream_response = client.chat.completions.create(
                                model=request.model,
                                messages=request.messages,
                                temperature=request.temperature,
                                stream=True,
                            )
                            
                            for chunk in stream_response:
                                chunk_json = chunk.model_dump_json()
                                yield f"data: {chunk_json}\n\n"
                            yield "data: [DONE]\n\n"
                        except Exception as e:
                            logger.error(f"Stream error: {str(e)}")
                            raise
                    
                    return StreamingResponse(content=generate(), media_type="text/event-stream")

                else:
                    response = client.chat.completions.create(
                        model=request.model,
                        messages=request.messages,
                        temperature=request.temperature,
                    )
                    logger.info("Chat completion successful")
                    return response.model_dump()
            else:
                gemini_messages = convert_messages_to_gemini_format(request.messages)
                payload = {
                    "contents": gemini_messages,
                    "generationConfig": {
                        "temperature": request.temperature,
                    }
                }

                if request.stream:
                    logger.info("Streaming response enabled")

                    async def generate():
                        nonlocal api_key, retries, api_keys

                        while retries < MAX_RETRIES:
                            try:
                                async with httpx.AsyncClient() as client:
                                    stream_url = f"https://generativelanguage.googleapis.com/v1beta/models/{request.model}:streamGenerateContent?alt=sse&key={api_key}"
                                    async with client.stream("POST", stream_url, json=payload, timeout=60.0) as response:
                                        if response.status_code == 429:
                                            logger.warning(f"Rate limit reached for key: {api_key}")
                                            retries += 1
                                            if retries >= MAX_RETRIES:
                                                yield f"data: {json.dumps({'error': 'Max retries reached'})}\n\n"
                                                break
                                            
                                            api_keys.remove(api_key)
                                            if not api_keys:
                                                yield f"data: {json.dumps({'error': 'All API keys exhausted'})}\n\n"
                                                break

                                            api_key = random.choice(api_keys)
                                            logger.info(f"Retrying with a new API key: {api_key}")
                                            continue

                                        if response.status_code != 200:
                                            logger.error(f"Error in streaming response with key {api_key}: {response.status_code} - {response.text}")
                                            
                                            retries += 1
                                            if retries >= MAX_RETRIES:
                                                yield f"data: {json.dumps({'error': 'Max retries reached'})}\n\n"
                                                break
                                            
                                            api_keys.remove(api_key)
                                            if not api_keys:
                                                yield f"data: {json.dumps({'error': 'All API keys exhausted'})}\n\n"
                                                break

                                            api_key = random.choice(api_keys)
                                            logger.info(f"Retrying with a new API key: {api_key}")
                                            continue

                                        async for line in response.aiter_lines():
                                            if line.startswith("data: "):
                                                try:
                                                    chunk = json.loads(line[6:])
                                                    if not chunk.get("candidates"):
                                                        continue

                                                    content = chunk["candidates"][0]["content"]["parts"][0]["text"]
                                                    
                                                    new_chunk = {
                                                        "id": "chatcmpl-" + str(uuid.uuid4()),
                                                        "object": "chat.completion.chunk",
                                                        "created": int(time.time()),
                                                        "model": request.model,
                                                        "choices": [
                                                            {
                                                                "index": 0,
                                                                "delta": {
                                                                    "content": content
                                                                },
                                                                "finish_reason": None,
                                                            }
                                                        ],
                                                    }
                                                    yield f"data: {json.dumps(new_chunk)}\n\n"

                                                except json.JSONDecodeError:
                                                    continue
                                        yield "data: [DONE]\n\n"
                                        return
                            except Exception as e:
                                logger.error(f"Stream error: {str(e)}")
                                retries += 1
                                if retries >= MAX_RETRIES:
                                    yield f"data: {json.dumps({'error': 'Max retries reached'})}\n\n"
                                    break
                                
                                api_keys.remove(api_key)
                                if not api_keys:
                                    yield f"data: {json.dumps({'error': 'All API keys exhausted'})}\n\n"
                                    break

                                api_key = random.choice(api_keys)
                                logger.info(f"Retrying with a new API key: {api_key}")
                                continue

                    return StreamingResponse(content=generate(), media_type="text/event-stream")
                else:
                    async with httpx.AsyncClient() as client:
                        non_stream_url = f"https://generativelanguage.googleapis.com/v1beta/models/{request.model}:generateContent?key={api_key}"
                        response = await client.post(non_stream_url, json=payload)
                        
                        if response.status_code != 200:
                            logger.error(f"Error in non-streaming response with key {api_key}: {response.status_code} - {response.text}")
                            
                            retries += 1
                            if retries >= MAX_RETRIES:
                                raise HTTPException(status_code=500, detail="Max retries reached")
                            
                            api_keys.remove(api_key)
                            if not api_keys:
                                raise HTTPException(status_code=500, detail="All API keys exhausted")

                            api_key = random.choice(api_keys)
                            logger.info(f"Retrying with a new API key: {api_key}")
                            continue

                        gemini_response = response.json()
                        logger.info("Chat completion successful")
                        return await convert_gemini_response_to_openai(gemini_response, request.model)

        except Exception as e:
            logger.error(f"Error in chat completion: {str(e)}")
            if isinstance(e, HTTPException):
                raise e
            
            retries += 1
            if retries >= MAX_RETRIES:
                logger.error("Max retries reached, giving up")
                raise HTTPException(status_code=500, detail="Max retries reached")
            
            api_keys.remove(api_key)
            if not api_keys:
              raise HTTPException(status_code=500, detail="All API keys exhausted")

            api_key = random.choice(api_keys)
            logger.info(f"Retrying with a new API key: {api_key}")
            continue

    raise HTTPException(status_code=500, detail="Unexpected error in chat completion")


@app.get("/health")
@app.get("/")
async def health_check():
    logger.info("Health check endpoint called")
    return {"status": "healthy"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8080)