Riy777 commited on
Commit
be6b412
·
verified ·
1 Parent(s): a409fe5

Update LLM.py

Browse files
Files changed (1) hide show
  1. LLM.py +12 -48
LLM.py CHANGED
@@ -1,13 +1,11 @@
1
- # LLM.py (V13.4 - The "Heavyweight" Omniscient Brain)
2
- # استعادة كامل التفاصيل في البرومبتات لضمان عدم وجود أي اختصارات.
3
-
4
  import os, traceback, json, re, time
5
  from datetime import datetime
6
  from typing import Dict, Any, Optional
7
  from openai import AsyncOpenAI, RateLimitError, APIError
8
 
9
  # ==============================================================================
10
- # 🔌 إعدادات الاتصال (مطابقة للأصل تماماً)
11
  # ==============================================================================
12
  LLM_API_URL = os.getenv("LLM_API_URL", "https://integrate.api.nvidia.com/v1")
13
  LLM_API_KEY = os.getenv("LLM_API_KEY")
@@ -32,14 +30,10 @@ class LLMService:
32
  )
33
  self.r2_service = None
34
  self.learning_hub = None
35
-
36
- print(f"🧠 [LLM V13.4] Heavyweight Brain Initialized: {LLM_MODEL}")
37
 
38
  async def _call_llm(self, prompt: str) -> Optional[str]:
39
- """إرسال الطلب مع تفعيل وضع التفكير العميق بدقة"""
40
- # ⚠️ هام: هذا الإعداد دقيق جداً لتفعيل قدرات Nemotron الخاصة
41
  system_prompt = "detailed thinking on"
42
-
43
  try:
44
  response = await self.client.chat.completions.create(
45
  model=LLM_MODEL,
@@ -61,7 +55,6 @@ class LLMService:
61
  return None
62
 
63
  def _parse_json_secure(self, text: str) -> Optional[Dict]:
64
- """محلل JSON قوي يستخرج البيانات من أي نص"""
65
  try:
66
  match = re.search(r'\{.*\}', text, re.DOTALL)
67
  if match: return json.loads(match.group(0))
@@ -69,24 +62,19 @@ class LLMService:
69
  return None
70
 
71
  # ==================================================================
72
- # 🧠 الوظيفة 1: قرار الدخول الاستراتيجي (تحليل شامل ومفصل)
73
  # ==================================================================
74
  async def get_trading_decision(self, candidate_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
75
  symbol = candidate_data.get('symbol', 'UNKNOWN')
76
  try:
77
- # جلب سياق التعلم السابق إن وجد
78
- learning_context = "Playbook: No specific prior learning for this scenario."
79
  if self.learning_hub:
80
  learning_context = await self.learning_hub.get_active_context_for_llm("general", f"{symbol} entry analysis")
81
 
82
- # بناء البرومبت المفصل جداً
83
  prompt = self._create_heavyweight_entry_prompt(candidate_data, learning_context)
84
-
85
- # استدعاء النموذج
86
  response_text = await self._call_llm(prompt)
87
  decision = self._parse_json_secure(response_text)
88
 
89
- # حفظ نسخة طبق الأصل من الطلب والرد للتدقيق
90
  if self.r2_service and response_text:
91
  await self.r2_service.save_llm_prompt_async(symbol, "entry_decision_full", prompt, response_text)
92
 
@@ -96,9 +84,6 @@ class LLMService:
96
  traceback.print_exc()
97
  return None
98
 
99
- # ==================================================================
100
- # 🔄 الوظيفة 2: إعادة التحليل الدوري (مراجعة شاملة للوضع)
101
- # ==================================================================
102
  async def re_analyze_trade_async(self, trade_data: Dict[str, Any], current_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
103
  symbol = trade_data.get('symbol', 'UNKNOWN')
104
  try:
@@ -108,7 +93,6 @@ class LLMService:
108
  learning_context = await self.learning_hub.get_active_context_for_llm("strategy", f"{symbol} re-eval {strategy}")
109
 
110
  prompt = self._create_heavyweight_reanalysis_prompt(trade_data, current_data, learning_context)
111
-
112
  response_text = await self._call_llm(prompt)
113
  decision = self._parse_json_secure(response_text)
114
 
@@ -121,32 +105,26 @@ class LLMService:
121
  return None
122
 
123
  # ==================================================================
124
- # 📝 قسم هندسة البرومبتات (تفاصيل كاملة بدون اختصارات)
125
  # ==================================================================
126
  def _create_heavyweight_entry_prompt(self, data: Dict[str, Any], learning_context: str) -> str:
127
- """
128
- إنشاء برومبت ضخم يحتوي على كل شاردة وواردة من البيانات المتاحة.
129
- """
130
  symbol = data.get('symbol')
131
  current_price = data.get('current_price')
132
 
133
- # 1. تفاصيل الطبقات الس��بقة (التحليل الفني والكمي)
134
  titan_score = data.get('titan_details', {}).get('score', 0)
135
  titan_trend = "STRONG_UP" if titan_score > 0.7 else "UP" if titan_score > 0.5 else "WEAK"
136
-
137
  pat_details = data.get('pattern_details', {})
138
  pat_name = pat_details.get('pattern_detected', 'None')
139
  pat_conf = pat_details.get('pattern_confidence', 0)
140
-
141
  mc_score = data.get('components', {}).get('mc_score', 0)
 
 
142
  l1_total = data.get('enhanced_final_score', 0)
143
  l2_total = data.get('layer2_score', 0)
144
 
145
- # 2. تفاصيل بيانات الحيتان (كاملة)
146
  whale = data.get('whale_data', {})
147
  whale_1h = whale.get('exchange_flows', {})
148
  whale_24h = whale.get('accumulation_analysis_24h', {})
149
-
150
  whale_section = f"""
151
  - 1H Net Flow to Exchanges: ${whale_1h.get('net_flow_usd', 0):,.2f}
152
  - 1H Deposits: {whale_1h.get('deposit_count', 0)} | Withdrawals: {whale_1h.get('withdrawal_count', 0)}
@@ -154,16 +132,11 @@ class LLMService:
154
  - 24H Whale Transaction Count: {whale_24h.get('whale_transfers_count', 0)}
155
  - Relative Flow Impact (24H): {whale_24h.get('relative_net_flow_percent', 0):.4f}%
156
  """
157
-
158
- # 3. تفاصيل الأخبار (النص الخام الكامل)
159
- news_text = data.get('news_text', 'No specific news available for this asset currently.')
160
-
161
- # 4. لقطة السوق (Price Action Snapshot)
162
  ohlcv = data.get('ohlcv_sample', {})
163
  price_section = ""
164
  for tf, candle in ohlcv.items():
165
  if candle:
166
- # [Timestamp, Open, High, Low, Close, Volume]
167
  price_section += f" - {tf.upper()}: Open={candle[1]}, High={candle[2]}, Low={candle[3]}, Close={candle[4]}, Vol={candle[5]}\n"
168
 
169
  return f"""
@@ -173,7 +146,7 @@ Current Price: {current_price}
173
 
174
  ========== 🧠 PART 1: SUB-SYSTEM REPORTS (PRELIMINARY ANALYSIS) ==========
175
  Your subordinate systems have flagged this asset with the following scores:
176
- * Layer 1 Technical Score: {l1_score:.4f} / 1.0
177
  - Titan ML Trend Model: {titan_score:.4f} ({titan_trend})
178
  - Chart Pattern Recognition: {pat_name} (Confidence: {pat_conf:.2f})
179
  - Monte Carlo Probability (1H): {mc_score:.4f}
@@ -206,28 +179,21 @@ REQUIRED OUTPUT (Strict JSON format ONLY):
206
  {{
207
  "action": "WATCH" or "IGNORE",
208
  "confidence_level": 0.00 to 1.00,
209
- "reasoning": "A rigorous, professional justification citing specific raw evidence (e.g., 'Whale 1H inflows of $5M contradict Titan trend').",
210
  "strategy_directive": "MOMENTUM_BREAKOUT" or "DIP_ACCUMULATION" or "SCALP_REVERSAL",
211
  "key_risk_factor": "Identify the single biggest risk based on raw evidence."
212
  }}
213
  """
214
 
215
  def _create_heavyweight_reanalysis_prompt(self, trade: Dict, current: Dict, learning_context: str) -> str:
216
- """
217
- إنشاء برومبت مفصل لإعادة تقييم صفقة مفتوحة بناءً على تغير الظروف.
218
- """
219
  symbol = trade.get('symbol')
220
  entry_price = trade.get('entry_price')
221
  current_price = current.get('current_price')
222
  pnl_pct = ((current_price - entry_price) / entry_price) * 100
223
- duration_min = (datetime.now() - datetime.fromisoformat(trade.get('entry_time').replace('Z', ''))).total_seconds() / 60
224
-
225
- # البيانات الحالية المقارنة
226
  titan_now = current.get('titan_score', 0)
227
-
228
  whale_now = current.get('whale_data', {})
229
  whale_1h_net = whale_now.get('exchange_flows', {}).get('net_flow_usd', 0)
230
-
231
  news_now = current.get('news_text', 'No new significant news.')
232
 
233
  return f"""
@@ -245,7 +211,6 @@ TIME IN TRADE: {duration_min:.1f} minutes
245
  ========== 🆕 CHANGED MARKET CONDITIONS (RAW DATA) ==========
246
  1. ML Trend Update (Titan): Currently {titan_now:.4f}
247
  2. Fresh Whale Activity (Last 1H): Net Flow ${whale_1h_net:,.0f}
248
- (Positive = potential selling pressure, Negative = accumulation)
249
  3. Latest News Update:
250
  \"\"\"{news_now[:1000]}\"\"\"
251
 
@@ -262,5 +227,4 @@ Output Strict JSON ONLY:
262
  "reasoning": "Professional assessment of current risk vs original thesis."
263
  }}
264
  """
265
-
266
  print("✅ LLM Service V13.4 (Heavyweight Omniscient Brain) Loaded - NO SHORTCUTS")
 
1
+ # LLM.py (V13.5 - Fixed Variable Name Error)
 
 
2
  import os, traceback, json, re, time
3
  from datetime import datetime
4
  from typing import Dict, Any, Optional
5
  from openai import AsyncOpenAI, RateLimitError, APIError
6
 
7
  # ==============================================================================
8
+ # 🔌 إعدادات الاتصال
9
  # ==============================================================================
10
  LLM_API_URL = os.getenv("LLM_API_URL", "https://integrate.api.nvidia.com/v1")
11
  LLM_API_KEY = os.getenv("LLM_API_KEY")
 
30
  )
31
  self.r2_service = None
32
  self.learning_hub = None
33
+ print(f"🧠 [LLM V13.5] Brain Online: {LLM_MODEL}")
 
34
 
35
  async def _call_llm(self, prompt: str) -> Optional[str]:
 
 
36
  system_prompt = "detailed thinking on"
 
37
  try:
38
  response = await self.client.chat.completions.create(
39
  model=LLM_MODEL,
 
55
  return None
56
 
57
  def _parse_json_secure(self, text: str) -> Optional[Dict]:
 
58
  try:
59
  match = re.search(r'\{.*\}', text, re.DOTALL)
60
  if match: return json.loads(match.group(0))
 
62
  return None
63
 
64
  # ==================================================================
65
+ # 🧠 الوظائف الرئيسية
66
  # ==================================================================
67
  async def get_trading_decision(self, candidate_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
68
  symbol = candidate_data.get('symbol', 'UNKNOWN')
69
  try:
70
+ learning_context = "Playbook: No specific prior learning."
 
71
  if self.learning_hub:
72
  learning_context = await self.learning_hub.get_active_context_for_llm("general", f"{symbol} entry analysis")
73
 
 
74
  prompt = self._create_heavyweight_entry_prompt(candidate_data, learning_context)
 
 
75
  response_text = await self._call_llm(prompt)
76
  decision = self._parse_json_secure(response_text)
77
 
 
78
  if self.r2_service and response_text:
79
  await self.r2_service.save_llm_prompt_async(symbol, "entry_decision_full", prompt, response_text)
80
 
 
84
  traceback.print_exc()
85
  return None
86
 
 
 
 
87
  async def re_analyze_trade_async(self, trade_data: Dict[str, Any], current_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
88
  symbol = trade_data.get('symbol', 'UNKNOWN')
89
  try:
 
93
  learning_context = await self.learning_hub.get_active_context_for_llm("strategy", f"{symbol} re-eval {strategy}")
94
 
95
  prompt = self._create_heavyweight_reanalysis_prompt(trade_data, current_data, learning_context)
 
96
  response_text = await self._call_llm(prompt)
97
  decision = self._parse_json_secure(response_text)
98
 
 
105
  return None
106
 
107
  # ==================================================================
108
+ # 📝 هندسة البرومبتات (مصححة)
109
  # ==================================================================
110
  def _create_heavyweight_entry_prompt(self, data: Dict[str, Any], learning_context: str) -> str:
 
 
 
111
  symbol = data.get('symbol')
112
  current_price = data.get('current_price')
113
 
 
114
  titan_score = data.get('titan_details', {}).get('score', 0)
115
  titan_trend = "STRONG_UP" if titan_score > 0.7 else "UP" if titan_score > 0.5 else "WEAK"
 
116
  pat_details = data.get('pattern_details', {})
117
  pat_name = pat_details.get('pattern_detected', 'None')
118
  pat_conf = pat_details.get('pattern_confidence', 0)
 
119
  mc_score = data.get('components', {}).get('mc_score', 0)
120
+
121
+ # ✅ تصحيح الاسم هنا واستخدامه بالأسفل
122
  l1_total = data.get('enhanced_final_score', 0)
123
  l2_total = data.get('layer2_score', 0)
124
 
 
125
  whale = data.get('whale_data', {})
126
  whale_1h = whale.get('exchange_flows', {})
127
  whale_24h = whale.get('accumulation_analysis_24h', {})
 
128
  whale_section = f"""
129
  - 1H Net Flow to Exchanges: ${whale_1h.get('net_flow_usd', 0):,.2f}
130
  - 1H Deposits: {whale_1h.get('deposit_count', 0)} | Withdrawals: {whale_1h.get('withdrawal_count', 0)}
 
132
  - 24H Whale Transaction Count: {whale_24h.get('whale_transfers_count', 0)}
133
  - Relative Flow Impact (24H): {whale_24h.get('relative_net_flow_percent', 0):.4f}%
134
  """
135
+ news_text = data.get('news_text', 'No specific news available.')
 
 
 
 
136
  ohlcv = data.get('ohlcv_sample', {})
137
  price_section = ""
138
  for tf, candle in ohlcv.items():
139
  if candle:
 
140
  price_section += f" - {tf.upper()}: Open={candle[1]}, High={candle[2]}, Low={candle[3]}, Close={candle[4]}, Vol={candle[5]}\n"
141
 
142
  return f"""
 
146
 
147
  ========== 🧠 PART 1: SUB-SYSTEM REPORTS (PRELIMINARY ANALYSIS) ==========
148
  Your subordinate systems have flagged this asset with the following scores:
149
+ * Layer 1 Technical Score: {l1_total:.4f} / 1.0 <-- ✅ تم التصحيح هنا
150
  - Titan ML Trend Model: {titan_score:.4f} ({titan_trend})
151
  - Chart Pattern Recognition: {pat_name} (Confidence: {pat_conf:.2f})
152
  - Monte Carlo Probability (1H): {mc_score:.4f}
 
179
  {{
180
  "action": "WATCH" or "IGNORE",
181
  "confidence_level": 0.00 to 1.00,
182
+ "reasoning": "A rigorous, professional justification citing specific raw evidence.",
183
  "strategy_directive": "MOMENTUM_BREAKOUT" or "DIP_ACCUMULATION" or "SCALP_REVERSAL",
184
  "key_risk_factor": "Identify the single biggest risk based on raw evidence."
185
  }}
186
  """
187
 
188
  def _create_heavyweight_reanalysis_prompt(self, trade: Dict, current: Dict, learning_context: str) -> str:
 
 
 
189
  symbol = trade.get('symbol')
190
  entry_price = trade.get('entry_price')
191
  current_price = current.get('current_price')
192
  pnl_pct = ((current_price - entry_price) / entry_price) * 100
193
+ duration_min = (datetime.now(timezone.utc) - datetime.fromisoformat(trade.get('entry_time').replace('Z', '+00:00'))).total_seconds() / 60
 
 
194
  titan_now = current.get('titan_score', 0)
 
195
  whale_now = current.get('whale_data', {})
196
  whale_1h_net = whale_now.get('exchange_flows', {}).get('net_flow_usd', 0)
 
197
  news_now = current.get('news_text', 'No new significant news.')
198
 
199
  return f"""
 
211
  ========== 🆕 CHANGED MARKET CONDITIONS (RAW DATA) ==========
212
  1. ML Trend Update (Titan): Currently {titan_now:.4f}
213
  2. Fresh Whale Activity (Last 1H): Net Flow ${whale_1h_net:,.0f}
 
214
  3. Latest News Update:
215
  \"\"\"{news_now[:1000]}\"\"\"
216
 
 
227
  "reasoning": "Professional assessment of current risk vs original thesis."
228
  }}
229
  """
 
230
  print("✅ LLM Service V13.4 (Heavyweight Omniscient Brain) Loaded - NO SHORTCUTS")