bahi-bh commited on
Commit
678887c
·
verified ·
1 Parent(s): b64e85e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -49
app.py CHANGED
@@ -1,6 +1,6 @@
1
  from fastapi import FastAPI, Request, HTTPException
2
- from fastapi.responses import JSONResponse, StreamingResponse
3
  from fastapi.middleware.cors import CORSMiddleware
 
4
  from pydantic import BaseModel
5
  from typing import List
6
  import g4f
@@ -9,17 +9,24 @@ import uuid
9
  import time
10
  import asyncio
11
 
12
- # ======================================================
13
- # API KEY
14
- # ======================================================
15
 
16
- API_KEY = "sk-123456"
17
 
18
- # ======================================================
19
- # APP
20
- # ======================================================
21
 
22
- app = FastAPI()
 
 
 
 
 
 
 
23
 
24
  app.add_middleware(
25
  CORSMiddleware,
@@ -29,20 +36,21 @@ app.add_middleware(
29
  allow_headers=["*"],
30
  )
31
 
32
- # ======================================================
33
  # MODELS
34
- # ======================================================
35
 
36
  MODELS = [
37
  "gpt-4o-mini",
38
  "gpt-4",
39
  "claude-3-haiku",
40
  "llama-3.1-70b",
 
41
  ]
42
 
43
- # ======================================================
44
- # REQUEST
45
- # ======================================================
46
 
47
  class Message(BaseModel):
48
  role: str
@@ -52,29 +60,39 @@ class ChatRequest(BaseModel):
52
  model: str
53
  messages: List[Message]
54
  stream: bool = False
 
 
55
 
56
- # ======================================================
57
  # AUTH
58
- # ======================================================
59
 
60
  def verify_api_key(req: Request):
61
 
62
  auth = req.headers.get("Authorization")
63
 
64
  if not auth:
65
- raise HTTPException(401, "Missing API Key")
66
 
67
  if not auth.startswith("Bearer "):
68
- raise HTTPException(401, "Invalid Authorization")
 
 
 
69
 
70
  token = auth.replace("Bearer ", "")
71
 
72
  if token != API_KEY:
73
- raise HTTPException(403, "Invalid API Key")
 
 
 
 
 
74
 
75
- # ======================================================
76
  # ROOT
77
- # ======================================================
78
 
79
  @app.get("/")
80
  async def root():
@@ -84,9 +102,9 @@ async def root():
84
  "provider": "Duck.ai"
85
  }
86
 
87
- # ======================================================
88
- # MODELS
89
- # ======================================================
90
 
91
  @app.get("/v1/models")
92
  async def models():
@@ -104,15 +122,16 @@ async def models():
104
  ]
105
  }
106
 
107
- # ======================================================
108
- # STREAM
109
- # ======================================================
110
 
111
- async def stream_generator(model, messages):
112
 
113
  try:
114
 
115
- response = g4f.ChatCompletion.create(
 
116
  model=model,
117
  provider=g4f.Provider.DuckDuckGo,
118
  messages=messages,
@@ -130,9 +149,11 @@ async def stream_generator(model, messages):
130
  "model": model,
131
  "choices": [
132
  {
 
133
  "delta": {
134
- "content": chunk
135
- }
 
136
  }
137
  ]
138
  }
@@ -145,20 +166,24 @@ async def stream_generator(model, messages):
145
 
146
  except Exception as e:
147
 
148
- error = {
149
  "error": {
150
- "message": str(e)
 
151
  }
152
  }
153
 
154
- yield f"data: {json.dumps(error)}\n\n"
155
 
156
- # ======================================================
157
- # CHAT
158
- # ======================================================
159
 
160
  @app.post("/v1/chat/completions")
161
- async def chat(req: Request, body: ChatRequest):
 
 
 
162
 
163
  verify_api_key(req)
164
 
@@ -170,27 +195,32 @@ async def chat(req: Request, body: ChatRequest):
170
  for m in body.messages
171
  ]
172
 
173
- # ==================================================
174
  # STREAM
175
- # ==================================================
176
 
177
  if body.stream:
178
 
179
  return StreamingResponse(
180
- stream_generator(
181
  body.model,
182
  messages
183
  ),
184
- media_type="text/event-stream"
 
 
 
 
185
  )
186
 
187
- # ==================================================
188
- # NORMAL
189
- # ==================================================
190
 
191
  try:
192
 
193
- response = g4f.ChatCompletion.create(
 
194
  model=body.model,
195
  provider=g4f.Provider.DuckDuckGo,
196
  messages=messages
@@ -203,10 +233,12 @@ async def chat(req: Request, body: ChatRequest):
203
  "model": body.model,
204
  "choices": [
205
  {
 
206
  "message": {
207
  "role": "assistant",
208
- "content": response
209
- }
 
210
  }
211
  ]
212
  })
@@ -216,4 +248,18 @@ async def chat(req: Request, body: ChatRequest):
216
  raise HTTPException(
217
  status_code=500,
218
  detail=str(e)
219
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, Request, HTTPException
 
2
  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
 
9
  import time
10
  import asyncio
11
 
12
+ # =====================================================
13
+ # CONFIG
14
+ # =====================================================
15
 
16
+ API_KEY = "sk-your-secret-key"
17
 
18
+ # =====================================================
19
+ # FASTAPI
20
+ # =====================================================
21
 
22
+ app = FastAPI(
23
+ title="Universal AI Gateway",
24
+ version="2.1.0"
25
+ )
26
+
27
+ # =====================================================
28
+ # CORS
29
+ # =====================================================
30
 
31
  app.add_middleware(
32
  CORSMiddleware,
 
36
  allow_headers=["*"],
37
  )
38
 
39
+ # =====================================================
40
  # MODELS
41
+ # =====================================================
42
 
43
  MODELS = [
44
  "gpt-4o-mini",
45
  "gpt-4",
46
  "claude-3-haiku",
47
  "llama-3.1-70b",
48
+ "mixtral-8x7b"
49
  ]
50
 
51
+ # =====================================================
52
+ # REQUEST MODELS
53
+ # =====================================================
54
 
55
  class Message(BaseModel):
56
  role: str
 
60
  model: str
61
  messages: List[Message]
62
  stream: bool = False
63
+ temperature: float = 0.7
64
+ max_tokens: int = 4096
65
 
66
+ # =====================================================
67
  # AUTH
68
+ # =====================================================
69
 
70
  def verify_api_key(req: Request):
71
 
72
  auth = req.headers.get("Authorization")
73
 
74
  if not auth:
75
+ return True
76
 
77
  if not auth.startswith("Bearer "):
78
+ raise HTTPException(
79
+ status_code=401,
80
+ detail="Invalid Authorization Format"
81
+ )
82
 
83
  token = auth.replace("Bearer ", "")
84
 
85
  if token != API_KEY:
86
+ raise HTTPException(
87
+ status_code=403,
88
+ detail="Invalid API Key"
89
+ )
90
+
91
+ return True
92
 
93
+ # =====================================================
94
  # ROOT
95
+ # =====================================================
96
 
97
  @app.get("/")
98
  async def root():
 
102
  "provider": "Duck.ai"
103
  }
104
 
105
+ # =====================================================
106
+ # MODELS ENDPOINT
107
+ # =====================================================
108
 
109
  @app.get("/v1/models")
110
  async def models():
 
122
  ]
123
  }
124
 
125
+ # =====================================================
126
+ # STREAM GENERATOR
127
+ # =====================================================
128
 
129
+ async def generate_stream(model, messages):
130
 
131
  try:
132
 
133
+ response = await asyncio.to_thread(
134
+ g4f.ChatCompletion.create,
135
  model=model,
136
  provider=g4f.Provider.DuckDuckGo,
137
  messages=messages,
 
149
  "model": model,
150
  "choices": [
151
  {
152
+ "index": 0,
153
  "delta": {
154
+ "content": str(chunk)
155
+ },
156
+ "finish_reason": None
157
  }
158
  ]
159
  }
 
166
 
167
  except Exception as e:
168
 
169
+ error_payload = {
170
  "error": {
171
+ "message": str(e),
172
+ "type": "server_error"
173
  }
174
  }
175
 
176
+ yield f"data: {json.dumps(error_payload)}\n\n"
177
 
178
+ # =====================================================
179
+ # CHAT COMPLETIONS
180
+ # =====================================================
181
 
182
  @app.post("/v1/chat/completions")
183
+ async def chat_completions(
184
+ req: Request,
185
+ body: ChatRequest
186
+ ):
187
 
188
  verify_api_key(req)
189
 
 
195
  for m in body.messages
196
  ]
197
 
198
+ # =================================================
199
  # STREAM
200
+ # =================================================
201
 
202
  if body.stream:
203
 
204
  return StreamingResponse(
205
+ generate_stream(
206
  body.model,
207
  messages
208
  ),
209
+ media_type="text/event-stream",
210
+ headers={
211
+ "Cache-Control": "no-cache",
212
+ "X-Accel-Buffering": "no"
213
+ }
214
  )
215
 
216
+ # =================================================
217
+ # NORMAL RESPONSE
218
+ # =================================================
219
 
220
  try:
221
 
222
+ response = await asyncio.to_thread(
223
+ g4f.ChatCompletion.create,
224
  model=body.model,
225
  provider=g4f.Provider.DuckDuckGo,
226
  messages=messages
 
233
  "model": body.model,
234
  "choices": [
235
  {
236
+ "index": 0,
237
  "message": {
238
  "role": "assistant",
239
+ "content": str(response)
240
+ },
241
+ "finish_reason": "stop"
242
  }
243
  ]
244
  })
 
248
  raise HTTPException(
249
  status_code=500,
250
  detail=str(e)
251
+ )
252
+
253
+ # =====================================================
254
+ # RUN
255
+ # =====================================================
256
+
257
+ if __name__ == "__main__":
258
+
259
+ import uvicorn
260
+
261
+ uvicorn.run(
262
+ app,
263
+ host="0.0.0.0",
264
+ port=7860
265
+ )