Elysiadev11 commited on
Commit
3f06aeb
Β·
verified Β·
1 Parent(s): 2832dbe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import random
4
+ from typing import Dict
5
+
6
+ from fastapi import FastAPI, Request, HTTPException
7
+ from fastapi.responses import StreamingResponse, HTMLResponse, JSONResponse
8
+
9
+ from ollama import Client
10
+
11
+ app = FastAPI()
12
+
13
+ # ── CONFIG ─────────────────────────────────────────────
14
+ MASTER_API_KEY = os.getenv("MASTER_API_KEY", "changeme")
15
+ BASE_URL = os.getenv("BASE_URL", "https://ollama.com")
16
+
17
+ # ── LOAD KEYS ──────────────────────────────────────────
18
+ def load_keys(prefix="OLLAMA_KEY_"):
19
+ pairs = []
20
+ for k, v in os.environ.items():
21
+ if k.startswith(prefix) and v:
22
+ try:
23
+ idx = int(k.replace(prefix, ""))
24
+ except:
25
+ idx = 9999
26
+ pairs.append((idx, v.strip()))
27
+ pairs.sort(key=lambda x: x[0])
28
+ return [v for _, v in pairs]
29
+
30
+ API_KEYS = load_keys()
31
+ print(f"[INIT] Loaded {len(API_KEYS)} keys")
32
+
33
+ # ── STATE ──────────────────────────────────────────────
34
+ key_status: Dict[str, Dict] = {
35
+ k: {
36
+ "status": "active",
37
+ "fail": 0,
38
+ "cooldown": 0,
39
+ "req": 0,
40
+ "err": 0,
41
+ "last": "-"
42
+ }
43
+ for k in API_KEYS
44
+ }
45
+
46
+ # ── AUTH ───────────────────────────────────────────────
47
+ def auth(req: Request):
48
+ if req.headers.get("Authorization") != f"Bearer {MASTER_API_KEY}":
49
+ raise HTTPException(401, "Unauthorized")
50
+
51
+ # ── KEY PICKER ─────────────────────────────────────────
52
+ def pick_key():
53
+ now = time.time()
54
+ valid = []
55
+
56
+ for k, v in key_status.items():
57
+ if v["status"] == "dead":
58
+ continue
59
+ if v["cooldown"] > now:
60
+ continue
61
+ valid.append(k)
62
+
63
+ return random.choice(valid) if valid else None
64
+
65
+ # ── STATUS UPDATE ──────────────────────────────────────
66
+ def mark_limit(k):
67
+ key_status[k]["status"] = "limited"
68
+ key_status[k]["cooldown"] = time.time() + 60
69
+ key_status[k]["err"] += 1
70
+ key_status[k]["last"] = "rate_limit"
71
+
72
+ def mark_dead(k, reason="dead"):
73
+ key_status[k]["status"] = "dead"
74
+ key_status[k]["err"] += 1
75
+ key_status[k]["last"] = reason
76
+
77
+ def mark_ok(k):
78
+ key_status[k]["status"] = "active"
79
+ key_status[k]["fail"] = 0
80
+ key_status[k]["last"] = "-"
81
+
82
+ # ── STREAM PROXY ───────────────────────────────────────
83
+ @app.post("/chat")
84
+ async def chat(req: Request):
85
+ auth(req)
86
+ body = await req.json()
87
+
88
+ model = body.get("model")
89
+ messages = body.get("messages")
90
+
91
+ if not model:
92
+ return JSONResponse({"error": "model required"}, status_code=400)
93
+
94
+ if not messages:
95
+ return JSONResponse({"error": "messages required"}, status_code=400)
96
+
97
+ for _ in range(len(API_KEYS)):
98
+ key = pick_key()
99
+
100
+ if not key:
101
+ return JSONResponse({"error": "all keys exhausted"}, status_code=503)
102
+
103
+ try:
104
+ client = Client(
105
+ host=BASE_URL,
106
+ headers={"Authorization": f"Bearer {key}"}
107
+ )
108
+
109
+ key_status[key]["req"] += 1
110
+
111
+ def stream():
112
+ try:
113
+ for part in client.chat(model, messages=messages, stream=True):
114
+ yield part["message"]["content"]
115
+ mark_ok(key)
116
+
117
+ except Exception as e:
118
+ key_status[key]["fail"] += 1
119
+ key_status[key]["err"] += 1
120
+ key_status[key]["last"] = str(e)
121
+
122
+ if "429" in str(e):
123
+ mark_limit(key)
124
+ elif key_status[key]["fail"] >= 3:
125
+ mark_dead(key, "fail")
126
+
127
+ raise e
128
+
129
+ return StreamingResponse(stream(), media_type="text/plain")
130
+
131
+ except Exception:
132
+ continue
133
+
134
+ return JSONResponse({"error": "all keys failed"}, status_code=500)
135
+
136
+ # ── DASHBOARD ──────────────────────────────────────────
137
+ @app.get("/dashboard")
138
+ async def dash(req: Request):
139
+ auth(req)
140
+
141
+ now = time.time()
142
+
143
+ html = """
144
+ <html><body style="background:#0f172a;color:white;font-family:sans-serif">
145
+ <h2>KEY STATUS</h2>
146
+ <table border="1" cellpadding="8">
147
+ <tr>
148
+ <th>Key</th><th>Status</th><th>Req</th><th>Err</th><th>Cooldown</th><th>Last</th>
149
+ </tr>
150
+ """
151
+
152
+ for k, v in key_status.items():
153
+ cd = max(0, int(v["cooldown"] - now))
154
+ html += f"""
155
+ <tr>
156
+ <td>{k[:6]}...</td>
157
+ <td>{v['status']}</td>
158
+ <td>{v['req']}</td>
159
+ <td>{v['err']}</td>
160
+ <td>{cd}s</td>
161
+ <td>{v['last']}</td>
162
+ </tr>
163
+ """
164
+
165
+ html += "</table></body></html>"
166
+ return HTMLResponse(html)
167
+
168
+ # ── ROOT ───────────────────────────────────────────────
169
+ @app.get("/")
170
+ def root():
171
+ return {"status": "ok", "keys": len(API_KEYS)}