bahi-bh commited on
Commit
3311f77
·
verified ·
1 Parent(s): 4cb6ebd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -77
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, Request
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import StreamingResponse, JSONResponse
4
  from pydantic import BaseModel
@@ -11,7 +11,6 @@ import time
11
  import logging
12
 
13
  import g4f
14
- import g4f.models
15
  from g4f.client import Client
16
 
17
  # =====================================================
@@ -19,15 +18,16 @@ from g4f.client import Client
19
  # =====================================================
20
 
21
  logging.basicConfig(level=logging.INFO)
 
22
  logger = logging.getLogger(__name__)
23
 
24
  # =====================================================
25
- # FASTAPI
26
  # =====================================================
27
 
28
  app = FastAPI(
29
- title="Universal AI Gateway",
30
- version="5.0.0"
31
  )
32
 
33
  # =====================================================
@@ -57,6 +57,12 @@ class ChatRequest(BaseModel):
57
  temperature: Optional[float] = 0.7
58
  max_tokens: Optional[int] = 4096
59
 
 
 
 
 
 
 
60
  # =====================================================
61
  # ROOT
62
  # =====================================================
@@ -66,63 +72,45 @@ async def root():
66
 
67
  return {
68
  "status": "online",
69
- "service": "Universal AI Gateway",
70
- "version": "5.0.0"
71
  }
72
 
73
  # =====================================================
74
- # AUTO MODELS IMPORT
75
  # =====================================================
76
 
77
  @app.get("/v1/models")
78
- async def get_models():
79
 
80
- models_data = []
81
 
82
  try:
83
 
84
- all_models = []
85
-
86
- if hasattr(g4f.models, "_all_models"):
87
- all_models = list(g4f.models._all_models)
88
-
89
- unique_models = set()
90
 
91
  for model in all_models:
92
 
93
- model_name = str(model)
94
-
95
- if model_name not in unique_models:
96
-
97
- unique_models.add(model_name)
98
-
99
- models_data.append({
100
- "id": model_name,
101
- "object": "model",
102
- "created": int(time.time()),
103
- "owned_by": "g4f"
104
- })
105
-
106
- except Exception as e:
107
-
108
- logger.error(f"Models error: {e}")
109
 
110
- # fallback
111
- if not models_data:
112
 
113
  fallback = [
114
  "gpt-4o-mini",
115
  "gpt-4o",
116
  "gpt-4",
117
  "claude-3-haiku",
118
- "gemini-pro",
119
- "llama-3.1-70b"
120
  ]
121
 
122
- for m in fallback:
123
 
124
- models_data.append({
125
- "id": m,
126
  "object": "model",
127
  "created": int(time.time()),
128
  "owned_by": "g4f"
@@ -130,17 +118,15 @@ async def get_models():
130
 
131
  return {
132
  "object": "list",
133
- "data": models_data
134
  }
135
 
136
  # =====================================================
137
- # CHAT COMPLETIONS
138
  # =====================================================
139
 
140
  @app.post("/v1/chat/completions")
141
- async def chat_completions(
142
- body: ChatRequest
143
- ):
144
 
145
  messages = [
146
  {
@@ -150,24 +136,24 @@ async def chat_completions(
150
  for m in body.messages
151
  ]
152
 
153
- logger.info(f"Model: {body.model}")
154
-
155
  # =================================================
156
  # STREAM
157
  # =================================================
158
 
159
  if body.stream:
160
 
161
- async def generate_stream():
162
 
163
  try:
164
 
165
- client = Client()
166
-
167
- response = client.chat.completions.create(
168
- model=body.model,
169
- messages=messages,
170
- stream=True
 
 
171
  )
172
 
173
  chunk_id = f"chatcmpl-{uuid.uuid4().hex}"
@@ -225,51 +211,51 @@ async def chat_completions(
225
  }
226
 
227
  yield f"data: {json.dumps(done_payload)}\n\n"
 
228
  yield "data: [DONE]\n\n"
229
 
230
  except Exception as e:
231
 
232
  logger.error(e)
233
 
234
- error_payload = {
235
  "error": {
236
- "message": str(e),
237
- "type": "server_error"
238
  }
239
  }
240
 
241
- yield f"data: {json.dumps(error_payload)}\n\n"
242
 
243
  return StreamingResponse(
244
- generate_stream(),
245
  media_type="text/event-stream",
246
  headers={
247
  "Cache-Control": "no-cache",
248
- "Connection": "keep-alive",
249
- "X-Accel-Buffering": "no"
250
  }
251
  )
252
 
253
  # =================================================
254
- # NORMAL RESPONSE
255
  # =================================================
256
 
257
  try:
258
 
259
- client = Client()
260
-
261
- response = await asyncio.to_thread(
262
- client.chat.completions.create,
263
- model=body.model,
264
- messages=messages
 
265
  )
266
 
267
- assistant_message = ""
268
 
269
  try:
270
- assistant_message = response.choices[0].message.content
271
  except:
272
- assistant_message = str(response)
273
 
274
  return JSONResponse({
275
  "id": f"chatcmpl-{uuid.uuid4().hex}",
@@ -281,16 +267,11 @@ async def chat_completions(
281
  "index": 0,
282
  "message": {
283
  "role": "assistant",
284
- "content": assistant_message
285
  },
286
  "finish_reason": "stop"
287
  }
288
- ],
289
- "usage": {
290
- "prompt_tokens": 0,
291
- "completion_tokens": 0,
292
- "total_tokens": 0
293
- }
294
  })
295
 
296
  except Exception as e:
 
1
+ from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import StreamingResponse, JSONResponse
4
  from pydantic import BaseModel
 
11
  import logging
12
 
13
  import g4f
 
14
  from g4f.client import Client
15
 
16
  # =====================================================
 
18
  # =====================================================
19
 
20
  logging.basicConfig(level=logging.INFO)
21
+
22
  logger = logging.getLogger(__name__)
23
 
24
  # =====================================================
25
+ # APP
26
  # =====================================================
27
 
28
  app = FastAPI(
29
+ title="DuckAI Gateway",
30
+ version="6.0.0"
31
  )
32
 
33
  # =====================================================
 
57
  temperature: Optional[float] = 0.7
58
  max_tokens: Optional[int] = 4096
59
 
60
+ # =====================================================
61
+ # CLIENT
62
+ # =====================================================
63
+
64
+ client = Client()
65
+
66
  # =====================================================
67
  # ROOT
68
  # =====================================================
 
72
 
73
  return {
74
  "status": "online",
75
+ "service": "DuckAI Gateway"
 
76
  }
77
 
78
  # =====================================================
79
+ # MODELS
80
  # =====================================================
81
 
82
  @app.get("/v1/models")
83
+ async def models():
84
 
85
+ output = []
86
 
87
  try:
88
 
89
+ all_models = list(g4f.models._all_models)
 
 
 
 
 
90
 
91
  for model in all_models:
92
 
93
+ output.append({
94
+ "id": str(model),
95
+ "object": "model",
96
+ "created": int(time.time()),
97
+ "owned_by": "g4f"
98
+ })
 
 
 
 
 
 
 
 
 
 
99
 
100
+ except Exception:
 
101
 
102
  fallback = [
103
  "gpt-4o-mini",
104
  "gpt-4o",
105
  "gpt-4",
106
  "claude-3-haiku",
107
+ "gemini-pro"
 
108
  ]
109
 
110
+ for model in fallback:
111
 
112
+ output.append({
113
+ "id": model,
114
  "object": "model",
115
  "created": int(time.time()),
116
  "owned_by": "g4f"
 
118
 
119
  return {
120
  "object": "list",
121
+ "data": output
122
  }
123
 
124
  # =====================================================
125
+ # CHAT
126
  # =====================================================
127
 
128
  @app.post("/v1/chat/completions")
129
+ async def chat(body: ChatRequest):
 
 
130
 
131
  messages = [
132
  {
 
136
  for m in body.messages
137
  ]
138
 
 
 
139
  # =================================================
140
  # STREAM
141
  # =================================================
142
 
143
  if body.stream:
144
 
145
+ async def event_stream():
146
 
147
  try:
148
 
149
+ response = await asyncio.wait_for(
150
+ asyncio.to_thread(
151
+ client.chat.completions.create,
152
+ model=body.model,
153
+ messages=messages,
154
+ stream=True
155
+ ),
156
+ timeout=60
157
  )
158
 
159
  chunk_id = f"chatcmpl-{uuid.uuid4().hex}"
 
211
  }
212
 
213
  yield f"data: {json.dumps(done_payload)}\n\n"
214
+
215
  yield "data: [DONE]\n\n"
216
 
217
  except Exception as e:
218
 
219
  logger.error(e)
220
 
221
+ payload = {
222
  "error": {
223
+ "message": str(e)
 
224
  }
225
  }
226
 
227
+ yield f"data: {json.dumps(payload)}\n\n"
228
 
229
  return StreamingResponse(
230
+ event_stream(),
231
  media_type="text/event-stream",
232
  headers={
233
  "Cache-Control": "no-cache",
234
+ "Connection": "keep-alive"
 
235
  }
236
  )
237
 
238
  # =================================================
239
+ # NORMAL
240
  # =================================================
241
 
242
  try:
243
 
244
+ response = await asyncio.wait_for(
245
+ asyncio.to_thread(
246
+ client.chat.completions.create,
247
+ model=body.model,
248
+ messages=messages
249
+ ),
250
+ timeout=60
251
  )
252
 
253
+ text = ""
254
 
255
  try:
256
+ text = response.choices[0].message.content
257
  except:
258
+ text = str(response)
259
 
260
  return JSONResponse({
261
  "id": f"chatcmpl-{uuid.uuid4().hex}",
 
267
  "index": 0,
268
  "message": {
269
  "role": "assistant",
270
+ "content": text
271
  },
272
  "finish_reason": "stop"
273
  }
274
+ ]
 
 
 
 
 
275
  })
276
 
277
  except Exception as e: