PERDYPTO commited on
Rename main.py to app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import time
|
| 4 |
+
from huggingface_hub import login, create_bucket, download_bucket_files, batch_bucket_files
|
| 5 |
+
|
| 6 |
+
def do_copy():
|
| 7 |
+
print("--- Starting HF Internal Bucket Copy ---")
|
| 8 |
+
|
| 9 |
+
# 1. Authenticate
|
| 10 |
+
token = os.environ.get("HF_TOKEN")
|
| 11 |
+
if not token:
|
| 12 |
+
print("❌ ERROR: HF_TOKEN secret not found in Space settings!")
|
| 13 |
+
return False
|
| 14 |
+
|
| 15 |
+
login(token=token, add_to_git_credential=False)
|
| 16 |
+
|
| 17 |
+
SOURCE_BUCKET = "PERDYPTO/db_snapshot"
|
| 18 |
+
DEST_BUCKET = "PERDYPTO/sdafasdf-storage"
|
| 19 |
+
FILENAME = "github_pipeline.db"
|
| 20 |
+
|
| 21 |
+
print(f"Ensuring destination bucket {DEST_BUCKET} exists...")
|
| 22 |
+
create_bucket(DEST_BUCKET, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
# 2. Temporary directory inside the Space's container
|
| 25 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 26 |
+
local_file_path = os.path.join(tmp_dir, FILENAME)
|
| 27 |
+
|
| 28 |
+
print(f"Downloading {FILENAME} from {SOURCE_BUCKET} into Space memory...")
|
| 29 |
+
download_bucket_files(SOURCE_BUCKET, files=[(FILENAME, local_file_path)])
|
| 30 |
+
|
| 31 |
+
print(f"Uploading {FILENAME} to {DEST_BUCKET}...")
|
| 32 |
+
# Because of Xet deduplication, this upload will be near-instant
|
| 33 |
+
batch_bucket_files(DEST_BUCKET, add=[(local_file_path, FILENAME)])
|
| 34 |
+
|
| 35 |
+
print("✅ Copy complete successfully!")
|
| 36 |
+
return True
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
try:
|
| 40 |
+
do_copy()
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"❌ Copy failed: {e}")
|
| 43 |
+
|
| 44 |
+
# Keep the Space running so it doesn't restart and loop the copy
|
| 45 |
+
print("Holding Space alive for 1 hour so you can read the logs...")
|
| 46 |
+
time.sleep(3600)
|
main.py
DELETED
|
@@ -1,299 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import os
|
| 3 |
-
import re
|
| 4 |
-
import time
|
| 5 |
-
from contextlib import asynccontextmanager
|
| 6 |
-
from dataclasses import dataclass, field
|
| 7 |
-
|
| 8 |
-
import httpx
|
| 9 |
-
from fastapi import FastAPI, HTTPException
|
| 10 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
-
from openai import AsyncOpenAI
|
| 12 |
-
|
| 13 |
-
from constants import (
|
| 14 |
-
REASONING_MODEL,
|
| 15 |
-
REASONING_PROVIDER_TIMEOUT_SECONDS,
|
| 16 |
-
NVIDIA_NIM_BASE_URL,
|
| 17 |
-
NVIDIA_NIM_MODEL,
|
| 18 |
-
GITHUB_MODELS_BASE_URL,
|
| 19 |
-
GITHUB_MODELS_MODEL,
|
| 20 |
-
GROQ_BASE_URL,
|
| 21 |
-
GROQ_MODEL,
|
| 22 |
-
THINKING,
|
| 23 |
-
)
|
| 24 |
-
from reasoning_client import ProviderRateLimitError, get_prediction
|
| 25 |
-
from models import ReasoningRequest, ReasoningResponse, ErrorResponse
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def _parse_api_keys(raw_value: str) -> list[str]:
|
| 29 |
-
keys = [key.strip() for key in re.split(r"[\s,;]+", raw_value or "") if key.strip()]
|
| 30 |
-
seen = set()
|
| 31 |
-
unique_keys = []
|
| 32 |
-
for key in keys:
|
| 33 |
-
if key not in seen:
|
| 34 |
-
seen.add(key)
|
| 35 |
-
unique_keys.append(key)
|
| 36 |
-
return unique_keys
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _load_api_keys(pool_env: str, single_envs: list[str]) -> list[str]:
|
| 40 |
-
key_pool = os.getenv(pool_env, "")
|
| 41 |
-
if key_pool.strip():
|
| 42 |
-
return _parse_api_keys(key_pool)
|
| 43 |
-
|
| 44 |
-
keys = []
|
| 45 |
-
for env_name in single_envs:
|
| 46 |
-
keys.extend(_parse_api_keys(os.getenv(env_name, "")))
|
| 47 |
-
|
| 48 |
-
seen = set()
|
| 49 |
-
unique_keys = []
|
| 50 |
-
for key in keys:
|
| 51 |
-
if key not in seen:
|
| 52 |
-
seen.add(key)
|
| 53 |
-
unique_keys.append(key)
|
| 54 |
-
return unique_keys
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _load_rate_limit_cooldown_seconds(env_name: str) -> int:
|
| 58 |
-
raw_value = os.getenv(env_name, os.getenv("REASONING_RATE_LIMIT_COOLDOWN_SECONDS", "3600"))
|
| 59 |
-
try:
|
| 60 |
-
return max(1, int(raw_value))
|
| 61 |
-
except ValueError:
|
| 62 |
-
print(f"[WARN] Invalid {env_name}={raw_value!r}; using 3600")
|
| 63 |
-
return 3600
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
@dataclass
|
| 67 |
-
class ReasoningProviderPool:
|
| 68 |
-
name: str
|
| 69 |
-
slug: str
|
| 70 |
-
base_url: str
|
| 71 |
-
model: str
|
| 72 |
-
api_keys: list[str]
|
| 73 |
-
enable_thinking: bool = False
|
| 74 |
-
rate_limit_cooldown_seconds: int = 3600
|
| 75 |
-
clients: list[AsyncOpenAI] = field(init=False)
|
| 76 |
-
client_index: int = 0
|
| 77 |
-
key_blocked_until: list[float] = field(init=False)
|
| 78 |
-
client_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
| 79 |
-
|
| 80 |
-
def __post_init__(self):
|
| 81 |
-
self.clients = [
|
| 82 |
-
AsyncOpenAI(
|
| 83 |
-
base_url=self.base_url,
|
| 84 |
-
api_key=api_key,
|
| 85 |
-
timeout=REASONING_PROVIDER_TIMEOUT_SECONDS
|
| 86 |
-
)
|
| 87 |
-
for api_key in self.api_keys
|
| 88 |
-
]
|
| 89 |
-
self.key_blocked_until = [0.0 for _ in self.clients]
|
| 90 |
-
|
| 91 |
-
@property
|
| 92 |
-
def configured_count(self) -> int:
|
| 93 |
-
return len(self.clients)
|
| 94 |
-
|
| 95 |
-
def available_count(self) -> int:
|
| 96 |
-
now = time.time()
|
| 97 |
-
return sum(1 for blocked_time in self.key_blocked_until if blocked_time <= now)
|
| 98 |
-
|
| 99 |
-
async def next_client(self) -> tuple[int, AsyncOpenAI] | None:
|
| 100 |
-
if not self.clients:
|
| 101 |
-
return None
|
| 102 |
-
|
| 103 |
-
now = time.time()
|
| 104 |
-
async with self.client_lock:
|
| 105 |
-
for _ in range(len(self.clients)):
|
| 106 |
-
client_index = self.client_index % len(self.clients)
|
| 107 |
-
self.client_index += 1
|
| 108 |
-
if self.key_blocked_until[client_index] <= now:
|
| 109 |
-
return client_index, self.clients[client_index]
|
| 110 |
-
|
| 111 |
-
return None
|
| 112 |
-
|
| 113 |
-
async def mark_rate_limited(self, client_index: int) -> None:
|
| 114 |
-
blocked_until = time.time() + self.rate_limit_cooldown_seconds
|
| 115 |
-
async with self.client_lock:
|
| 116 |
-
self.key_blocked_until[client_index] = max(
|
| 117 |
-
self.key_blocked_until[client_index],
|
| 118 |
-
blocked_until
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
async def close(self) -> None:
|
| 122 |
-
for client in self.clients:
|
| 123 |
-
await client.close()
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def _build_provider_pools() -> list[ReasoningProviderPool]:
|
| 127 |
-
return [
|
| 128 |
-
ReasoningProviderPool(
|
| 129 |
-
name="NVIDIA NIM",
|
| 130 |
-
slug="nvidia",
|
| 131 |
-
base_url=NVIDIA_NIM_BASE_URL,
|
| 132 |
-
model=NVIDIA_NIM_MODEL,
|
| 133 |
-
api_keys=_load_api_keys("NVIDIA_NIM_API_KEYS", ["NVIDIA_NIM_API_KEY"]),
|
| 134 |
-
enable_thinking=THINKING,
|
| 135 |
-
rate_limit_cooldown_seconds=_load_rate_limit_cooldown_seconds("NVIDIA_NIM_RATE_LIMIT_COOLDOWN_SECONDS"),
|
| 136 |
-
),
|
| 137 |
-
ReasoningProviderPool(
|
| 138 |
-
name="GitHub Models",
|
| 139 |
-
slug="github",
|
| 140 |
-
base_url=GITHUB_MODELS_BASE_URL,
|
| 141 |
-
model=GITHUB_MODELS_MODEL,
|
| 142 |
-
api_keys=_load_api_keys("GITHUB_MODELS_API_KEYS", ["GITHUB_MODELS_API_KEY", "GITHUB_TOKEN"]),
|
| 143 |
-
enable_thinking=False,
|
| 144 |
-
rate_limit_cooldown_seconds=_load_rate_limit_cooldown_seconds("GITHUB_MODELS_RATE_LIMIT_COOLDOWN_SECONDS"),
|
| 145 |
-
),
|
| 146 |
-
ReasoningProviderPool(
|
| 147 |
-
name="Groq",
|
| 148 |
-
slug="groq",
|
| 149 |
-
base_url=GROQ_BASE_URL,
|
| 150 |
-
model=GROQ_MODEL,
|
| 151 |
-
api_keys=_load_api_keys("GROQ_API_KEYS", ["GROQ_API_KEY"]),
|
| 152 |
-
enable_thinking=False,
|
| 153 |
-
rate_limit_cooldown_seconds=_load_rate_limit_cooldown_seconds("GROQ_RATE_LIMIT_COOLDOWN_SECONDS"),
|
| 154 |
-
),
|
| 155 |
-
]
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
@asynccontextmanager
|
| 159 |
-
async def lifespan(app: FastAPI):
|
| 160 |
-
"""Manage shared reasoning provider key pools."""
|
| 161 |
-
app.state.reasoning_provider_pools = _build_provider_pools()
|
| 162 |
-
app.state.openai_clients = app.state.reasoning_provider_pools[0].clients
|
| 163 |
-
app.state.http_client = httpx.AsyncClient(timeout=REASONING_PROVIDER_TIMEOUT_SECONDS)
|
| 164 |
-
|
| 165 |
-
configured_total = sum(pool.configured_count for pool in app.state.reasoning_provider_pools)
|
| 166 |
-
if configured_total == 0:
|
| 167 |
-
print("[WARN] No reasoning provider API keys are configured")
|
| 168 |
-
for pool in app.state.reasoning_provider_pools:
|
| 169 |
-
print(f"[INFO] {pool.name} key pool initialized with {pool.configured_count} key(s)")
|
| 170 |
-
|
| 171 |
-
yield
|
| 172 |
-
for pool in app.state.reasoning_provider_pools:
|
| 173 |
-
await pool.close()
|
| 174 |
-
await app.state.http_client.aclose()
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
app = FastAPI(title="Perdypto Reasoning Service", lifespan=lifespan)
|
| 178 |
-
|
| 179 |
-
app.add_middleware(
|
| 180 |
-
CORSMiddleware,
|
| 181 |
-
allow_origins=["*"],
|
| 182 |
-
allow_credentials=True,
|
| 183 |
-
allow_methods=["*"],
|
| 184 |
-
allow_headers=["*"],
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
@app.get("/health")
|
| 189 |
-
async def health_check():
|
| 190 |
-
pools = getattr(app.state, "reasoning_provider_pools", [])
|
| 191 |
-
provider_health = {}
|
| 192 |
-
for pool in pools:
|
| 193 |
-
blocked_count = pool.configured_count - pool.available_count()
|
| 194 |
-
provider_health[pool.slug] = {
|
| 195 |
-
"name": pool.name,
|
| 196 |
-
"model": pool.model,
|
| 197 |
-
"keys_configured": pool.configured_count,
|
| 198 |
-
"keys_available": pool.available_count(),
|
| 199 |
-
"keys_in_cooldown": blocked_count,
|
| 200 |
-
"rate_limit_cooldown_seconds": pool.rate_limit_cooldown_seconds,
|
| 201 |
-
}
|
| 202 |
-
|
| 203 |
-
nvidia_health = provider_health.get("nvidia", {})
|
| 204 |
-
configured_total = sum(pool.configured_count for pool in pools)
|
| 205 |
-
return {
|
| 206 |
-
"status": "ok" if configured_total else "missing_config",
|
| 207 |
-
"service": "reasoning-service",
|
| 208 |
-
"model": REASONING_MODEL,
|
| 209 |
-
"fallback_order": [pool.slug for pool in pools],
|
| 210 |
-
"provider_timeout_seconds": REASONING_PROVIDER_TIMEOUT_SECONDS,
|
| 211 |
-
"providers": provider_health,
|
| 212 |
-
"nim_keys_configured": nvidia_health.get("keys_configured", 0),
|
| 213 |
-
"nim_keys_available": nvidia_health.get("keys_available", 0),
|
| 214 |
-
"nim_keys_in_cooldown": nvidia_health.get("keys_in_cooldown", 0),
|
| 215 |
-
}
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
async def _get_prediction_with_provider(request: ReasoningRequest, pool: ReasoningProviderPool):
|
| 219 |
-
last_rate_limit_error = None
|
| 220 |
-
client_count = pool.configured_count
|
| 221 |
-
if client_count == 0:
|
| 222 |
-
raise ValueError(f"{pool.name} API keys not configured")
|
| 223 |
-
|
| 224 |
-
for _ in range(client_count):
|
| 225 |
-
next_client = await pool.next_client()
|
| 226 |
-
if next_client is None:
|
| 227 |
-
break
|
| 228 |
-
|
| 229 |
-
client_index, client = next_client
|
| 230 |
-
try:
|
| 231 |
-
return await asyncio.wait_for(
|
| 232 |
-
get_prediction(
|
| 233 |
-
request,
|
| 234 |
-
client,
|
| 235 |
-
model=pool.model,
|
| 236 |
-
provider_name=pool.name,
|
| 237 |
-
enable_thinking=pool.enable_thinking,
|
| 238 |
-
),
|
| 239 |
-
timeout=REASONING_PROVIDER_TIMEOUT_SECONDS
|
| 240 |
-
)
|
| 241 |
-
except asyncio.TimeoutError as e:
|
| 242 |
-
raise TimeoutError(
|
| 243 |
-
f"{pool.name} timed out after {REASONING_PROVIDER_TIMEOUT_SECONDS}s"
|
| 244 |
-
) from e
|
| 245 |
-
except ProviderRateLimitError as e:
|
| 246 |
-
last_rate_limit_error = e
|
| 247 |
-
await pool.mark_rate_limited(client_index)
|
| 248 |
-
print(f"[WARN] {pool.name} key #{client_index + 1} rate-limited for {request.symbol}; trying next key")
|
| 249 |
-
|
| 250 |
-
raise ValueError(
|
| 251 |
-
f"All configured {pool.name} keys are rate-limited or in cooldown. "
|
| 252 |
-
f"Configured keys: {client_count}. "
|
| 253 |
-
f"Cooldown seconds: {pool.rate_limit_cooldown_seconds}. "
|
| 254 |
-
f"Last error: {last_rate_limit_error}"
|
| 255 |
-
)
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
async def _get_prediction_with_fallback(request: ReasoningRequest):
|
| 259 |
-
failures = []
|
| 260 |
-
for pool in app.state.reasoning_provider_pools:
|
| 261 |
-
if pool.configured_count == 0:
|
| 262 |
-
failures.append(f"{pool.name}: no API keys configured")
|
| 263 |
-
continue
|
| 264 |
-
|
| 265 |
-
try:
|
| 266 |
-
prediction = await _get_prediction_with_provider(request, pool)
|
| 267 |
-
return prediction, f"{pool.name} / {pool.model}"
|
| 268 |
-
except Exception as e:
|
| 269 |
-
failures.append(f"{pool.name}: {e}")
|
| 270 |
-
print(f"[WARN] {pool.name} failed for {request.symbol}: {e}; trying fallback provider")
|
| 271 |
-
|
| 272 |
-
raise ValueError("All reasoning providers failed. " + " | ".join(failures))
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
@app.post("/reason", response_model=ReasoningResponse)
|
| 276 |
-
async def reason(request: ReasoningRequest):
|
| 277 |
-
"""Generate structured price prediction from combined TA + news + price data."""
|
| 278 |
-
start_time = time.time()
|
| 279 |
-
|
| 280 |
-
try:
|
| 281 |
-
prediction, model_used = await _get_prediction_with_fallback(request)
|
| 282 |
-
|
| 283 |
-
return ReasoningResponse(
|
| 284 |
-
coin_id=request.coin_id,
|
| 285 |
-
symbol=request.symbol,
|
| 286 |
-
name=request.name,
|
| 287 |
-
price_at_prediction=request.current_price,
|
| 288 |
-
prediction=prediction,
|
| 289 |
-
model_used=model_used,
|
| 290 |
-
reasoning_time_ms=int((time.time() - start_time) * 1000)
|
| 291 |
-
)
|
| 292 |
-
|
| 293 |
-
except Exception as e:
|
| 294 |
-
# Always print full error to stdout for debugging
|
| 295 |
-
print(f"[ERROR] /reason failed for {request.symbol}: {e}")
|
| 296 |
-
raise HTTPException(
|
| 297 |
-
status_code=503,
|
| 298 |
-
detail=ErrorResponse(error="Prediction generation failed", detail=str(e)).model_dump()
|
| 299 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|