bahi-bh commited on
Commit
18e8000
·
verified ·
1 Parent(s): 1627ff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -72
app.py CHANGED
@@ -16,21 +16,21 @@ from pydantic import BaseModel
16
 
17
  API_KEY = "sk-your-secret-key"
18
 
19
- PROVIDERS = [
20
- g4f.Provider.DuckDuckGo,
21
- g4f.Provider.Blackbox,
22
- ]
23
-
24
  executor = ThreadPoolExecutor(max_workers=5)
25
 
26
  # =====================================
27
- # APP
28
  # =====================================
29
 
30
  app = FastAPI(
31
- title="HuggingFace AI Gateway"
 
32
  )
33
 
 
 
 
 
34
  app.add_middleware(
35
  CORSMiddleware,
36
  allow_origins=["*"],
@@ -52,15 +52,21 @@ class ChatRequest(BaseModel):
52
  stream: bool = False
53
 
54
  # =====================================
55
- # AUTH
56
  # =====================================
57
 
58
  def verify_api_key(auth: str):
59
 
 
 
 
 
 
 
60
  if not auth.startswith("Bearer "):
61
  raise HTTPException(
62
  status_code=401,
63
- detail="Invalid Authorization"
64
  )
65
 
66
  token = auth.replace("Bearer ", "")
@@ -72,106 +78,92 @@ def verify_api_key(auth: str):
72
  )
73
 
74
  # =====================================
75
- # GENERATE
76
  # =====================================
77
 
78
- def generate(model, messages):
79
-
80
- last_error = None
81
 
82
- for provider in PROVIDERS:
83
-
84
- try:
85
-
86
- response = g4f.ChatCompletion.create(
87
- model=model,
88
- provider=provider,
89
- messages=messages
90
- )
91
-
92
- return response
93
 
94
- except Exception as e:
 
 
 
95
 
96
- print(f"{provider.__name__}: {e}")
97
 
98
- last_error = e
99
 
100
- raise Exception(str(last_error))
101
 
102
  # =====================================
103
- # STREAM
104
  # =====================================
105
 
106
- async def stream_generate(model, messages):
107
 
108
  loop = asyncio.get_event_loop()
109
 
110
- for provider in PROVIDERS:
111
-
112
- try:
113
 
114
- response = await loop.run_in_executor(
115
- executor,
116
- lambda: g4f.ChatCompletion.create(
117
- model=model,
118
- provider=provider,
119
- messages=messages,
120
- stream=True
121
- )
122
  )
 
123
 
124
- for chunk in response:
125
 
126
- if chunk:
127
 
128
- payload = {
129
- "choices": [
130
- {
131
- "delta": {
132
- "content": chunk
133
- }
134
  }
135
- ]
136
- }
137
-
138
- yield f"data: {json.dumps(payload)}\\n\\n"
139
-
140
- yield "data: [DONE]\\n\\n"
141
 
142
- return
143
 
144
- except Exception as e:
145
 
146
- print(f"Streaming Error: {e}")
147
 
148
- continue
 
 
149
 
150
- yield f"data: {json.dumps({'error':'All providers failed'})}\\n\\n"
151
 
152
  # =====================================
153
- # API
154
  # =====================================
155
 
156
  @app.get("/")
157
  async def home():
158
 
159
  return {
160
- "status": "online"
 
161
  }
162
 
 
 
 
 
163
  @app.post("/v1/chat/completions")
164
  async def chat(
165
  req: ChatRequest,
166
  authorization: str = Header(None)
167
  ):
168
 
169
- if not authorization:
170
- raise HTTPException(
171
- status_code=401,
172
- detail="Missing Authorization"
173
- )
174
-
175
  verify_api_key(authorization)
176
 
177
  messages = [
@@ -180,13 +172,13 @@ async def chat(
180
  ]
181
 
182
  # =================================
183
- # STREAM
184
  # =================================
185
 
186
  if req.stream:
187
 
188
  return StreamingResponse(
189
- stream_generate(
190
  req.model,
191
  messages
192
  ),
@@ -194,7 +186,7 @@ async def chat(
194
  )
195
 
196
  # =================================
197
- # NORMAL
198
  # =================================
199
 
200
  loop = asyncio.get_event_loop()
@@ -203,7 +195,7 @@ async def chat(
203
 
204
  response = await loop.run_in_executor(
205
  executor,
206
- lambda: generate(
207
  req.model,
208
  messages
209
  )
 
16
 
17
  API_KEY = "sk-your-secret-key"
18
 
 
 
 
 
 
19
  executor = ThreadPoolExecutor(max_workers=5)
20
 
21
  # =====================================
22
+ # FASTAPI
23
  # =====================================
24
 
25
  app = FastAPI(
26
+ title="AI Gateway",
27
+ version="2.0.0"
28
  )
29
 
30
+ # =====================================
31
+ # CORS
32
+ # =====================================
33
+
34
  app.add_middleware(
35
  CORSMiddleware,
36
  allow_origins=["*"],
 
52
  stream: bool = False
53
 
54
  # =====================================
55
+ # API KEY
56
  # =====================================
57
 
58
  def verify_api_key(auth: str):
59
 
60
+ if not auth:
61
+ raise HTTPException(
62
+ status_code=401,
63
+ detail="Missing Authorization Header"
64
+ )
65
+
66
  if not auth.startswith("Bearer "):
67
  raise HTTPException(
68
  status_code=401,
69
+ detail="Invalid Authorization Format"
70
  )
71
 
72
  token = auth.replace("Bearer ", "")
 
78
  )
79
 
80
  # =====================================
81
+ # NORMAL RESPONSE
82
  # =====================================
83
 
84
+ def generate_response(model, messages):
 
 
85
 
86
+ try:
 
 
 
 
 
 
 
 
 
 
87
 
88
+ response = g4f.ChatCompletion.create(
89
+ model=model,
90
+ messages=messages
91
+ )
92
 
93
+ return response
94
 
95
+ except Exception as e:
96
 
97
+ raise Exception(str(e))
98
 
99
  # =====================================
100
+ # STREAMING RESPONSE
101
  # =====================================
102
 
103
+ async def stream_response(model, messages):
104
 
105
  loop = asyncio.get_event_loop()
106
 
107
+ try:
 
 
108
 
109
+ response = await loop.run_in_executor(
110
+ executor,
111
+ lambda: g4f.ChatCompletion.create(
112
+ model=model,
113
+ messages=messages,
114
+ stream=True
 
 
115
  )
116
+ )
117
 
118
+ for chunk in response:
119
 
120
+ if chunk:
121
 
122
+ payload = {
123
+ "choices": [
124
+ {
125
+ "delta": {
126
+ "content": chunk
 
127
  }
128
+ }
129
+ ]
130
+ }
 
 
 
131
 
132
+ yield f"data: {json.dumps(payload)}\\n\\n"
133
 
134
+ yield "data: [DONE]\\n\\n"
135
 
136
+ except Exception as e:
137
 
138
+ error_payload = {
139
+ "error": str(e)
140
+ }
141
 
142
+ yield f"data: {json.dumps(error_payload)}\\n\\n"
143
 
144
  # =====================================
145
+ # HOME
146
  # =====================================
147
 
148
  @app.get("/")
149
  async def home():
150
 
151
  return {
152
+ "status": "online",
153
+ "service": "AI Gateway"
154
  }
155
 
156
+ # =====================================
157
+ # CHAT COMPLETIONS
158
+ # =====================================
159
+
160
  @app.post("/v1/chat/completions")
161
  async def chat(
162
  req: ChatRequest,
163
  authorization: str = Header(None)
164
  ):
165
 
166
+ # تحقق API Key
 
 
 
 
 
167
  verify_api_key(authorization)
168
 
169
  messages = [
 
172
  ]
173
 
174
  # =================================
175
+ # STREAMING
176
  # =================================
177
 
178
  if req.stream:
179
 
180
  return StreamingResponse(
181
+ stream_response(
182
  req.model,
183
  messages
184
  ),
 
186
  )
187
 
188
  # =================================
189
+ # NORMAL RESPONSE
190
  # =================================
191
 
192
  loop = asyncio.get_event_loop()
 
195
 
196
  response = await loop.run_in_executor(
197
  executor,
198
+ lambda: generate_response(
199
  req.model,
200
  messages
201
  )