Spaces:
Sleeping

PERDYPTO commited on
Commit
30a97c9
·
verified ·
1 Parent(s): d35349a

Delete orchestrator.py

Browse files
Files changed (1) hide show
  1. orchestrator.py +0 -312
orchestrator.py DELETED
@@ -1,312 +0,0 @@
1
- import asyncio
2
- from datetime import datetime, timezone, timedelta
3
- from typing import Optional
4
-
5
- import httpx
6
-
7
- from constants import (
8
- CACHE_TTL_SECONDS, DEFAULT_COINS,
9
- PRICE_SERVICE_URL, NEWS_SERVICE_URL,
10
- CRYPTO_AI_SERVICE_URL, CACHE_SERVICE_URL,
11
- REASONING_SERVICE_URL
12
- )
13
- from models import (
14
- PriceWithCandles, PriceData, BulkPriceResponse, TAAnalysisResult, NewsSummary,
15
- PredictionOutput, PredictionResult, CacheCheckResponse,
16
- OrchestrationResult
17
- )
18
-
19
-
20
- REASONING_CANDLE_CONTEXT_1M_LIMIT = 40
21
- REASONING_CANDLE_CONTEXT_1H_LIMIT = 24
22
- REASONING_SERVICE_TIMEOUT_SECONDS = 300.0
23
- ORCHESTRATION_TIMEOUT_SECONDS = 420
24
-
25
-
26
- def compact_candle_context(candles, limit: int):
27
- """Return recent candles in a compact JSON-friendly shape for the reasoning model."""
28
- return [
29
- {
30
- "t": candle.timestamp.isoformat(),
31
- "o": candle.open,
32
- "h": candle.high,
33
- "l": candle.low,
34
- "c": candle.close,
35
- "v": candle.volume
36
- }
37
- for candle in candles[-limit:]
38
- ]
39
-
40
-
41
- async def with_retry(coro_func, retries=2, label="service"):
42
- """Generic retry wrapper with exponential backoff for downstream calls."""
43
- for attempt in range(retries):
44
- try:
45
- return await coro_func()
46
- except asyncio.CancelledError:
47
- raise
48
- except Exception as e:
49
- if attempt == retries - 1:
50
- raise
51
- wait = 0.5 * (2 ** attempt)
52
- print(f"[WARN] {label} attempt {attempt+1} failed: {e}, retrying in {wait}s")
53
- await asyncio.sleep(wait)
54
-
55
-
56
- async def check_cache(client: httpx.AsyncClient, coin_id: str) -> Optional[CacheCheckResponse]:
57
- """Check cache service for fresh prediction. Never raises, returns None on failure."""
58
- if not CACHE_SERVICE_URL:
59
- print("[WARN] CACHE_SERVICE_URL not configured")
60
- return None
61
- try:
62
- response = await client.get(f"{CACHE_SERVICE_URL}/cache/{coin_id}")
63
- response.raise_for_status()
64
- try:
65
- return CacheCheckResponse(**response.json())
66
- except Exception as e:
67
- print(f"[WARN] Schema validation failed for cache: {e}")
68
- raise ValueError(f"Invalid response schema from cache: {e}")
69
- except Exception as e:
70
- print(f"[WARN] Cache check failed for {coin_id}: {e}")
71
- return None
72
-
73
-
74
- async def fetch_price_and_candles(client: httpx.AsyncClient, coin: dict) -> PriceWithCandles:
75
- """Fetch price + OHLCV from Price Service. Raises ValueError on failure."""
76
- if not PRICE_SERVICE_URL:
77
- raise ValueError("PRICE_SERVICE_URL not configured")
78
- response = await client.get(f"{PRICE_SERVICE_URL}/price/{coin['id']}/full")
79
- response.raise_for_status()
80
- try:
81
- return PriceWithCandles(**response.json())
82
- except Exception as e:
83
- print(f"[WARN] Schema validation failed for price-service: {e}")
84
- raise ValueError(f"Invalid response schema from price-service: {e}")
85
-
86
-
87
- async def fetch_live_price(client: httpx.AsyncClient, coin: dict) -> PriceData:
88
- """Fetch only current price data from Price Service. No TA/news/reasoning calls."""
89
- if not PRICE_SERVICE_URL:
90
- raise ValueError("PRICE_SERVICE_URL not configured")
91
- response = await client.get(f"{PRICE_SERVICE_URL}/price/{coin['id']}")
92
- response.raise_for_status()
93
- try:
94
- return PriceData(**response.json())
95
- except Exception as e:
96
- print(f"[WARN] Schema validation failed for price-service live price: {e}")
97
- raise ValueError(f"Invalid response schema from price-service: {e}")
98
-
99
-
100
- async def fetch_all_live_prices(client: httpx.AsyncClient) -> BulkPriceResponse:
101
- """Fetch current prices for all default coins. No TA/news/reasoning calls."""
102
- if not PRICE_SERVICE_URL:
103
- raise ValueError("PRICE_SERVICE_URL not configured")
104
- response = await client.get(f"{PRICE_SERVICE_URL}/prices")
105
- response.raise_for_status()
106
- try:
107
- return BulkPriceResponse(**response.json())
108
- except Exception as e:
109
- print(f"[WARN] Schema validation failed for price-service bulk prices: {e}")
110
- raise ValueError(f"Invalid response schema from price-service: {e}")
111
-
112
-
113
- async def fetch_news(client: httpx.AsyncClient, coin: dict) -> NewsSummary:
114
- """Fetch news summary from News Service. Raises ValueError on failure."""
115
- if not NEWS_SERVICE_URL:
116
- raise ValueError("NEWS_SERVICE_URL not configured")
117
- response = await client.get(f"{NEWS_SERVICE_URL}/news/{coin['id']}")
118
- response.raise_for_status()
119
- try:
120
- return NewsSummary(**response.json())
121
- except Exception as e:
122
- print(f"[WARN] Schema validation failed for news-service: {e}")
123
- raise ValueError(f"Invalid response schema from news-service: {e}")
124
-
125
-
126
- async def fetch_ta_analysis(client: httpx.AsyncClient, coin: dict, price_with_candles: PriceWithCandles) -> TAAnalysisResult:
127
- """Fetch TA analysis from Crypto AI Service. Raises ValueError on failure."""
128
- if not CRYPTO_AI_SERVICE_URL:
129
- raise ValueError("CRYPTO_AI_SERVICE_URL not configured")
130
- payload = {
131
- "coin_id": coin["id"],
132
- "symbol": coin["symbol"],
133
- "name": coin["name"],
134
- "current_price": price_with_candles.price.current_price,
135
- "candles": [
136
- c.model_dump(mode="json")
137
- for c in (price_with_candles.candles_1m or price_with_candles.candles)
138
- ],
139
- "candles_1h": [c.model_dump(mode="json") for c in price_with_candles.candles_1h]
140
- }
141
- response = await client.post(f"{CRYPTO_AI_SERVICE_URL}/analyze", json=payload)
142
- response.raise_for_status()
143
- try:
144
- data = response.json()
145
- indicators = data.get("indicators", {})
146
- return TAAnalysisResult(
147
- coin_id=data["coin_id"],
148
- symbol=data["symbol"],
149
- trend=data["trend"],
150
- confidence=data["confidence"],
151
- analysis_summary=data["analysis_summary"],
152
- ai_reasoning=data["ai_reasoning"],
153
- rsi_signal=indicators["rsi_signal"],
154
- macd_signal_dir=indicators["macd_signal_dir"],
155
- price_vs_bb=indicators["price_vs_bb"],
156
- higher_tf_trend=indicators.get("higher_tf_trend"),
157
- higher_tf_confidence=indicators.get("higher_tf_confidence"),
158
- higher_tf_rsi_signal=indicators.get("higher_tf_rsi_signal"),
159
- higher_tf_macd_signal_dir=indicators.get("higher_tf_macd_signal_dir"),
160
- higher_tf_price_vs_bb=indicators.get("higher_tf_price_vs_bb")
161
- )
162
- except Exception as e:
163
- print(f"[WARN] Schema validation failed for crypto-ai-service: {e}")
164
- raise ValueError(f"Invalid response schema from crypto-ai-service: {e}")
165
-
166
-
167
- async def call_reasoning(
168
- client,
169
- coin,
170
- price_with_candles: PriceWithCandles,
171
- ta_result: TAAnalysisResult,
172
- news_summary: NewsSummary
173
- ) -> PredictionOutput:
174
- """Call Reasoning Service with combined data. Raises ValueError on failure."""
175
- if not REASONING_SERVICE_URL:
176
- raise ValueError("REASONING_SERVICE_URL not configured")
177
- price_data = price_with_candles.price
178
- payload = {
179
- "coin_id": coin["id"],
180
- "symbol": coin["symbol"],
181
- "name": coin["name"],
182
- "current_price": price_data.current_price,
183
- "price_change_24h": price_data.price_change_24h,
184
- "volume_24h": price_data.volume_24h,
185
- "ta_result": ta_result.model_dump(mode="json"),
186
- "news_summary": news_summary.model_dump(mode="json"),
187
- "raw_candles_1m": compact_candle_context(
188
- price_with_candles.candles_1m or price_with_candles.candles,
189
- REASONING_CANDLE_CONTEXT_1M_LIMIT
190
- ),
191
- "raw_candles_1h": compact_candle_context(
192
- price_with_candles.candles_1h,
193
- REASONING_CANDLE_CONTEXT_1H_LIMIT
194
- )
195
- }
196
- response = await client.post(f"{REASONING_SERVICE_URL}/reason", json=payload)
197
- response.raise_for_status()
198
- try:
199
- return PredictionOutput(**response.json()["prediction"])
200
- except Exception as e:
201
- print(f"[WARN] Schema validation failed for reasoning-service: {e}")
202
- raise ValueError(f"Invalid response schema from reasoning-service: {e}")
203
-
204
-
205
- async def save_to_cache(client: httpx.AsyncClient, prediction: PredictionResult) -> None:
206
- """Save prediction to cache service. Prints warning on failure."""
207
- if not CACHE_SERVICE_URL:
208
- print("[WARN] CACHE_SERVICE_URL not configured")
209
- return
210
- try:
211
- payload = {"prediction": prediction.model_dump(mode="json")}
212
- response = await client.post(f"{CACHE_SERVICE_URL}/cache", json=payload)
213
- response.raise_for_status()
214
- except Exception as e:
215
- print(f"[WARN] Cache save failed for {prediction.coin_id}: {e}")
216
-
217
-
218
- async def orchestrate(client: httpx.AsyncClient, coin: dict, force_refresh: bool) -> OrchestrationResult:
219
- """Main orchestration logic with retries, independent timeouts, and degraded mode."""
220
- # Step 1: Check cache if not force_refresh
221
- if not force_refresh:
222
- cache_resp = await check_cache(client, coin["id"])
223
- if cache_resp and cache_resp.found and cache_resp.is_fresh and cache_resp.data:
224
- return OrchestrationResult(
225
- prediction=cache_resp.data,
226
- from_cache=True,
227
- cache_expires_in=getattr(cache_resp.data, "seconds_until_expiry", None)
228
- )
229
-
230
- price_with_candles = None
231
- news_summary = None
232
- result = None
233
-
234
- try:
235
- async with asyncio.timeout(ORCHESTRATION_TIMEOUT_SECONDS):
236
- # Price Service — mandatory, fast exchange API
237
- price_with_candles = await with_retry(
238
- lambda: asyncio.wait_for(fetch_price_and_candles(client, coin), timeout=15.0),
239
- label="price-service"
240
- )
241
-
242
- # News Service — degraded mode fallback if it fails after retries
243
- try:
244
- news_summary = await with_retry(
245
- lambda: asyncio.wait_for(fetch_news(client, coin), timeout=30.0),
246
- label="news-service"
247
- )
248
- except Exception as e:
249
- print(f"[WARN] News fetch failed, flagging as unavailable: {e}")
250
- news_summary = NewsSummary(
251
- coin_id=coin['id'],
252
- symbol=coin['symbol'],
253
- overall_sentiment="unavailable",
254
- bullish_count=0,
255
- bearish_count=0,
256
- neutral_count=0,
257
- summary="NEWS DATA UNAVAILABLE - base prediction on TA and price action only, ignore news sentiment entirely."
258
- )
259
-
260
- # Crypto AI — TA computation + Llama call
261
- ta_result = await with_retry(
262
- lambda: asyncio.wait_for(fetch_ta_analysis(client, coin, price_with_candles), timeout=60.0),
263
- label="crypto-ai-service"
264
- )
265
-
266
- # Reasoning Service — DeepSeek thinking mode
267
- prediction_output = await with_retry(
268
- lambda: asyncio.wait_for(call_reasoning(client, coin, price_with_candles,
269
- ta_result, news_summary), timeout=REASONING_SERVICE_TIMEOUT_SECONDS),
270
- retries=1,
271
- label="reasoning-service"
272
- )
273
-
274
- # Step 5: Build PredictionResult
275
- now = datetime.now(timezone.utc)
276
- result = PredictionResult(
277
- coin_id=coin["id"],
278
- symbol=coin["symbol"],
279
- name=coin["name"],
280
- price_at_prediction=price_with_candles.price.current_price,
281
- price_change_24h=price_with_candles.price.price_change_24h,
282
- volume_24h=price_with_candles.price.volume_24h,
283
- predicted_1m=prediction_output.predicted_1m,
284
- predicted_15m=prediction_output.predicted_15m,
285
- predicted_1h=prediction_output.predicted_1h,
286
- confidence_score=prediction_output.confidence_score,
287
- reasoning=prediction_output.reasoning,
288
- ta_summary=prediction_output.ta_summary,
289
- news_summary=prediction_output.news_summary,
290
- created_at=now,
291
- expires_at=now + timedelta(seconds=CACHE_TTL_SECONDS)
292
- )
293
-
294
- # Step 6: Save to cache with timeout (awaited, never silently dropped)
295
- try:
296
- await asyncio.wait_for(save_to_cache(client, result), timeout=10.0)
297
- except asyncio.TimeoutError:
298
- print("[WARN] Cache save timed out, prediction not cached")
299
- except Exception as e:
300
- print(f"[WARN] Cache save failed: {e}")
301
- except asyncio.TimeoutError:
302
- raise ValueError(f"Orchestration exceeded global {ORCHESTRATION_TIMEOUT_SECONDS}s budget. Try again shortly.")
303
-
304
- if result is None:
305
- raise ValueError("Orchestration failed before producing a result")
306
-
307
- # Step 7: Return result
308
- return OrchestrationResult(
309
- prediction=result,
310
- from_cache=False,
311
- cache_expires_in=CACHE_TTL_SECONDS
312
- )