File size: 8,258 Bytes
bb4d1c9
ed1e830
 
 
17aa345
ac3850e
0f4cc05
ab33dd3
ed1e830
 
 
 
 
ab33dd3
ac3850e
 
 
 
 
 
 
 
94f8ccb
ab33dd3
ac3850e
 
 
 
 
 
 
ab33dd3
ed1e830
 
 
ac3850e
ed1e830
 
 
d9707fb
94f8ccb
ed1e830
ac3850e
ed1e830
 
ac3850e
 
ed1e830
0f4cc05
94f8ccb
 
ed1e830
 
 
ac3850e
0f4cc05
94f8ccb
 
ac3850e
 
ed1e830
 
ac3850e
d9707fb
ac3850e
ab33dd3
ac3850e
ed1e830
 
ac3850e
ed1e830
ab33dd3
ac3850e
ab33dd3
ac3850e
 
 
 
 
f535544
ac3850e
 
 
 
 
f535544
ac3850e
 
 
 
 
f535544
 
ac3850e
0f4cc05
ac3850e
0f4cc05
ac3850e
f535544
ac3850e
f535544
ac3850e
f535544
ac3850e
 
 
 
 
0f4cc05
ac3850e
f535544
ac3850e
 
 
 
 
f535544
ac3850e
f535544
ac3850e
 
 
 
 
f535544
ac3850e
f535544
ac3850e
 
 
 
 
f535544
ac3850e
f535544
ac3850e
 
 
 
f535544
 
ac3850e
f535544
ac3850e
 
 
 
0f4cc05
ab33dd3
ac3850e
 
17aa345
ac3850e
ab33dd3
17aa345
ac3850e
17aa345
ac3850e
 
17aa345
ac3850e
 
 
ab33dd3
 
ac3850e
ab33dd3
ac3850e
 
 
 
17aa345
ac3850e
 
 
 
 
 
 
 
 
 
 
 
ab33dd3
ac3850e
 
0f4cc05
ab33dd3
ac3850e
 
 
17aa345
ac3850e
17aa345
ac3850e
ed1e830
ac3850e
 
 
 
 
 
f535544
ac3850e
ed1e830
ac3850e
17aa345
ac3850e
17aa345
ac3850e
17aa345
ac3850e
 
 
 
 
17aa345
ac3850e
17aa345
ac3850e
 
17aa345
ac3850e
17aa345
ac3850e
17aa345
ac3850e
17aa345
ac3850e
17aa345
ac3850e
17aa345
ac3850e
 
 
 
17aa345
ac3850e
 
f535544
ed1e830
ac3850e
94f8ccb
ac3850e
 
 
 
0f4cc05
94f8ccb
ac3850e
0f4cc05
 
f535544
ac3850e
f535544
ac3850e
f535544
0f4cc05
ac3850e
 
0f4cc05
f535544
ac3850e
0f4cc05
ab33dd3
87051a4
ac3850e
ab33dd3
ac3850e
17aa345
ac3850e
 
 
 
 
17aa345
ac3850e
17aa345
ac3850e
 
 
ed1e830
 
ac3850e
 
 
94f8ccb
 
ac3850e
94f8ccb
ac3850e
94f8ccb
ac3850e
ed1e830
ac3850e
ed1e830
ac3850e
0f4cc05
ac3850e
 
 
 
0f4cc05
ac3850e
0f4cc05
ac3850e
0f4cc05
ac3850e
ed1e830
ac3850e
f535544
ac3850e
 
f535544
ac3850e
 
f535544
ac3850e
 
f535544
ac3850e
 
 
 
 
 
 
 
 
 
ab33dd3
ac3850e
 
 
0f4cc05
ac3850e
ab33dd3
ac3850e
ab33dd3
ac3850e
ab33dd3
ac3850e
 
 
ab33dd3
94f8ccb
ac3850e
 
 
 
87051a4
f535544
ac3850e
87051a4
ac3850e
f535544
ac3850e
ab33dd3
ac3850e
 
 
ed1e830
ac3850e
0f4cc05
ed1e830
ac3850e
ed1e830
ac3850e
94f8ccb
ac3850e
94f8ccb
ac3850e
 
94f8ccb
ac3850e
 
94f8ccb
ac3850e
94f8ccb
ac3850e
ab33dd3
ac3850e
ab33dd3
ac3850e
ab33dd3
ac3850e
 
f535544
ac3850e
 
f535544
ac3850e
f535544
ac3850e
 
f535544
ac3850e
f535544
ac3850e
 
f535544
ac3850e
f535544
ac3850e
f535544
ac3850e
 
 
0f4cc05
f535544
 
ac3850e
f535544
ac3850e
 
 
 
f535544
ac3850e
17aa345
ac3850e
 
 
17aa345
ac3850e
17aa345
ac3850e
f535544
ac3850e
f535544
ac3850e
17aa345
ac3850e
17aa345
ac3850e
 
 
0f4cc05
17aa345
ac3850e
 
 
 
 
 
 
 
17aa345
0f4cc05
17aa345
0f4cc05
f535544
ac3850e
0f4cc05
ac3850e
 
 
 
 
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
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

import os
import json
import time
import logging
import asyncio
import g4f

from fastapi import FastAPI, HTTPException, Header
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional


# ================= Logging =================

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

logger=logging.getLogger(__name__)


# ================= App =================

app=FastAPI(
    title="G4F Smart Gateway",
    version="2.0"
)

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

API_KEY=os.getenv(
    "API_KEY",
    "your_fallback_secret"
)


# ================= Models =================

class ChatMessage(BaseModel):
    role:str
    content:str


class ChatRequest(BaseModel):
    model:str="gpt-4o-mini"
    messages:List[ChatMessage]
    stream:bool=False
    provider:Optional[str]=None
    temperature:Optional[float]=0.7
    max_tokens:Optional[int]=2048


# ================= Auth =================

def verify_key(auth:str):

    if not auth:
        raise HTTPException(
            status_code=401,
            detail="Missing Authorization"
        )

    parts=auth.split()

    if len(parts)!=2:
        raise HTTPException(
            status_code=401,
            detail="Malformed Authorization"
        )

    if parts[0]!="Bearer":
        raise HTTPException(
            status_code=401,
            detail="Invalid Authorization"
        )

    if parts[1]!=API_KEY:
        raise HTTPException(
            status_code=401,
            detail="Invalid API Key"
        )


# ================= Provider Selection =================

def choose_provider(model:str):

    model=model.lower()

    try:

        if "qwen" in model:

            return getattr(
                g4f.Provider,
                "DeepInfra",
                None
            )

        elif "perplexity" in model:

            return getattr(
                g4f.Provider,
                "PerplexityLabs",
                None
            )

        elif "llama" in model:

            return getattr(
                g4f.Provider,
                "DeepInfra",
                None
            )

        elif "claude" in model:

            return getattr(
                g4f.Provider,
                "OpenaiChat",
                None
            )

        elif "gemini" in model:

            return getattr(
                g4f.Provider,
                "OpenaiChat",
                None
            )

        elif "gpt" in model:

            return getattr(
                g4f.Provider,
                "OpenaiChat",
                None
            )

    except:
        pass

    return None


# ================= Health =================

@app.get("/")
async def root():

    return {
        "status":"online"
    }


# ================= Models =================

@app.get("/v1/models")
async def models(
    authorization:str=Header(None)
):

    verify_key(
        authorization
    )

    try:

        found=[]

        if hasattr(
            g4f.models,
            "ModelUtils"
        ):

            found=list(
                g4f.models.ModelUtils.convert.keys()
            )

        found=sorted(
            list(set(found))
        )

        if not found:

            found=[

                "gpt-4o-mini",
                "gpt-4",
                "gpt-3.5-turbo",
                "qwen-2.5-72b",
                "llama-3-70b",
                "perplexity"

            ]

        return {

            "object":"list",

            "data":[

                {
                    "id":m,
                    "object":"model",
                    "owned_by":"g4f"
                }

                for m in found

            ]
        }

    except Exception as e:

        logger.exception(e)

        return {

            "object":"list",

            "data":[

                {
                    "id":"gpt-4o-mini",
                    "object":"model"
                }

            ]
        }


# ================= Chat =================

@app.post("/v1/chat/completions")
async def chat(
    body:ChatRequest,
    authorization:str=Header(None)
):

    verify_key(
        authorization
    )

    try:

        messages=[

            {
                "role":m.role,
                "content":m.content
            }

            for m in body.messages
        ]


        provider=None

        if body.provider:

            provider=getattr(
                g4f.Provider,
                body.provider,
                None
            )

        else:

            provider=choose_provider(
                body.model
            )


        logger.info(
            f"Model={body.model} Provider={provider}"
        )


        # ========= STREAM =========

        if body.stream:

            def generate():

                try:

                    response=g4f.ChatCompletion.create(

                        model=body.model,
                        messages=messages,
                        provider=provider,
                        stream=True

                    )

                    for chunk in response:

                        payload={

                            "id":"chatcmpl",

                            "object":
                            "chat.completion.chunk",

                            "created":
                            int(time.time()),

                            "model":
                            body.model,

                            "choices":[
                                {
                                    "delta":{
                                        "content":
                                        str(chunk)
                                    },
                                    "index":0
                                }
                            ]
                        }

                        yield (
                            f"data: {json.dumps(payload)}\n\n"
                        )

                    yield "data: [DONE]\n\n"

                except Exception as e:

                    logger.exception(e)

                    yield (
                        f"data:{json.dumps({'error':str(e)})}\n\n"
                    )


            return StreamingResponse(
                generate(),
                media_type="text/event-stream"
            )


        # ========= NORMAL =========

        response=await asyncio.to_thread(

            g4f.ChatCompletion.create,

            model=body.model,
            messages=messages,
            provider=provider

        )


        return {

            "id":"chatcmpl",

            "object":"chat.completion",

            "created":
            int(time.time()),

            "model":
            body.model,

            "choices":[

                {

                    "index":0,

                    "message":{

                        "role":
                        "assistant",

                        "content":
                        str(response)

                    },

                    "finish_reason":
                    "stop"

                }

            ]
        }

    except Exception as e:

        logger.exception(e)

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


# ================= Test =================

@app.get("/test/{model}")
async def test_model(
    model:str
):

    try:

        provider=choose_provider(
            model
        )

        result=await asyncio.to_thread(

            g4f.ChatCompletion.create,

            model=model,

            provider=provider,

            messages=[

                {
                    "role":"user",
                    "content":"hello"
                }

            ]
        )

        return {

            "model":model,
            "provider":str(provider),
            "working":True

        }

    except Exception as e:

        return {

            "model":model,
            "working":False,
            "error":str(e)

        }