Spaces:
Sleeping

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

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +15 -0
  2. README.md +27 -11
  3. constants.py +7 -0
  4. main.py +71 -0
  5. models.py +73 -0
  6. reasoning_client.py +122 -0
  7. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN useradd -m -u 1000 user
4
+ ENV HOME=/home/user
5
+ ENV PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR /home/user/app
7
+
8
+ COPY --chown=user:user requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY --chown=user:user . .
12
+
13
+ EXPOSE 7860
14
+
15
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,11 +1,27 @@
1
- ---
2
- title: Reasoning Service
3
- emoji: 🦀
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: docker
7
- pinned: false
8
- short_description: This is the reasoning service for Perdypto
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Perdypto Reasoning Service
3
+ emoji: 🧠
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ # Perdypto Reasoning Service
11
+
12
+ FastAPI microservice that synthesizes price, TA, and news data via DeepSeek V4 Pro to generate structured crypto price predictions.
13
+
14
+ ## Endpoint
15
+
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
constants.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
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
main.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
32
+
33
+ app.add_middleware(
34
+ CORSMiddleware,
35
+ allow_origins=["*"],
36
+ allow_credentials=True,
37
+ allow_methods=["*"],
38
+ allow_headers=["*"],
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,
57
+ symbol=request.symbol,
58
+ name=request.name,
59
+ price_at_prediction=request.current_price,
60
+ prediction=prediction,
61
+ model_used=REASONING_MODEL,
62
+ reasoning_time_ms=int((time.time() - start_time) * 1000)
63
+ )
64
+
65
+ except Exception as e:
66
+ # Always print full error to stdout for debugging
67
+ print(f"[ERROR] /reason failed for {request.symbol}: {e}")
68
+ raise HTTPException(
69
+ status_code=503,
70
+ detail=ErrorResponse(error="Prediction generation failed", detail=str(e)).model_dump()
71
+ )
models.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+ from typing import Optional
3
+ from pydantic import BaseModel, ConfigDict
4
+
5
+
6
+ class TAAnalysisResult(BaseModel):
7
+ model_config = ConfigDict(from_attributes=True)
8
+
9
+ coin_id: str
10
+ symbol: str
11
+ trend: str
12
+ confidence: float
13
+ analysis_summary: str
14
+ ai_reasoning: str
15
+ rsi_signal: str
16
+ macd_signal_dir: str
17
+ price_vs_bb: str
18
+
19
+
20
+ class NewsSummary(BaseModel):
21
+ model_config = ConfigDict(from_attributes=True)
22
+
23
+ coin_id: str
24
+ symbol: str
25
+ overall_sentiment: str
26
+ bullish_count: int
27
+ bearish_count: int
28
+ neutral_count: int
29
+ summary: str
30
+
31
+
32
+ class ReasoningRequest(BaseModel):
33
+ model_config = ConfigDict(from_attributes=True)
34
+
35
+ coin_id: str
36
+ symbol: str
37
+ name: str
38
+ current_price: float
39
+ price_change_24h: float
40
+ volume_24h: float
41
+ ta_result: TAAnalysisResult
42
+ news_summary: NewsSummary
43
+
44
+
45
+ class PredictionOutput(BaseModel):
46
+ model_config = ConfigDict(from_attributes=True)
47
+
48
+ predicted_1m: Optional[float]
49
+ predicted_15m: float
50
+ predicted_1h: float
51
+ confidence_score: float
52
+ reasoning: str
53
+ ta_summary: str
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
62
+ name: str
63
+ price_at_prediction: float
64
+ prediction: PredictionOutput
65
+ model_used: str
66
+ reasoning_time_ms: int
67
+
68
+
69
+ class ErrorResponse(BaseModel):
70
+ model_config = ConfigDict(from_attributes=True)
71
+
72
+ error: str
73
+ detail: Optional[str]
reasoning_client.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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})
32
+ CURRENT PRICE: {req.current_price}
33
+ 24H CHANGE: {req.price_change_24h}%
34
+ 24H VOLUME: {req.volume_24h}
35
+
36
+ TECHNICAL ANALYSIS:
37
+ Trend: {ta.trend}
38
+ TA Confidence: {ta.confidence}
39
+ RSI Signal: {ta.rsi_signal}
40
+ MACD Direction: {ta.macd_signal_dir}
41
+ Bollinger Band Position: {ta.price_vs_bb}
42
+ TA AI Reasoning: {ta.ai_reasoning}
43
+ TA Summary: {ta.analysis_summary}
44
+
45
+ NEWS SENTIMENT: {news.overall_sentiment}
46
+ Bullish Articles: {news.bullish_count}
47
+ Bearish Articles: {news.bearish_count}
48
+ Neutral Articles: {news.neutral_count}
49
+ News Summary: {news.summary}"""
50
+
51
+
52
+ def _strip_markdown(text: str) -> str:
53
+ """Remove markdown code fences from response."""
54
+ text = text.strip()
55
+ text = re.sub(r'^```json\s*', '', text, flags=re.MULTILINE)
56
+ text = re.sub(r'^```\s*', '', text, flags=re.MULTILINE)
57
+ text = re.sub(r'```$', '', text, flags=re.MULTILINE)
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()
68
+
69
+ # Retry loop wraps entire streaming + parsing to handle mid-stream failures
70
+ for attempt in range(2):
71
+ full_response = ""
72
+ try:
73
+ completion = await client.chat.completions.create(
74
+ model=REASONING_MODEL,
75
+ messages=[
76
+ {"role": "system", "content": SYSTEM_PROMPT},
77
+ {"role": "user", "content": user_message}
78
+ ],
79
+ temperature=TEMPERATURE,
80
+ top_p=TOP_P,
81
+ max_tokens=MAX_TOKENS,
82
+ extra_body={"chat_template_kwargs": {"thinking": THINKING}},
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():
99
+ raise ValueError("Empty response received from model")
100
+
101
+ # Strip markdown and validate JSON structure before parsing
102
+ cleaned = _strip_markdown(full_response)
103
+ if not cleaned.strip().startswith("{") or not cleaned.strip().endswith("}"):
104
+ raise ValueError(f"Incomplete JSON received: {cleaned[:200]}")
105
+
106
+ parsed = json.loads(cleaned)
107
+
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")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.115.0
2
+ uvicorn==0.30.6
3
+ httpx==0.27.2
4
+ pydantic==2.8.2
5
+ python-dotenv==1.0.1
6
+ openai==1.35.0