Spaces:
Sleeping

PERDYPTO commited on
Commit
0791913
·
verified ·
1 Parent(s): ad1ba00

Upload 7 files

Browse files
Files changed (4) hide show
  1. README.md +6 -4
  2. main.py +133 -32
  3. models.py +3 -3
  4. reasoning_client.py +68 -43
README.md CHANGED
@@ -16,12 +16,14 @@ FastAPI microservice that synthesizes price, TA, and news data via DeepSeek V4 P
16
  - `POST /reason` - Generate prediction from combined inputs
17
  - `GET /health` - Health check with model info
18
 
19
- ## Environment Variables
20
-
21
- - `NVIDIA_NIM_API_KEY` (required) - NVIDIA NIM API key for DeepSeek V4 Pro
 
 
22
 
23
  ## Model
24
 
25
  - `deepseek-ai/deepseek-v4-pro` via NVIDIA NIM
26
  - Temperature: 0.1, Max tokens: 1024
27
- - Response: Strict JSON with 1m/15m/1h price predictions
 
16
  - `POST /reason` - Generate prediction from combined inputs
17
  - `GET /health` - Health check with model info
18
 
19
+ ## Environment Variables
20
+
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
main.py CHANGED
@@ -1,31 +1,69 @@
1
- import os
2
- import time
3
- from contextlib import asynccontextmanager
 
 
4
 
5
  import httpx
6
  from fastapi import FastAPI, HTTPException
7
  from fastapi.middleware.cors import CORSMiddleware
8
- from openai import AsyncOpenAI
9
-
10
- from constants import REASONING_MODEL, NVIDIA_NIM_BASE_URL
11
- from reasoning_client import get_prediction
12
- from models import ReasoningRequest, ReasoningResponse, ErrorResponse
13
-
14
-
15
- @asynccontextmanager
16
- async def lifespan(app: FastAPI):
17
- """Manage shared AsyncOpenAI client for NVIDIA NIM with 150s timeout."""
18
- api_key = os.getenv("NVIDIA_NIM_API_KEY")
19
- if not api_key:
20
- print("[WARN] NVIDIA_NIM_API_KEY not set")
21
- app.state.openai_client = AsyncOpenAI(
22
- base_url=NVIDIA_NIM_BASE_URL,
23
- api_key=api_key
24
- )
25
- app.state.http_client = httpx.AsyncClient(timeout=150.0)
26
- yield
27
- await app.state.openai_client.close()
28
- await app.state.http_client.aclose()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  app = FastAPI(title="Perdypto Reasoning Service", lifespan=lifespan)
@@ -39,18 +77,81 @@ app.add_middleware(
39
  )
40
 
41
 
42
- @app.get("/health")
43
- async def health_check():
44
- return {"status": "ok", "service": "reasoning-service", "model": REASONING_MODEL}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
  @app.post("/reason", response_model=ReasoningResponse)
48
  async def reason(request: ReasoningRequest):
49
  """Generate structured price prediction from combined TA + news + price data."""
50
- start_time = time.time()
51
-
52
- try:
53
- prediction = await get_prediction(request, app.state.openai_client)
54
 
55
  return ReasoningResponse(
56
  coin_id=request.coin_id,
@@ -68,4 +169,4 @@ async def reason(request: ReasoningRequest):
68
  raise HTTPException(
69
  status_code=503,
70
  detail=ErrorResponse(error="Prediction generation failed", detail=str(e)).model_dump()
71
- )
 
1
+ import asyncio
2
+ 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 = []
21
+ for key in keys:
22
+ if key not in seen:
23
+ seen.add(key)
24
+ unique_keys.append(key)
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
 
69
  app = FastAPI(title="Perdypto Reasoning Service", lifespan=lifespan)
 
77
  )
78
 
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)
149
  async def reason(request: ReasoningRequest):
150
  """Generate structured price prediction from combined TA + news + price data."""
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,
 
169
  raise HTTPException(
170
  status_code=503,
171
  detail=ErrorResponse(error="Prediction generation failed", detail=str(e)).model_dump()
172
+ )
models.py CHANGED
@@ -54,8 +54,8 @@ class PredictionOutput(BaseModel):
54
  news_summary: str
55
 
56
 
57
- class ReasoningResponse(BaseModel):
58
- model_config = ConfigDict(from_attributes=True)
59
 
60
  coin_id: str
61
  symbol: str
@@ -70,4 +70,4 @@ class ErrorResponse(BaseModel):
70
  model_config = ConfigDict(from_attributes=True)
71
 
72
  error: str
73
- detail: Optional[str]
 
54
  news_summary: str
55
 
56
 
57
+ class ReasoningResponse(BaseModel):
58
+ model_config = ConfigDict(from_attributes=True, protected_namespaces=())
59
 
60
  coin_id: str
61
  symbol: str
 
70
  model_config = ConfigDict(from_attributes=True)
71
 
72
  error: str
73
+ detail: Optional[str]
reasoning_client.py CHANGED
@@ -1,31 +1,50 @@
1
- import asyncio
2
- import json
3
- import os
4
- import re
5
- import time
6
-
7
- from openai import AsyncOpenAI
8
-
9
- from constants import (
10
- NVIDIA_NIM_BASE_URL, REASONING_MODEL,
11
- MAX_TOKENS, TEMPERATURE, TOP_P, THINKING
12
- )
13
- from models import ReasoningRequest, PredictionOutput
14
-
15
-
16
- 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:
17
- {
18
- "predicted_1m": <float price>,
 
 
19
  "predicted_15m": <float price>,
20
  "predicted_1h": <float price>,
21
  "confidence_score": <float between 0.0 and 1.0>,
22
  "reasoning": "<2-3 sentences combining TA + news + price action>",
23
  "ta_summary": "<one sentence TA conclusion>",
24
  "news_summary": "<one sentence news conclusion>"
25
- }"""
26
-
27
-
28
- def _build_user_message(req: ReasoningRequest) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  ta = req.ta_result
30
  news = req.news_summary
31
  return f"""COIN: {req.symbol} ({req.name})
@@ -58,10 +77,10 @@ def _strip_markdown(text: str) -> str:
58
  return text.strip()
59
 
60
 
61
- async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> PredictionOutput:
62
- """Call NVIDIA NIM DeepSeek V4 Pro via AsyncOpenAI with streaming for structured price prediction."""
63
- if not client.api_key:
64
- raise ValueError("NVIDIA_NIM_API_KEY not configured")
65
 
66
  user_message = _build_user_message(request)
67
  start = time.time()
@@ -83,16 +102,18 @@ async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> Pred
83
  stream=True
84
  )
85
 
86
- # Collect full stream with interruption validation
87
- try:
88
- async for chunk in completion:
89
- if not getattr(chunk, "choices", None):
90
- continue
91
- delta = chunk.choices[0].delta.content
92
- if delta is not None:
93
- full_response += delta
94
- except Exception as e:
95
- raise ValueError(f"Stream interrupted after {len(full_response)} chars: {e}")
 
 
96
 
97
  # Validate non-empty response
98
  if not full_response.strip():
@@ -108,15 +129,19 @@ async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> Pred
108
  elapsed_ms = int((time.time() - start) * 1000)
109
  print(f"[INFO] Prediction for {request.symbol} generated in {elapsed_ms}ms")
110
 
111
- return PredictionOutput(**parsed)
112
-
113
- except Exception as e:
114
- if attempt == 1:
115
- print(f"[ERROR] NVIDIA NIM call failed after retry for {request.symbol}: {e}")
116
- raise ValueError(f"All retries exhausted. Last error: {e}. Raw response: {full_response[:500]}")
 
 
 
 
117
  print(f"[WARN] Attempt {attempt + 1} failed: {e}, retrying...")
118
  await asyncio.sleep(0.5 * (2 ** attempt))
119
  # full_response reset at start of next loop iteration
120
 
121
  # Should not reach here
122
- raise ValueError("Prediction failed: unexpected retry loop exit")
 
1
+ import asyncio
2
+ import json
3
+ import re
4
+ import time
5
+
6
+ from openai import AsyncOpenAI
7
+
8
+ from constants import (
9
+ REASONING_MODEL, MAX_TOKENS, TEMPERATURE, TOP_P, THINKING
10
+ )
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:
19
+ {
20
+ "predicted_1m": <float price>,
21
  "predicted_15m": <float price>,
22
  "predicted_1h": <float price>,
23
  "confidence_score": <float between 0.0 and 1.0>,
24
  "reasoning": "<2-3 sentences combining TA + news + price action>",
25
  "ta_summary": "<one sentence TA conclusion>",
26
  "news_summary": "<one sentence news conclusion>"
27
+ }"""
28
+
29
+
30
+ def is_rate_limit_error(exc: Exception) -> bool:
31
+ status_code = getattr(exc, "status_code", None)
32
+ response = getattr(exc, "response", None)
33
+ response_status = getattr(response, "status_code", None)
34
+ if status_code == 429 or response_status == 429:
35
+ return True
36
+
37
+ message = str(exc).lower()
38
+ return (
39
+ "too many requests" in message
40
+ or "rate limit" in message
41
+ or "error code: 429" in message
42
+ or "status': 429" in message
43
+ or '"status": 429' in message
44
+ )
45
+
46
+
47
+ def _build_user_message(req: ReasoningRequest) -> str:
48
  ta = req.ta_result
49
  news = req.news_summary
50
  return f"""COIN: {req.symbol} ({req.name})
 
77
  return text.strip()
78
 
79
 
80
+ async def get_prediction(request: ReasoningRequest, client: AsyncOpenAI) -> PredictionOutput:
81
+ """Call NVIDIA NIM DeepSeek V4 Pro via AsyncOpenAI with streaming for structured price prediction."""
82
+ if not client.api_key:
83
+ raise ValueError("NVIDIA_NIM_API_KEYS or NVIDIA_NIM_API_KEY not configured")
84
 
85
  user_message = _build_user_message(request)
86
  start = time.time()
 
102
  stream=True
103
  )
104
 
105
+ # Collect full stream with interruption validation
106
+ try:
107
+ async for chunk in completion:
108
+ if not getattr(chunk, "choices", None):
109
+ continue
110
+ delta = chunk.choices[0].delta.content
111
+ if delta is not None:
112
+ full_response += delta
113
+ except Exception as e:
114
+ if is_rate_limit_error(e):
115
+ raise NimRateLimitError(str(e)) from e
116
+ raise ValueError(f"Stream interrupted after {len(full_response)} chars: {e}")
117
 
118
  # Validate non-empty response
119
  if not full_response.strip():
 
129
  elapsed_ms = int((time.time() - start) * 1000)
130
  print(f"[INFO] Prediction for {request.symbol} generated in {elapsed_ms}ms")
131
 
132
+ return PredictionOutput(**parsed)
133
+
134
+ except NimRateLimitError:
135
+ raise
136
+ except Exception as e:
137
+ if is_rate_limit_error(e):
138
+ raise NimRateLimitError(str(e)) from e
139
+ if attempt == 1:
140
+ print(f"[ERROR] NVIDIA NIM call failed after retry for {request.symbol}: {e}")
141
+ raise ValueError(f"All retries exhausted. Last error: {e}. Raw response: {full_response[:500]}")
142
  print(f"[WARN] Attempt {attempt + 1} failed: {e}, retrying...")
143
  await asyncio.sleep(0.5 * (2 ** attempt))
144
  # full_response reset at start of next loop iteration
145
 
146
  # Should not reach here
147
+ raise ValueError("Prediction failed: unexpected retry loop exit")