Elysiadev11 commited on
Commit
aa0cd44
Β·
verified Β·
1 Parent(s): 6f02e11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -32
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import time
3
  import random
4
- import json
5
  import httpx
6
  from typing import Dict
7
 
@@ -33,7 +32,11 @@ print(f"[INIT] Loaded {len(API_KEYS)} keys")
33
  # STATE
34
  # ─────────────────────────────
35
  key_status: Dict[str, Dict] = {
36
- k: {"fail": 0, "cooldown": 0, "status": "active"}
 
 
 
 
37
  for k in API_KEYS
38
  }
39
 
@@ -70,7 +73,7 @@ def mark_ok(k):
70
  key_status[k]["status"] = "active"
71
 
72
  # ─────────────────────────────
73
- # UNIVERSAL OPENAI PROXY
74
  # ─────────────────────────────
75
  @app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
76
  async def proxy(req: Request, path: str):
@@ -91,51 +94,61 @@ async def proxy(req: Request, path: str):
91
  headers["Authorization"] = f"Bearer {key}"
92
 
93
  try:
94
- async with httpx.AsyncClient(timeout=None) as client:
95
 
96
- # πŸ”₯ STREAM SAFE MODE (FIX UTAMA)
97
- async with client.stream(
 
 
98
  method=req.method,
99
  url=target_url,
100
  headers=headers,
101
  content=body,
102
  params=req.query_params
103
- ) as r:
104
-
105
- # ERROR RESPONSE
106
- if r.status_code >= 400:
107
- err = await r.aread()
108
- if r.status_code == 429:
109
- mark_limit(key)
110
- elif r.status_code >= 500:
111
- key_status[key]["fail"] += 1
112
- if key_status[key]["fail"] >= 3:
113
- mark_dead(key)
114
-
115
- continue
116
-
117
- mark_ok(key)
118
-
119
- # STREAMING RESPONSE
120
- return StreamingResponse(
121
- r.aiter_bytes(),
122
- media_type=r.headers.get(
123
- "content-type",
124
- "application/json"
125
- )
 
 
 
 
 
 
126
  )
 
127
 
128
  except Exception as e:
129
  key_status[key]["fail"] += 1
 
130
  if key_status[key]["fail"] >= 3:
131
  mark_dead(key)
132
 
133
- print(f"[ERROR] key={key[:6]} err={e}")
134
 
135
  return JSONResponse(
136
  {
137
  "error": "all keys failed",
138
- "hint": "check keys or model access"
139
  },
140
  500
141
  )
@@ -147,6 +160,6 @@ async def proxy(req: Request, path: str):
147
  def root():
148
  return {
149
  "status": "ok",
150
- "mode": "openai-grade-proxy",
151
  "keys": len(API_KEYS)
152
  }
 
1
  import os
2
  import time
3
  import random
 
4
  import httpx
5
  from typing import Dict
6
 
 
32
  # STATE
33
  # ─────────────────────────────
34
  key_status: Dict[str, Dict] = {
35
+ k: {
36
+ "fail": 0,
37
+ "cooldown": 0,
38
+ "status": "active"
39
+ }
40
  for k in API_KEYS
41
  }
42
 
 
73
  key_status[k]["status"] = "active"
74
 
75
  # ─────────────────────────────
76
+ # UNIVERSAL OPENAI PROXY (/v1/*)
77
  # ─────────────────────────────
78
  @app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
79
  async def proxy(req: Request, path: str):
 
94
  headers["Authorization"] = f"Bearer {key}"
95
 
96
  try:
97
+ async with httpx.AsyncClient(timeout=60) as client:
98
 
99
+ # ─────────────────────────────
100
+ # STEP 1: VALIDATE REQUEST (NO STREAM)
101
+ # ─────────────────────────────
102
+ test = await client.request(
103
  method=req.method,
104
  url=target_url,
105
  headers=headers,
106
  content=body,
107
  params=req.query_params
108
+ )
109
+
110
+ if test.status_code >= 400:
111
+ if test.status_code == 429:
112
+ mark_limit(key)
113
+ elif test.status_code >= 500:
114
+ key_status[key]["fail"] += 1
115
+ if key_status[key]["fail"] >= 3:
116
+ mark_dead(key)
117
+ continue
118
+
119
+ mark_ok(key)
120
+
121
+ # ─────────────────────────────
122
+ # STEP 2: STREAM RESPONSE (SAFE)
123
+ # ─────────────────────────────
124
+ stream = await client.stream(
125
+ method=req.method,
126
+ url=target_url,
127
+ headers=headers,
128
+ content=body,
129
+ params=req.query_params
130
+ )
131
+
132
+ return StreamingResponse(
133
+ stream.aiter_bytes(),
134
+ media_type=test.headers.get(
135
+ "content-type",
136
+ "application/json"
137
  )
138
+ )
139
 
140
  except Exception as e:
141
  key_status[key]["fail"] += 1
142
+
143
  if key_status[key]["fail"] >= 3:
144
  mark_dead(key)
145
 
146
+ print(f"[ERROR] key={key[:6]} -> {e}")
147
 
148
  return JSONResponse(
149
  {
150
  "error": "all keys failed",
151
+ "hint": "check keys / model access / BASE_URL"
152
  },
153
  500
154
  )
 
160
  def root():
161
  return {
162
  "status": "ok",
163
+ "mode": "openai-proxy-fixed",
164
  "keys": len(API_KEYS)
165
  }