bahi-bh commited on
Commit
6e1e854
·
verified ·
1 Parent(s): 869a377

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -98
app.py CHANGED
@@ -3,31 +3,32 @@ from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import StreamingResponse, JSONResponse
4
  from pydantic import BaseModel
5
  from typing import List
6
- import g4f
7
- import g4f.models
8
  import json
9
- import uuid
10
  import time
11
- import asyncio
12
 
13
- # =====================================================
 
 
 
14
  # CONFIG
15
- # =====================================================
16
 
17
  API_KEY = "sk-your-secret-key"
18
 
19
- # =====================================================
20
- # FASTAPI
21
- # =====================================================
22
 
23
  app = FastAPI(
24
- title="Universal AI Gateway",
25
- version="2.0.0"
26
  )
27
 
28
- # =====================================================
29
  # CORS
30
- # =====================================================
31
 
32
  app.add_middleware(
33
  CORSMiddleware,
@@ -37,9 +38,20 @@ app.add_middleware(
37
  allow_headers=["*"],
38
  )
39
 
40
- # =====================================================
 
 
 
 
 
 
 
 
 
 
 
41
  # MODELS
42
- # =====================================================
43
 
44
  class Message(BaseModel):
45
  role: str
@@ -52,9 +64,9 @@ class ChatRequest(BaseModel):
52
  temperature: float = 0.7
53
  max_tokens: int = 4096
54
 
55
- # =====================================================
56
  # AUTH
57
- # =====================================================
58
 
59
  def verify_api_key(req: Request):
60
 
@@ -80,21 +92,21 @@ def verify_api_key(req: Request):
80
  detail="Invalid API Key"
81
  )
82
 
83
- # =====================================================
84
  # ROOT
85
- # =====================================================
86
 
87
  @app.get("/")
88
  async def root():
89
 
90
  return {
91
  "status": "online",
92
- "service": "Universal AI Gateway"
93
  }
94
 
95
- # =====================================================
96
- # MODELS ENDPOINT
97
- # =====================================================
98
 
99
  @app.get("/v1/models")
100
  async def models():
@@ -138,9 +150,115 @@ async def models():
138
  "data": data
139
  }
140
 
141
- # =====================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  # CHAT COMPLETIONS
143
- # =====================================================
144
 
145
  @app.post("/v1/chat/completions")
146
  async def chat_completions(
@@ -158,89 +276,29 @@ async def chat_completions(
158
  for m in body.messages
159
  ]
160
 
161
- # =================================================
162
- # STREAMING
163
- # =================================================
164
 
165
  if body.stream:
166
 
167
- async def generate_stream():
168
-
169
- try:
170
-
171
- response = g4f.ChatCompletion.create(
172
- model=body.model,
173
- messages=messages,
174
- stream=True
175
- )
176
-
177
- for chunk in response:
178
-
179
- if chunk:
180
-
181
- payload = {
182
- "id": f"chatcmpl-{uuid.uuid4().hex}",
183
- "object": "chat.completion.chunk",
184
- "created": int(time.time()),
185
- "model": body.model,
186
- "choices": [
187
- {
188
- "index": 0,
189
- "delta": {
190
- "content": chunk
191
- },
192
- "finish_reason": None
193
- }
194
- ]
195
- }
196
-
197
- yield f"data: {json.dumps(payload)}\n\n"
198
-
199
- await asyncio.sleep(0)
200
-
201
- done_payload = {
202
- "id": f"chatcmpl-{uuid.uuid4().hex}",
203
- "object": "chat.completion.chunk",
204
- "created": int(time.time()),
205
- "model": body.model,
206
- "choices": [
207
- {
208
- "index": 0,
209
- "delta": {},
210
- "finish_reason": "stop"
211
- }
212
- ]
213
- }
214
-
215
- yield f"data: {json.dumps(done_payload)}\n\n"
216
-
217
- yield "data: [DONE]\n\n"
218
-
219
- except Exception as e:
220
-
221
- error_payload = {
222
- "error": {
223
- "message": str(e),
224
- "type": "server_error"
225
- }
226
- }
227
-
228
- yield f"data: {json.dumps(error_payload)}\n\n"
229
-
230
  return StreamingResponse(
231
- generate_stream(),
 
 
 
232
  media_type="text/event-stream"
233
  )
234
 
235
- # =================================================
236
- # NORMAL RESPONSE
237
- # =================================================
238
 
239
  try:
240
 
241
- response = g4f.ChatCompletion.create(
242
- model=body.model,
243
- messages=messages
244
  )
245
 
246
  return JSONResponse({
 
3
  from fastapi.responses import StreamingResponse, JSONResponse
4
  from pydantic import BaseModel
5
  from typing import List
6
+ import asyncio
 
7
  import json
 
8
  import time
9
+ import uuid
10
 
11
+ import g4f
12
+ import g4f.models
13
+
14
+ # =========================================================
15
  # CONFIG
16
+ # =========================================================
17
 
18
  API_KEY = "sk-your-secret-key"
19
 
20
+ # =========================================================
21
+ # APP
22
+ # =========================================================
23
 
24
  app = FastAPI(
25
+ title="DuckAI Gateway",
26
+ version="3.0.0"
27
  )
28
 
29
+ # =========================================================
30
  # CORS
31
+ # =========================================================
32
 
33
  app.add_middleware(
34
  CORSMiddleware,
 
38
  allow_headers=["*"],
39
  )
40
 
41
+ # =========================================================
42
+ # PROVIDERS
43
+ # =========================================================
44
+
45
+ PROVIDERS = [
46
+ g4f.Provider.DuckDuckGo,
47
+ g4f.Provider.Blackbox,
48
+ g4f.Provider.Free2GPT,
49
+ g4f.Provider.Bing
50
+ ]
51
+
52
+ # =========================================================
53
  # MODELS
54
+ # =========================================================
55
 
56
  class Message(BaseModel):
57
  role: str
 
64
  temperature: float = 0.7
65
  max_tokens: int = 4096
66
 
67
+ # =========================================================
68
  # AUTH
69
+ # =========================================================
70
 
71
  def verify_api_key(req: Request):
72
 
 
92
  detail="Invalid API Key"
93
  )
94
 
95
+ # =========================================================
96
  # ROOT
97
+ # =========================================================
98
 
99
  @app.get("/")
100
  async def root():
101
 
102
  return {
103
  "status": "online",
104
+ "service": "DuckAI Gateway"
105
  }
106
 
107
+ # =========================================================
108
+ # MODELS
109
+ # =========================================================
110
 
111
  @app.get("/v1/models")
112
  async def models():
 
150
  "data": data
151
  }
152
 
153
+ # =========================================================
154
+ # NORMAL RESPONSE
155
+ # =========================================================
156
+
157
+ def generate_response(model, messages):
158
+
159
+ last_error = None
160
+
161
+ for provider in PROVIDERS:
162
+
163
+ try:
164
+
165
+ response = g4f.ChatCompletion.create(
166
+ model=model,
167
+ provider=provider,
168
+ messages=messages
169
+ )
170
+
171
+ return response
172
+
173
+ except Exception as e:
174
+
175
+ last_error = str(e)
176
+
177
+ continue
178
+
179
+ raise Exception(last_error or "All providers failed")
180
+
181
+ # =========================================================
182
+ # STREAM RESPONSE
183
+ # =========================================================
184
+
185
+ async def generate_stream(model, messages):
186
+
187
+ last_error = None
188
+
189
+ for provider in PROVIDERS:
190
+
191
+ try:
192
+
193
+ response = g4f.ChatCompletion.create(
194
+ model=model,
195
+ provider=provider,
196
+ messages=messages,
197
+ stream=True
198
+ )
199
+
200
+ for chunk in response:
201
+
202
+ if chunk:
203
+
204
+ payload = {
205
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
206
+ "object": "chat.completion.chunk",
207
+ "created": int(time.time()),
208
+ "model": model,
209
+ "choices": [
210
+ {
211
+ "index": 0,
212
+ "delta": {
213
+ "content": chunk
214
+ },
215
+ "finish_reason": None
216
+ }
217
+ ]
218
+ }
219
+
220
+ yield f"data: {json.dumps(payload)}\n\n"
221
+
222
+ await asyncio.sleep(0)
223
+
224
+ done_payload = {
225
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
226
+ "object": "chat.completion.chunk",
227
+ "created": int(time.time()),
228
+ "model": model,
229
+ "choices": [
230
+ {
231
+ "index": 0,
232
+ "delta": {},
233
+ "finish_reason": "stop"
234
+ }
235
+ ]
236
+ }
237
+
238
+ yield f"data: {json.dumps(done_payload)}\n\n"
239
+
240
+ yield "data: [DONE]\n\n"
241
+
242
+ return
243
+
244
+ except Exception as e:
245
+
246
+ last_error = str(e)
247
+
248
+ continue
249
+
250
+ error_payload = {
251
+ "error": {
252
+ "message": last_error or "All providers failed",
253
+ "type": "server_error"
254
+ }
255
+ }
256
+
257
+ yield f"data: {json.dumps(error_payload)}\n\n"
258
+
259
+ # =========================================================
260
  # CHAT COMPLETIONS
261
+ # =========================================================
262
 
263
  @app.post("/v1/chat/completions")
264
  async def chat_completions(
 
276
  for m in body.messages
277
  ]
278
 
279
+ # =====================================================
280
+ # STREAM
281
+ # =====================================================
282
 
283
  if body.stream:
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  return StreamingResponse(
286
+ generate_stream(
287
+ body.model,
288
+ messages
289
+ ),
290
  media_type="text/event-stream"
291
  )
292
 
293
+ # =====================================================
294
+ # NORMAL
295
+ # =====================================================
296
 
297
  try:
298
 
299
+ response = generate_response(
300
+ body.model,
301
+ messages
302
  )
303
 
304
  return JSONResponse({