Route proxy to Kimi K3 instead of Kaggle tunnel
Browse files- Replace KAGGLE_TUNNEL_URL backend with Kimi for Coding API (api.kimi.com/coding)
- Auth via KIMI_API_KEY space secret (Bearer), base URL overridable via KIMI_BASE_URL
- Default model k3 when client omits one; streaming errors now surface real status codes
- Remove /update-tunnel endpoint (Kaggle-specific)
- Status page + /health now report Kimi reachability and model list
README.md
CHANGED
|
@@ -9,4 +9,5 @@ pinned: true
|
|
| 9 |
|
| 10 |
# WirelessAudit Proxy
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
| 9 |
|
| 10 |
# WirelessAudit Proxy
|
| 11 |
|
| 12 |
+
OpenAI-compatible proxy → Kimi K3 (`https://api.kimi.com/coding`).
|
| 13 |
+
Requires `KIMI_API_KEY` in space secrets. Client base URL: `/v1`.
|
app.py
CHANGED
|
@@ -1,104 +1,121 @@
|
|
| 1 |
-
import os, httpx
|
| 2 |
from fastapi import FastAPI, Request
|
| 3 |
from fastapi.responses import JSONResponse, StreamingResponse, HTMLResponse
|
| 4 |
import uvicorn
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
@app.get("/")
|
| 15 |
async def root():
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
async with httpx.AsyncClient(timeout=5) as c:
|
| 21 |
-
r = await c.get(f"{tunnel}/health")
|
| 22 |
-
d = r.json()
|
| 23 |
-
alive = d.get("status") == "ok"
|
| 24 |
-
model = d.get("model", "unknown")
|
| 25 |
-
except: pass
|
| 26 |
color = "#00ff88" if alive else "#ff4444"
|
| 27 |
status = "ONLINE" if alive else "OFFLINE"
|
|
|
|
| 28 |
return HTMLResponse(f"""<html><body style="font-family:monospace;padding:2rem;background:#0d1117;color:#c9d1d9">
|
| 29 |
<h2>WirelessAudit Proxy</h2>
|
|
|
|
| 30 |
<p>Status: <b style="color:{color}">{status}</b></p>
|
| 31 |
-
<p>
|
| 32 |
-
<p>Tunnel: <code>{tunnel}</code></p>
|
| 33 |
<p>Cline Base URL: <code>/v1</code></p>
|
| 34 |
</body></html>""")
|
| 35 |
|
| 36 |
@app.get("/health")
|
| 37 |
async def health():
|
| 38 |
try:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
return (await c.get(f"{t}/health")).json()
|
| 42 |
-
except Exception as e:
|
| 43 |
return JSONResponse({"status": "offline", "error": str(e)}, status_code=503)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
@app.get("/v1/models")
|
| 46 |
async def models():
|
| 47 |
try:
|
| 48 |
-
t = get_tunnel()
|
| 49 |
async with httpx.AsyncClient(timeout=10) as c:
|
| 50 |
-
|
| 51 |
-
|
|
|
|
| 52 |
return JSONResponse({"error": str(e)}, status_code=503)
|
|
|
|
|
|
|
| 53 |
|
| 54 |
@app.post("/v1/chat/completions")
|
| 55 |
async def chat(request: Request):
|
| 56 |
try:
|
| 57 |
-
|
| 58 |
except ValueError as e:
|
| 59 |
return JSONResponse({"error": str(e)}, status_code=503)
|
| 60 |
body = await request.json()
|
|
|
|
|
|
|
| 61 |
stream = body.get("stream", False)
|
|
|
|
|
|
|
| 62 |
try:
|
| 63 |
if stream:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
async def proxy():
|
| 65 |
-
|
| 66 |
-
async
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
| 70 |
return StreamingResponse(proxy(), media_type="text/event-stream",
|
| 71 |
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 72 |
-
async with httpx.AsyncClient(timeout=
|
| 73 |
-
r = await c.post(
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
except httpx.ConnectError:
|
| 77 |
-
return JSONResponse({"error": {"message": "
|
|
|
|
|
|
|
| 78 |
except Exception as e:
|
| 79 |
return JSONResponse({"error": {"message": str(e)}}, status_code=500)
|
| 80 |
|
| 81 |
-
@app.post("/update-tunnel")
|
| 82 |
-
async def update_tunnel(request: Request):
|
| 83 |
-
body = await request.json()
|
| 84 |
-
if body.get("secret") != os.environ.get("HF_TOKEN", ""):
|
| 85 |
-
return JSONResponse({"error": "unauthorized"}, status_code=401)
|
| 86 |
-
new_url = body.get("tunnel_url", "")
|
| 87 |
-
if not new_url:
|
| 88 |
-
return JSONResponse({"error": "tunnel_url required"}, status_code=400)
|
| 89 |
-
space_id = os.environ.get("MY_SPACE_ID", "")
|
| 90 |
-
hf_token = os.environ.get("HF_TOKEN", "")
|
| 91 |
-
try:
|
| 92 |
-
async with httpx.AsyncClient(timeout=15) as c:
|
| 93 |
-
r = await c.post(f"https://huggingface.co/api/spaces/{space_id}/secrets",
|
| 94 |
-
headers={"Authorization": f"Bearer {hf_token}", "Content-Type": "application/json"},
|
| 95 |
-
json={"key": "KAGGLE_TUNNEL_URL", "value": new_url})
|
| 96 |
-
if r.status_code == 200:
|
| 97 |
-
os.environ["KAGGLE_TUNNEL_URL"] = new_url
|
| 98 |
-
return JSONResponse({"status": "updated", "tunnel_url": new_url})
|
| 99 |
-
return JSONResponse({"error": r.text}, status_code=500)
|
| 100 |
-
except Exception as e:
|
| 101 |
-
return JSONResponse({"error": str(e)}, status_code=500)
|
| 102 |
-
|
| 103 |
if __name__ == "__main__":
|
| 104 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
import os, json, httpx
|
| 2 |
from fastapi import FastAPI, Request
|
| 3 |
from fastapi.responses import JSONResponse, StreamingResponse, HTMLResponse
|
| 4 |
import uvicorn
|
| 5 |
|
| 6 |
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", "")
|
| 13 |
+
if not key:
|
| 14 |
+
raise ValueError("KIMI_API_KEY not set")
|
| 15 |
+
return key
|
| 16 |
+
|
| 17 |
+
def auth_headers():
|
| 18 |
+
return {"Authorization": f"Bearer {get_key()}", "Content-Type": "application/json"}
|
| 19 |
+
|
| 20 |
+
async def kimi_alive():
|
| 21 |
+
"""Returns (ok, models_list | error_message)."""
|
| 22 |
+
try:
|
| 23 |
+
async with httpx.AsyncClient(timeout=8) as c:
|
| 24 |
+
r = await c.get(f"{KIMI_BASE}/v1/models", headers=auth_headers())
|
| 25 |
+
if r.status_code == 200:
|
| 26 |
+
return True, [m.get("id") for m in r.json().get("data", [])]
|
| 27 |
+
return False, f"HTTP {r.status_code}: {r.text[:200]}"
|
| 28 |
+
except Exception as e:
|
| 29 |
+
return False, str(e)
|
| 30 |
|
| 31 |
@app.get("/")
|
| 32 |
async def root():
|
| 33 |
+
if not os.environ.get("KIMI_API_KEY"):
|
| 34 |
+
alive, info = False, "KIMI_API_KEY secret not set"
|
| 35 |
+
else:
|
| 36 |
+
alive, info = await kimi_alive()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
color = "#00ff88" if alive else "#ff4444"
|
| 38 |
status = "ONLINE" if alive else "OFFLINE"
|
| 39 |
+
models = ", ".join(info) if isinstance(info, list) else info
|
| 40 |
return HTMLResponse(f"""<html><body style="font-family:monospace;padding:2rem;background:#0d1117;color:#c9d1d9">
|
| 41 |
<h2>WirelessAudit Proxy</h2>
|
| 42 |
+
<p>Backend: <code>Kimi K3</code> — <code>{KIMI_BASE}</code></p>
|
| 43 |
<p>Status: <b style="color:{color}">{status}</b></p>
|
| 44 |
+
<p>Models: <code>{models}</code></p>
|
|
|
|
| 45 |
<p>Cline Base URL: <code>/v1</code></p>
|
| 46 |
</body></html>""")
|
| 47 |
|
| 48 |
@app.get("/health")
|
| 49 |
async def health():
|
| 50 |
try:
|
| 51 |
+
get_key()
|
| 52 |
+
except ValueError as e:
|
|
|
|
|
|
|
| 53 |
return JSONResponse({"status": "offline", "error": str(e)}, status_code=503)
|
| 54 |
+
alive, info = await kimi_alive()
|
| 55 |
+
if alive:
|
| 56 |
+
return {"status": "ok", "backend": "kimi", "models": info}
|
| 57 |
+
return JSONResponse({"status": "offline", "error": info}, status_code=503)
|
| 58 |
|
| 59 |
@app.get("/v1/models")
|
| 60 |
async def models():
|
| 61 |
try:
|
|
|
|
| 62 |
async with httpx.AsyncClient(timeout=10) as c:
|
| 63 |
+
r = await c.get(f"{KIMI_BASE}/v1/models", headers=auth_headers())
|
| 64 |
+
return JSONResponse(r.json(), status_code=r.status_code)
|
| 65 |
+
except ValueError as e:
|
| 66 |
return JSONResponse({"error": str(e)}, status_code=503)
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return JSONResponse({"error": str(e)}, status_code=502)
|
| 69 |
|
| 70 |
@app.post("/v1/chat/completions")
|
| 71 |
async def chat(request: Request):
|
| 72 |
try:
|
| 73 |
+
headers = auth_headers()
|
| 74 |
except ValueError as e:
|
| 75 |
return JSONResponse({"error": str(e)}, status_code=503)
|
| 76 |
body = await request.json()
|
| 77 |
+
if not body.get("model"):
|
| 78 |
+
body["model"] = DEFAULT_MODEL
|
| 79 |
stream = body.get("stream", False)
|
| 80 |
+
url = f"{KIMI_BASE}/v1/chat/completions"
|
| 81 |
+
timeout = httpx.Timeout(300.0, connect=15.0)
|
| 82 |
try:
|
| 83 |
if stream:
|
| 84 |
+
c = httpx.AsyncClient(timeout=timeout)
|
| 85 |
+
req = c.build_request("POST", url, json=body, headers=headers)
|
| 86 |
+
r = await c.send(req, stream=True)
|
| 87 |
+
if r.status_code != 200:
|
| 88 |
+
err_body = await r.aread()
|
| 89 |
+
code = r.status_code
|
| 90 |
+
await r.aclose()
|
| 91 |
+
await c.aclose()
|
| 92 |
+
try:
|
| 93 |
+
payload = json.loads(err_body)
|
| 94 |
+
except Exception:
|
| 95 |
+
payload = {"error": {"message": err_body.decode(errors="replace"), "code": code}}
|
| 96 |
+
return JSONResponse(payload, status_code=code)
|
| 97 |
async def proxy():
|
| 98 |
+
try:
|
| 99 |
+
async for chunk in r.aiter_bytes():
|
| 100 |
+
yield chunk
|
| 101 |
+
finally:
|
| 102 |
+
await r.aclose()
|
| 103 |
+
await c.aclose()
|
| 104 |
return StreamingResponse(proxy(), media_type="text/event-stream",
|
| 105 |
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
| 106 |
+
async with httpx.AsyncClient(timeout=timeout) as c:
|
| 107 |
+
r = await c.post(url, json=body, headers=headers)
|
| 108 |
+
try:
|
| 109 |
+
return JSONResponse(r.json(), status_code=r.status_code)
|
| 110 |
+
except Exception:
|
| 111 |
+
return JSONResponse({"error": {"message": r.text, "code": r.status_code}},
|
| 112 |
+
status_code=r.status_code)
|
| 113 |
except httpx.ConnectError:
|
| 114 |
+
return JSONResponse({"error": {"message": "Kimi unreachable", "code": 503}}, status_code=503)
|
| 115 |
+
except httpx.ReadTimeout:
|
| 116 |
+
return JSONResponse({"error": {"message": "Kimi timed out", "code": 504}}, status_code=504)
|
| 117 |
except Exception as e:
|
| 118 |
return JSONResponse({"error": {"message": str(e)}}, status_code=500)
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
if __name__ == "__main__":
|
| 121 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|