Spaces:
Sleeping

PERDYPTO commited on
Commit
edd7530
·
verified ·
1 Parent(s): f8c98a8

Upload 7 files

Browse files
Files changed (4) hide show
  1. README.md +17 -5
  2. constants.py +26 -6
  3. main.py +213 -86
  4. reasoning_client.py +42 -30
README.md CHANGED
@@ -21,9 +21,21 @@ FastAPI microservice that synthesizes price, TA, and news data via DeepSeek V4 P
21
  - `NVIDIA_NIM_API_KEYS` (recommended) - One or more NVIDIA NIM API keys for DeepSeek V4 Pro. Separate keys with commas, spaces, semicolons, or new lines.
22
  - `NVIDIA_NIM_API_KEY` (fallback) - Single NVIDIA NIM API key. Used only when `NVIDIA_NIM_API_KEYS` is not set.
23
  - `NVIDIA_NIM_RATE_LIMIT_COOLDOWN_SECONDS` (optional) - How long to skip a key after it returns 429. Defaults to `3600`.
24
-
25
- ## Model
26
-
27
- - `deepseek-ai/deepseek-v4-pro` via NVIDIA NIM
28
- - Temperature: 0.1, Max tokens: 1024
 
 
 
 
 
 
 
 
 
 
 
 
29
  - Response: Strict JSON with 1m/15m/1h price predictions
 
21
  - `NVIDIA_NIM_API_KEYS` (recommended) - One or more NVIDIA NIM API keys for DeepSeek V4 Pro. Separate keys with commas, spaces, semicolons, or new lines.
22
  - `NVIDIA_NIM_API_KEY` (fallback) - Single NVIDIA NIM API key. Used only when `NVIDIA_NIM_API_KEYS` is not set.
23
  - `NVIDIA_NIM_RATE_LIMIT_COOLDOWN_SECONDS` (optional) - How long to skip a key after it returns 429. Defaults to `3600`.
24
+ - `GITHUB_MODELS_API_KEYS` (recommended) - One or more GitHub Models tokens with `models:read` permission. Separate multiple tokens with commas, spaces, semicolons, or new lines.
25
+ - `GITHUB_MODELS_API_KEY` or `GITHUB_TOKEN` (fallback) - Single GitHub Models token.
26
+ - `GITHUB_MODELS_MODEL` (optional) - Defaults to `deepseek/DeepSeek-R1-0528`.
27
+ - `GROQ_API_KEYS` (recommended) - One or more Groq API keys. Separate multiple keys with commas, spaces, semicolons, or new lines.
28
+ - `GROQ_API_KEY` (fallback) - Single Groq API key.
29
+ - `GROQ_MODEL` (optional) - Defaults to `openai/gpt-oss-120b`.
30
+ - `REASONING_PROVIDER_TIMEOUT_SECONDS` (optional) - Per-provider timeout before falling back to the next provider. Defaults to `90`.
31
+ - `REASONING_RATE_LIMIT_COOLDOWN_SECONDS` (optional) - Shared fallback cooldown for provider keys after 429s. Defaults to `3600`.
32
+
33
+ GitHub Models tokens must include `models:read`; GitHub may route model calls through a Microsoft service.
34
+
35
+ ## Model
36
+
37
+ - Primary: `deepseek-ai/deepseek-v4-pro` via NVIDIA NIM
38
+ - Fallback 1: GitHub Models via `https://models.github.ai/inference`
39
+ - Fallback 2: `openai/gpt-oss-120b` via Groq
40
+ - Temperature: 0.08, Max tokens: 16384
41
  - Response: Strict JSON with 1m/15m/1h price predictions
constants.py CHANGED
@@ -1,7 +1,27 @@
1
- NVIDIA_NIM_BASE_URL = "https://integrate.api.nvidia.com/v1"
2
- REASONING_MODEL = "deepseek-ai/deepseek-v4-pro"
3
- MAX_TOKENS = 16384
4
- TEMPERATURE = 0.08
5
- TOP_P = 0.95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  THINKING = True
7
- CACHE_TTL_SECONDS = 900
 
1
+ import os
2
+
3
+
4
+ def _load_positive_int(env_name: str, default: int) -> int:
5
+ raw_value = os.getenv(env_name, str(default))
6
+ try:
7
+ return max(1, int(raw_value))
8
+ except ValueError:
9
+ print(f"[WARN] Invalid {env_name}={raw_value!r}; using {default}")
10
+ return default
11
+
12
+
13
+ NVIDIA_NIM_BASE_URL = "https://integrate.api.nvidia.com/v1"
14
+ GITHUB_MODELS_BASE_URL = "https://models.github.ai/inference"
15
+ GROQ_BASE_URL = "https://api.groq.com/openai/v1"
16
+
17
+ NVIDIA_NIM_MODEL = os.getenv("NVIDIA_NIM_MODEL", "deepseek-ai/deepseek-v4-pro")
18
+ GITHUB_MODELS_MODEL = os.getenv("GITHUB_MODELS_MODEL", "deepseek/DeepSeek-R1-0528")
19
+ GROQ_MODEL = os.getenv("GROQ_MODEL", "openai/gpt-oss-120b")
20
+
21
+ REASONING_MODEL = NVIDIA_NIM_MODEL
22
+ REASONING_PROVIDER_TIMEOUT_SECONDS = _load_positive_int("REASONING_PROVIDER_TIMEOUT_SECONDS", 90)
23
+ MAX_TOKENS = 16384
24
+ TEMPERATURE = 0.08
25
+ TOP_P = 0.95
26
  THINKING = True
27
+ CACHE_TTL_SECONDS = 900
main.py CHANGED
@@ -3,18 +3,29 @@ import os
3
  import re
4
  import time
5
  from contextlib import asynccontextmanager
6
-
7
- import httpx
8
- from fastapi import FastAPI, HTTPException
9
- from fastapi.middleware.cors import CORSMiddleware
 
10
  from openai import AsyncOpenAI
11
 
12
- from constants import REASONING_MODEL, NVIDIA_NIM_BASE_URL
13
- from reasoning_client import NimRateLimitError, get_prediction
 
 
 
 
 
 
 
 
 
 
14
  from models import ReasoningRequest, ReasoningResponse, ErrorResponse
15
 
16
 
17
- def _parse_nim_api_keys(raw_value: str) -> list[str]:
18
  keys = [key.strip() for key in re.split(r"[\s,;]+", raw_value or "") if key.strip()]
19
  seen = set()
20
  unique_keys = []
@@ -25,44 +36,141 @@ def _parse_nim_api_keys(raw_value: str) -> list[str]:
25
  return unique_keys
26
 
27
 
28
- def _load_nim_api_keys() -> list[str]:
29
- key_pool = os.getenv("NVIDIA_NIM_API_KEYS", "")
30
  if key_pool.strip():
31
- return _parse_nim_api_keys(key_pool)
32
 
33
- single_key = os.getenv("NVIDIA_NIM_API_KEY", "")
34
- return _parse_nim_api_keys(single_key)
 
35
 
 
 
 
 
 
 
 
36
 
37
- def _load_rate_limit_cooldown_seconds() -> int:
38
- raw_value = os.getenv("NVIDIA_NIM_RATE_LIMIT_COOLDOWN_SECONDS", "3600")
 
39
  try:
40
  return max(1, int(raw_value))
41
  except ValueError:
42
- print(f"[WARN] Invalid NVIDIA_NIM_RATE_LIMIT_COOLDOWN_SECONDS={raw_value!r}; using 3600")
43
  return 3600
44
 
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  @asynccontextmanager
47
  async def lifespan(app: FastAPI):
48
- """Manage shared AsyncOpenAI clients for the NVIDIA NIM key pool."""
49
- api_keys = _load_nim_api_keys()
50
- if not api_keys:
51
- print("[WARN] NVIDIA_NIM_API_KEYS and NVIDIA_NIM_API_KEY are not set")
52
-
53
- app.state.openai_clients = [
54
- AsyncOpenAI(base_url=NVIDIA_NIM_BASE_URL, api_key=api_key)
55
- for api_key in api_keys
56
- ]
57
- app.state.nim_client_index = 0
58
- app.state.nim_key_blocked_until = [0.0 for _ in app.state.openai_clients]
59
- app.state.nim_rate_limit_cooldown_seconds = _load_rate_limit_cooldown_seconds()
60
- app.state.nim_client_lock = asyncio.Lock()
61
- app.state.http_client = httpx.AsyncClient(timeout=150.0)
62
- print(f"[INFO] NVIDIA NIM key pool initialized with {len(app.state.openai_clients)} key(s)")
63
  yield
64
- for client in app.state.openai_clients:
65
- await client.close()
66
  await app.state.http_client.aclose()
67
 
68
 
@@ -79,70 +187,89 @@ app.add_middleware(
79
 
80
  @app.get("/health")
81
  async def health_check():
82
- key_count = len(getattr(app.state, "openai_clients", []))
83
- now = time.time()
84
- blocked_until = getattr(app.state, "nim_key_blocked_until", [])
85
- blocked_count = sum(1 for blocked_time in blocked_until if blocked_time > now)
 
 
 
 
 
 
 
 
 
 
 
86
  return {
87
- "status": "ok" if key_count else "missing_config",
88
  "service": "reasoning-service",
89
  "model": REASONING_MODEL,
90
- "nim_keys_configured": key_count,
91
- "nim_keys_available": max(0, key_count - blocked_count),
92
- "nim_keys_in_cooldown": blocked_count
 
 
 
93
  }
94
 
95
 
96
- async def _next_openai_client() -> tuple[int, AsyncOpenAI] | None:
97
- clients = app.state.openai_clients
98
- if not clients:
99
- raise ValueError("NVIDIA_NIM_API_KEYS or NVIDIA_NIM_API_KEY not configured")
100
-
101
- now = time.time()
102
- async with app.state.nim_client_lock:
103
- for _ in range(len(clients)):
104
- client_index = app.state.nim_client_index % len(clients)
105
- app.state.nim_client_index += 1
106
- if app.state.nim_key_blocked_until[client_index] <= now:
107
- return client_index, clients[client_index]
108
-
109
- return None
110
-
111
-
112
- async def _mark_openai_client_rate_limited(client_index: int) -> None:
113
- blocked_until = time.time() + app.state.nim_rate_limit_cooldown_seconds
114
- async with app.state.nim_client_lock:
115
- app.state.nim_key_blocked_until[client_index] = max(
116
- app.state.nim_key_blocked_until[client_index],
117
- blocked_until
118
- )
119
-
120
-
121
- async def _get_prediction_with_key_pool(request: ReasoningRequest):
122
  last_rate_limit_error = None
123
- client_count = len(app.state.openai_clients)
124
  if client_count == 0:
125
- raise ValueError("NVIDIA_NIM_API_KEYS or NVIDIA_NIM_API_KEY not configured")
126
 
127
  for _ in range(client_count):
128
- next_client = await _next_openai_client()
129
  if next_client is None:
130
  break
131
 
132
  client_index, client = next_client
133
  try:
134
- return await get_prediction(request, client)
135
- except NimRateLimitError as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  last_rate_limit_error = e
137
- await _mark_openai_client_rate_limited(client_index)
138
- print(f"[WARN] NVIDIA NIM key #{client_index + 1} rate-limited for {request.symbol}; trying next key")
139
 
140
  raise ValueError(
141
- "All configured NVIDIA NIM keys are rate-limited or in cooldown. "
142
  f"Configured keys: {client_count}. "
143
- f"Cooldown seconds: {app.state.nim_rate_limit_cooldown_seconds}. "
144
  f"Last error: {last_rate_limit_error}"
145
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
 
148
  @app.post("/reason", response_model=ReasoningResponse)
@@ -151,17 +278,17 @@ async def reason(request: ReasoningRequest):
151
  start_time = time.time()
152
 
153
  try:
154
- prediction = await _get_prediction_with_key_pool(request)
155
-
156
- return ReasoningResponse(
157
- coin_id=request.coin_id,
158
- symbol=request.symbol,
159
- name=request.name,
160
- price_at_prediction=request.current_price,
161
- prediction=prediction,
162
- model_used=REASONING_MODEL,
163
- reasoning_time_ms=int((time.time() - start_time) * 1000)
164
- )
165
 
166
  except Exception as e:
167
  # Always print full error to stdout for debugging
 
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 = []
 
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
 
 
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)
 
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
reasoning_client.py CHANGED
@@ -11,8 +11,11 @@ from constants import (
11
  from models import ReasoningRequest, PredictionOutput
12
 
13
 
14
- class NimRateLimitError(RuntimeError):
15
- """Raised when a NIM API key has hit its provider rate limit."""
 
 
 
16
 
17
 
18
  SYSTEM_PROMPT = """You are an expert crypto market analyst and price predictor. You receive current price data, technical analysis and latest market news for a cryptocurrency. Synthesize all three and produce short term price predictions. You MUST respond in this exact JSON format and nothing else. No explanation before or after. No markdown. No code fences. Raw JSON only:
@@ -93,7 +96,7 @@ CURRENT PRICE: {req.current_price}
93
  24H CHANGE: {req.price_change_24h}%
94
  24H VOLUME: {req.volume_24h}
95
 
96
- SHORT-TERM TECHNICAL ANALYSIS (100 x 1m candles, about 100 minutes):
97
  Trend: {ta.trend}
98
  TA Confidence: {ta.confidence}
99
  RSI Signal: {ta.rsi_signal}
@@ -129,30 +132,39 @@ def _format_candle_context(candles) -> str:
129
  )
130
 
131
 
132
- async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> PredictionOutput:
133
- """Call NVIDIA NIM DeepSeek V4 Pro via AsyncOpenAI with streaming for structured price prediction."""
 
 
 
 
 
 
134
  if not client.api_key:
135
- raise ValueError("NVIDIA_NIM_API_KEYS or NVIDIA_NIM_API_KEY not configured")
136
-
137
- user_message = _build_user_message(request)
138
- start = time.time()
139
 
140
  # Retry loop wraps entire streaming + parsing to handle mid-stream failures
141
  for attempt in range(2):
142
- full_response = ""
143
- try:
144
- completion = await client.chat.completions.create(
145
- model=REASONING_MODEL,
146
- messages=[
147
- {"role": "system", "content": SYSTEM_PROMPT},
148
- {"role": "user", "content": user_message}
149
- ],
150
- temperature=TEMPERATURE,
151
- top_p=TOP_P,
152
- max_tokens=MAX_TOKENS,
153
- extra_body={"chat_template_kwargs": {"thinking": THINKING}},
154
- stream=True
155
- )
 
 
 
156
 
157
  # Collect full stream with interruption validation
158
  try:
@@ -164,7 +176,7 @@ async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> Pred
164
  full_response += delta
165
  except Exception as e:
166
  if is_rate_limit_error(e):
167
- raise NimRateLimitError(str(e)) from e
168
  raise ValueError(f"Stream interrupted after {len(full_response)} chars: {e}")
169
 
170
  # Validate non-empty response
@@ -178,18 +190,18 @@ async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> Pred
178
 
179
  parsed = json.loads(cleaned)
180
 
181
- elapsed_ms = int((time.time() - start) * 1000)
182
- print(f"[INFO] Prediction for {request.symbol} generated in {elapsed_ms}ms")
183
-
184
  return PredictionOutput(**parsed)
185
 
186
- except NimRateLimitError:
187
  raise
188
  except Exception as e:
189
  if is_rate_limit_error(e):
190
- raise NimRateLimitError(str(e)) from e
191
  if attempt == 1:
192
- print(f"[ERROR] NVIDIA NIM call failed after retry for {request.symbol}: {e}")
193
  raise ValueError(f"All retries exhausted. Last error: {e}. Raw response: {full_response[:500]}")
194
  print(f"[WARN] Attempt {attempt + 1} failed: {e}, retrying...")
195
  await asyncio.sleep(0.5 * (2 ** attempt))
 
11
  from models import ReasoningRequest, PredictionOutput
12
 
13
 
14
+ class ProviderRateLimitError(RuntimeError):
15
+ """Raised when a reasoning provider API key has hit its rate limit."""
16
+
17
+
18
+ NimRateLimitError = ProviderRateLimitError
19
 
20
 
21
  SYSTEM_PROMPT = """You are an expert crypto market analyst and price predictor. You receive current price data, technical analysis and latest market news for a cryptocurrency. Synthesize all three and produce short term price predictions. You MUST respond in this exact JSON format and nothing else. No explanation before or after. No markdown. No code fences. Raw JSON only:
 
96
  24H CHANGE: {req.price_change_24h}%
97
  24H VOLUME: {req.volume_24h}
98
 
99
+ SHORT-TERM TECHNICAL ANALYSIS (200 x 1m candles, about 200 minutes):
100
  Trend: {ta.trend}
101
  TA Confidence: {ta.confidence}
102
  RSI Signal: {ta.rsi_signal}
 
132
  )
133
 
134
 
135
+ async def get_prediction(
136
+ request: ReasoningRequest,
137
+ client: AsyncOpenAI,
138
+ model: str = REASONING_MODEL,
139
+ provider_name: str = "NVIDIA NIM",
140
+ enable_thinking: bool = THINKING
141
+ ) -> PredictionOutput:
142
+ """Call a reasoning model via AsyncOpenAI streaming for structured price prediction."""
143
  if not client.api_key:
144
+ raise ValueError(f"{provider_name} API key not configured")
145
+
146
+ user_message = _build_user_message(request)
147
+ start = time.time()
148
 
149
  # Retry loop wraps entire streaming + parsing to handle mid-stream failures
150
  for attempt in range(2):
151
+ full_response = ""
152
+ try:
153
+ completion_kwargs = {
154
+ "model": model,
155
+ "messages": [
156
+ {"role": "system", "content": SYSTEM_PROMPT},
157
+ {"role": "user", "content": user_message}
158
+ ],
159
+ "temperature": TEMPERATURE,
160
+ "top_p": TOP_P,
161
+ "max_tokens": MAX_TOKENS,
162
+ "stream": True
163
+ }
164
+ if enable_thinking:
165
+ completion_kwargs["extra_body"] = {"chat_template_kwargs": {"thinking": THINKING}}
166
+
167
+ completion = await client.chat.completions.create(**completion_kwargs)
168
 
169
  # Collect full stream with interruption validation
170
  try:
 
176
  full_response += delta
177
  except Exception as e:
178
  if is_rate_limit_error(e):
179
+ raise ProviderRateLimitError(str(e)) from e
180
  raise ValueError(f"Stream interrupted after {len(full_response)} chars: {e}")
181
 
182
  # Validate non-empty response
 
190
 
191
  parsed = json.loads(cleaned)
192
 
193
+ elapsed_ms = int((time.time() - start) * 1000)
194
+ print(f"[INFO] Prediction for {request.symbol} generated by {provider_name} ({model}) in {elapsed_ms}ms")
195
+
196
  return PredictionOutput(**parsed)
197
 
198
+ except ProviderRateLimitError:
199
  raise
200
  except Exception as e:
201
  if is_rate_limit_error(e):
202
+ raise ProviderRateLimitError(str(e)) from e
203
  if attempt == 1:
204
+ print(f"[ERROR] {provider_name} call failed after retry for {request.symbol}: {e}")
205
  raise ValueError(f"All retries exhausted. Last error: {e}. Raw response: {full_response[:500]}")
206
  print(f"[WARN] Attempt {attempt + 1} failed: {e}, retrying...")
207
  await asyncio.sleep(0.5 * (2 ** attempt))