Nottybro commited on
Commit
8c37db9
·
1 Parent(s): 419a331

Add daily token cap: 2.5M tokens per UTC day

Browse files

- Counts total_tokens from upstream usage (exact for both stream and
non-stream; stream sniffed via injected stream_options.include_usage)
- chars/4 estimate fallback when upstream omits usage
- Pre-check (used + prompt estimate) rejects with 429 once cap hit
- Counter persists to tempdir (survives app restart; container rebuild resets)
- DAILY_TOKEN_CAP env override; / and /health show today's usage

Files changed (1) hide show
  1. app.py +103 -4
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import os, json, httpx
2
  from fastapi import FastAPI, Request
3
  from fastapi.responses import JSONResponse, StreamingResponse, HTMLResponse
4
  import uvicorn
@@ -7,6 +7,54 @@ app = FastAPI()
7
 
8
  KIMI_BASE = os.environ.get("KIMI_BASE_URL", "https://api.kimi.com/coding").rstrip("/")
9
  DEFAULT_MODEL = os.environ.get("KIMI_DEFAULT_MODEL", "k3")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  def get_key():
12
  key = os.environ.get("KIMI_API_KEY", "")
@@ -48,11 +96,14 @@ async def root():
48
  color = "#00ff88" if alive else "#ff4444"
49
  status = "ONLINE" if alive else "OFFLINE"
50
  models = ", ".join(info) if isinstance(info, list) else info
 
 
51
  return HTMLResponse(f"""<html><body style="font-family:monospace;padding:2rem;background:#0d1117;color:#c9d1d9">
52
  <h2>WirelessAudit Proxy</h2>
53
  <p>Backend: <code>Kimi K3</code> — <code>{KIMI_BASE}</code></p>
54
  <p>Status: <b style="color:{color}">{status}</b></p>
55
  <p>Models: <code>{models}</code></p>
 
56
  <p>Cline Base URL: <code>/v1</code> (requires API key)</p>
57
  </body></html>""")
58
 
@@ -63,9 +114,10 @@ async def health():
63
  except ValueError as e:
64
  return JSONResponse({"status": "offline", "error": str(e)}, status_code=503)
65
  alive, info = await kimi_alive()
 
66
  if alive:
67
- return {"status": "ok", "backend": "kimi", "models": info}
68
- return JSONResponse({"status": "offline", "error": info}, status_code=503)
69
 
70
  @app.get("/v1/models")
71
  async def models(request: Request):
@@ -92,10 +144,18 @@ async def chat(request: Request):
92
  if not body.get("model"):
93
  body["model"] = DEFAULT_MODEL
94
  stream = body.get("stream", False)
 
 
 
 
 
95
  url = f"{KIMI_BASE}/v1/chat/completions"
96
  timeout = httpx.Timeout(300.0, connect=15.0)
97
  try:
98
  if stream:
 
 
 
99
  c = httpx.AsyncClient(timeout=timeout)
100
  req = c.build_request("POST", url, json=body, headers=headers)
101
  r = await c.send(req, stream=True)
@@ -109,22 +169,61 @@ async def chat(request: Request):
109
  except Exception:
110
  payload = {"error": {"message": err_body.decode(errors="replace"), "code": code}}
111
  return JSONResponse(payload, status_code=code)
 
112
  async def proxy():
 
 
 
113
  try:
114
  async for chunk in r.aiter_bytes():
115
  yield chunk
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  finally:
117
  await r.aclose()
118
  await c.aclose()
 
 
 
 
 
119
  return StreamingResponse(proxy(), media_type="text/event-stream",
120
  headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
121
  async with httpx.AsyncClient(timeout=timeout) as c:
122
  r = await c.post(url, json=body, headers=headers)
123
  try:
124
- return JSONResponse(r.json(), status_code=r.status_code)
125
  except Exception:
126
  return JSONResponse({"error": {"message": r.text, "code": r.status_code}},
127
  status_code=r.status_code)
 
 
 
 
 
 
 
 
 
128
  except httpx.ConnectError:
129
  return JSONResponse({"error": {"message": "Kimi unreachable", "code": 503}}, status_code=503)
130
  except httpx.ReadTimeout:
 
1
+ import os, json, time, tempfile, httpx
2
  from fastapi import FastAPI, Request
3
  from fastapi.responses import JSONResponse, StreamingResponse, HTMLResponse
4
  import uvicorn
 
7
 
8
  KIMI_BASE = os.environ.get("KIMI_BASE_URL", "https://api.kimi.com/coding").rstrip("/")
9
  DEFAULT_MODEL = os.environ.get("KIMI_DEFAULT_MODEL", "k3")
10
+ DAILY_CAP = int(os.environ.get("DAILY_TOKEN_CAP", "2500000"))
11
+ USAGE_FILE = os.path.join(tempfile.gettempdir(), "wirelessaudit_token_usage.json")
12
+
13
+ _usage = {"date": "", "used": 0}
14
+
15
+ def _today():
16
+ return time.strftime("%Y-%m-%d", time.gmtime())
17
+
18
+ def _load_usage():
19
+ try:
20
+ with open(USAGE_FILE) as f:
21
+ d = json.load(f)
22
+ if d.get("date") == _today() and isinstance(d.get("used"), int):
23
+ _usage.update(d)
24
+ except Exception:
25
+ pass
26
+
27
+ def _save_usage():
28
+ try:
29
+ with open(USAGE_FILE, "w") as f:
30
+ json.dump(_usage, f)
31
+ except Exception:
32
+ pass
33
+
34
+ def usage_today():
35
+ """Tokens used today (UTC); rolls the counter at the day boundary."""
36
+ if _usage["date"] != _today():
37
+ _usage["date"] = _today()
38
+ _usage["used"] = 0
39
+ _save_usage()
40
+ return _usage["used"]
41
+
42
+ def usage_add(n):
43
+ usage_today()
44
+ _usage["used"] += max(0, int(n))
45
+ _save_usage()
46
+
47
+ def estimate_prompt_tokens(body):
48
+ n = 0
49
+ for m in body.get("messages", []):
50
+ c = m.get("content")
51
+ if isinstance(c, str):
52
+ n += len(c)
53
+ elif isinstance(c, list):
54
+ n += sum(len(p.get("text", "")) for p in c if isinstance(p, dict))
55
+ return n // 4 + 8
56
+
57
+ _load_usage()
58
 
59
  def get_key():
60
  key = os.environ.get("KIMI_API_KEY", "")
 
96
  color = "#00ff88" if alive else "#ff4444"
97
  status = "ONLINE" if alive else "OFFLINE"
98
  models = ", ".join(info) if isinstance(info, list) else info
99
+ used = usage_today()
100
+ cap_color = "#ff4444" if used >= DAILY_CAP else "#00ff88"
101
  return HTMLResponse(f"""<html><body style="font-family:monospace;padding:2rem;background:#0d1117;color:#c9d1d9">
102
  <h2>WirelessAudit Proxy</h2>
103
  <p>Backend: <code>Kimi K3</code> — <code>{KIMI_BASE}</code></p>
104
  <p>Status: <b style="color:{color}">{status}</b></p>
105
  <p>Models: <code>{models}</code></p>
106
+ <p>Daily tokens (UTC): <b style="color:{cap_color}">{used:,}</b> / {DAILY_CAP:,} — resets 00:00 UTC</p>
107
  <p>Cline Base URL: <code>/v1</code> (requires API key)</p>
108
  </body></html>""")
109
 
 
114
  except ValueError as e:
115
  return JSONResponse({"status": "offline", "error": str(e)}, status_code=503)
116
  alive, info = await kimi_alive()
117
+ usage = {"used": usage_today(), "cap": DAILY_CAP}
118
  if alive:
119
+ return {"status": "ok", "backend": "kimi", "models": info, "daily_tokens": usage}
120
+ return JSONResponse({"status": "offline", "error": info, "daily_tokens": usage}, status_code=503)
121
 
122
  @app.get("/v1/models")
123
  async def models(request: Request):
 
144
  if not body.get("model"):
145
  body["model"] = DEFAULT_MODEL
146
  stream = body.get("stream", False)
147
+ est_prompt = estimate_prompt_tokens(body)
148
+ used = usage_today()
149
+ if used + est_prompt >= DAILY_CAP:
150
+ return JSONResponse({"error": {"message": f"Daily token cap reached ({used:,}/{DAILY_CAP:,} tokens, UTC day). Resets at 00:00 UTC.",
151
+ "type": "rate_limit_exceeded", "code": 429}}, status_code=429)
152
  url = f"{KIMI_BASE}/v1/chat/completions"
153
  timeout = httpx.Timeout(300.0, connect=15.0)
154
  try:
155
  if stream:
156
+ so = dict(body.get("stream_options") or {})
157
+ so["include_usage"] = True
158
+ body["stream_options"] = so
159
  c = httpx.AsyncClient(timeout=timeout)
160
  req = c.build_request("POST", url, json=body, headers=headers)
161
  r = await c.send(req, stream=True)
 
169
  except Exception:
170
  payload = {"error": {"message": err_body.decode(errors="replace"), "code": code}}
171
  return JSONResponse(payload, status_code=code)
172
+
173
  async def proxy():
174
+ usage = None
175
+ completion_chars = 0
176
+ buf = b""
177
  try:
178
  async for chunk in r.aiter_bytes():
179
  yield chunk
180
+ buf += chunk
181
+ if len(buf) > 65536:
182
+ buf = buf[-4096:]
183
+ while b"\n" in buf:
184
+ line, buf = buf.split(b"\n", 1)
185
+ line = line.strip()
186
+ if not line.startswith(b"data:"):
187
+ continue
188
+ data = line[5:].strip()
189
+ if not data or data == b"[DONE]":
190
+ continue
191
+ try:
192
+ ev = json.loads(data)
193
+ except Exception:
194
+ continue
195
+ if ev.get("usage"):
196
+ usage = ev["usage"]
197
+ for ch in ev.get("choices") or []:
198
+ d = ch.get("delta") or {}
199
+ completion_chars += len(d.get("content") or "")
200
+ completion_chars += len(d.get("reasoning_content") or "")
201
  finally:
202
  await r.aclose()
203
  await c.aclose()
204
+ if usage and usage.get("total_tokens"):
205
+ usage_add(usage["total_tokens"])
206
+ else:
207
+ usage_add(est_prompt + completion_chars // 4)
208
+
209
  return StreamingResponse(proxy(), media_type="text/event-stream",
210
  headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
211
  async with httpx.AsyncClient(timeout=timeout) as c:
212
  r = await c.post(url, json=body, headers=headers)
213
  try:
214
+ payload = r.json()
215
  except Exception:
216
  return JSONResponse({"error": {"message": r.text, "code": r.status_code}},
217
  status_code=r.status_code)
218
+ if r.status_code == 200:
219
+ u = payload.get("usage") or {}
220
+ if u.get("total_tokens"):
221
+ usage_add(u["total_tokens"])
222
+ else:
223
+ out = "".join((ch.get("message") or {}).get("content") or ""
224
+ for ch in payload.get("choices", []))
225
+ usage_add(est_prompt + len(out) // 4)
226
+ return JSONResponse(payload, status_code=r.status_code)
227
  except httpx.ConnectError:
228
  return JSONResponse({"error": {"message": "Kimi unreachable", "code": 503}}, status_code=503)
229
  except httpx.ReadTimeout: