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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
🤖 LLM Sender Unified Module
|
| 3 |
+
ماژول یکپارچه برای ارسال به ChatGPT و Grok
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
import os
|
| 8 |
+
import logging
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import time
|
| 11 |
+
from abc import ABC, abstractmethod
|
| 12 |
+
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LLMSender(ABC):
|
| 18 |
+
"""کلاس پایه برای ارسال به مدلهای مختلف LLM"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, api_key: Optional[str] = None, model: str = None):
|
| 21 |
+
self.api_key = api_key
|
| 22 |
+
self.model = model
|
| 23 |
+
self.base_url = ""
|
| 24 |
+
|
| 25 |
+
@abstractmethod
|
| 26 |
+
def get_default_model(self) -> str:
|
| 27 |
+
"""مدل پیشفرض"""
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
@abstractmethod
|
| 31 |
+
def get_base_url(self) -> str:
|
| 32 |
+
"""URL پایه API"""
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
def set_api_key(self, api_key: str):
|
| 36 |
+
"""تنظیم کلید API"""
|
| 37 |
+
self.api_key = api_key
|
| 38 |
+
logger.info("✅ کلید API تنظیم شد")
|
| 39 |
+
|
| 40 |
+
def set_model(self, model: str):
|
| 41 |
+
"""تغییر مدل"""
|
| 42 |
+
self.model = model
|
| 43 |
+
logger.info(f"✅ مدل تغییر یافت به: {model}")
|
| 44 |
+
|
| 45 |
+
def send_simple(self, text: str, lang: str = 'fa') -> str:
|
| 46 |
+
"""ارسال ساده بدون system message سفارشی"""
|
| 47 |
+
system_msg = (
|
| 48 |
+
"شما یک تحلیلگر متخصص هستید. متن حاوی کدهای ناشناس است. "
|
| 49 |
+
"به درخواستها با دقت و حرفهای پاسخ دهید."
|
| 50 |
+
if lang == 'fa'
|
| 51 |
+
else "You are a professional analyst. The text contains anonymous codes. "
|
| 52 |
+
"Answer requests accurately and professionally."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
return self.send(text, system_msg=system_msg, lang=lang)
|
| 56 |
+
|
| 57 |
+
def send(
|
| 58 |
+
self,
|
| 59 |
+
text: str,
|
| 60 |
+
system_msg: Optional[str] = None,
|
| 61 |
+
max_tokens: int = 2000,
|
| 62 |
+
temperature: float = 0.7,
|
| 63 |
+
timeout: int = 60,
|
| 64 |
+
lang: str = 'fa',
|
| 65 |
+
retry_count: int = 3
|
| 66 |
+
) -> str:
|
| 67 |
+
"""ارسال متن به LLM با کنترل کامل"""
|
| 68 |
+
try:
|
| 69 |
+
# بررسی اولیه
|
| 70 |
+
if not text or not text.strip():
|
| 71 |
+
error_msg = "متن خالی است!" if lang == 'fa' else "Text is empty!"
|
| 72 |
+
logger.error(f"❌ {error_msg}")
|
| 73 |
+
return f"❌ {error_msg}"
|
| 74 |
+
|
| 75 |
+
if not self.api_key:
|
| 76 |
+
error_msg = "کلید API تنظیم نشده است!" if lang == 'fa' else "API Key not configured!"
|
| 77 |
+
logger.error(f"❌ {error_msg}")
|
| 78 |
+
return f"❌ {error_msg}"
|
| 79 |
+
|
| 80 |
+
# تنظیم system message پیشفرض
|
| 81 |
+
if system_msg is None:
|
| 82 |
+
system_msg = (
|
| 83 |
+
"شما یک تحلیلگر مالی حرفهای هستید. متن حاوی کدهای ناشناس است. "
|
| 84 |
+
"به سوالات با دقت پاسخ دهید."
|
| 85 |
+
if lang == 'fa'
|
| 86 |
+
else "You are a professional financial analyst. The text contains anonymous codes. "
|
| 87 |
+
"Answer questions accurately."
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# تهیه headers
|
| 91 |
+
headers = {
|
| 92 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 93 |
+
"Content-Type": "application/json"
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
# ساخت request body
|
| 97 |
+
data = {
|
| 98 |
+
"model": self.model,
|
| 99 |
+
"messages": [
|
| 100 |
+
{"role": "system", "content": system_msg},
|
| 101 |
+
{"role": "user", "content": text}
|
| 102 |
+
],
|
| 103 |
+
"max_tokens": max_tokens,
|
| 104 |
+
"temperature": temperature
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
# ارسال با retry mechanism
|
| 108 |
+
for attempt in range(retry_count):
|
| 109 |
+
try:
|
| 110 |
+
logger.info(f"📤 ارسال درخواست به {self.__class__.__name__} (تلاش {attempt + 1}/{retry_count})...")
|
| 111 |
+
|
| 112 |
+
response = requests.post(
|
| 113 |
+
self.base_url,
|
| 114 |
+
headers=headers,
|
| 115 |
+
json=data,
|
| 116 |
+
timeout=timeout
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# پردازش پاسخ موفق
|
| 120 |
+
if response.status_code == 200:
|
| 121 |
+
result = response.json()
|
| 122 |
+
llm_response = result['choices'][0]['message']['content']
|
| 123 |
+
logger.info("✅ پاسخ دریافت شد")
|
| 124 |
+
return llm_response
|
| 125 |
+
|
| 126 |
+
# پردازش خطاهای مختلف
|
| 127 |
+
elif response.status_code == 429: # Rate limiting
|
| 128 |
+
wait_time = 5 * (attempt + 1)
|
| 129 |
+
logger.warning(f"⚠️ Rate limit | صبر: {wait_time} ثانیه")
|
| 130 |
+
if attempt < retry_count - 1:
|
| 131 |
+
time.sleep(wait_time)
|
| 132 |
+
continue
|
| 133 |
+
else:
|
| 134 |
+
return (
|
| 135 |
+
"❌ سهمیه API تمام شده است. لطفاً بعداً تلاش کنید."
|
| 136 |
+
if lang == 'fa'
|
| 137 |
+
else "❌ API quota exceeded. Please try later."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
elif response.status_code == 401:
|
| 141 |
+
return (
|
| 142 |
+
"❌ کلید API نامعتبر است!"
|
| 143 |
+
if lang == 'fa'
|
| 144 |
+
else "❌ Invalid API key!"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
elif response.status_code in [502, 503, 504]: # Server errors
|
| 148 |
+
wait_time = 2 * (attempt + 1)
|
| 149 |
+
logger.warning(f"⚠️ Server error {response.status_code} | صبر: {wait_time} ثانیه")
|
| 150 |
+
if attempt < retry_count - 1:
|
| 151 |
+
time.sleep(wait_time)
|
| 152 |
+
continue
|
| 153 |
+
else:
|
| 154 |
+
return (
|
| 155 |
+
f"❌ خطای سرور: {response.status_code}"
|
| 156 |
+
if lang == 'fa'
|
| 157 |
+
else f"❌ Server error: {response.status_code}"
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
else:
|
| 161 |
+
# خطای دیگر
|
| 162 |
+
try:
|
| 163 |
+
error_data = response.json() if response.content else {}
|
| 164 |
+
# چک کنیم که error_data واقعاً dict باشه
|
| 165 |
+
if isinstance(error_data, dict):
|
| 166 |
+
error_msg = error_data.get('error', {}).get('message', response.text)
|
| 167 |
+
else:
|
| 168 |
+
# اگه string یا چیز دیگهای بود
|
| 169 |
+
error_msg = str(error_data)
|
| 170 |
+
except:
|
| 171 |
+
# اگه JSON parse نشد
|
| 172 |
+
error_msg = response.text[:200] # فقط 200 کاراکتر اول
|
| 173 |
+
|
| 174 |
+
logger.error(f"❌ API Error: {error_msg}")
|
| 175 |
+
return f"❌ API Error: {error_msg}"
|
| 176 |
+
|
| 177 |
+
except requests.exceptions.Timeout:
|
| 178 |
+
logger.warning("⚠️ Timeout | صبر: 3 ثانیه و تلاش مجدد")
|
| 179 |
+
if attempt < retry_count - 1:
|
| 180 |
+
time.sleep(3)
|
| 181 |
+
continue
|
| 182 |
+
else:
|
| 183 |
+
return (
|
| 184 |
+
"❌ خطای اتصال: timeout"
|
| 185 |
+
if lang == 'fa'
|
| 186 |
+
else "❌ Connection error: timeout"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
except requests.exceptions.ConnectionError as e:
|
| 190 |
+
logger.warning("⚠️ Connection error | صبر: 2 ثانیه و تلاش مجدد")
|
| 191 |
+
if attempt < retry_count - 1:
|
| 192 |
+
time.sleep(2)
|
| 193 |
+
continue
|
| 194 |
+
else:
|
| 195 |
+
return (
|
| 196 |
+
f"❌ خطای اتصال: {str(e)}"
|
| 197 |
+
if lang == 'fa'
|
| 198 |
+
else f"❌ Connection error: {str(e)}"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
logger.error(f"❌ خطای غیرمنتظره: {str(e)}")
|
| 203 |
+
return (
|
| 204 |
+
f"❌ خطا در ارتباط با LLM: {str(e)}"
|
| 205 |
+
if lang == 'fa'
|
| 206 |
+
else f"❌ Error connecting to LLM: {str(e)}"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class ChatGPTSender(LLMSender):
|
| 211 |
+
"""کلاس برای ارسال به ChatGPT"""
|
| 212 |
+
|
| 213 |
+
def __init__(self, api_key: Optional[str] = None, model: str = "gpt-4o-mini"):
|
| 214 |
+
# ✅ پاکسازی API key از فضاهای خالی و newline
|
| 215 |
+
raw_key = api_key or os.getenv("OPENAI_API_KEY", "")
|
| 216 |
+
cleaned_key = raw_key.strip() if raw_key else ""
|
| 217 |
+
|
| 218 |
+
super().__init__(cleaned_key, model)
|
| 219 |
+
self.base_url = self.get_base_url()
|
| 220 |
+
|
| 221 |
+
if not self.api_key:
|
| 222 |
+
logger.warning("⚠️ کلید OpenAI API تنظیم نشده است!")
|
| 223 |
+
|
| 224 |
+
def get_default_model(self) -> str:
|
| 225 |
+
return "gpt-4o-mini"
|
| 226 |
+
|
| 227 |
+
def get_base_url(self) -> str:
|
| 228 |
+
return "https://api.openai.com/v1/chat/completions"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class GrokSender(LLMSender):
|
| 232 |
+
"""کلاس برای ارسال به Grok (xAI)"""
|
| 233 |
+
|
| 234 |
+
def __init__(self, api_key: Optional[str] = None, model: str = "grok-beta"):
|
| 235 |
+
# ✅ پاکسازی API key از فضاهای خالی و newline
|
| 236 |
+
raw_key = api_key or os.getenv("XAI_API_KEY", "")
|
| 237 |
+
cleaned_key = raw_key.strip() if raw_key else ""
|
| 238 |
+
|
| 239 |
+
super().__init__(cleaned_key, model)
|
| 240 |
+
self.base_url = self.get_base_url()
|
| 241 |
+
|
| 242 |
+
if not self.api_key:
|
| 243 |
+
logger.warning("⚠️ کلید xAI API تنظیم نشده است!")
|
| 244 |
+
|
| 245 |
+
def get_default_model(self) -> str:
|
| 246 |
+
return "grok-beta"
|
| 247 |
+
|
| 248 |
+
def get_base_url(self) -> str:
|
| 249 |
+
return "https://api.x.ai/v1/chat/completions"
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# Factory function برای ایجاد sender مناسب
|
| 253 |
+
def create_llm_sender(
|
| 254 |
+
provider: str = "chatgpt",
|
| 255 |
+
api_key: Optional[str] = None,
|
| 256 |
+
model: Optional[str] = None
|
| 257 |
+
) -> LLMSender:
|
| 258 |
+
"""
|
| 259 |
+
ایجاد LLM sender بر اساس provider
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
provider: "chatgpt" یا "grok"
|
| 263 |
+
api_key: کلید API (اختیاری)
|
| 264 |
+
model: مدل (اختیاری، از پیشفرض استفاده میشود)
|
| 265 |
+
|
| 266 |
+
Returns:
|
| 267 |
+
instance از ChatGPTSender یا GrokSender
|
| 268 |
+
"""
|
| 269 |
+
provider = provider.lower()
|
| 270 |
+
|
| 271 |
+
if provider == "chatgpt":
|
| 272 |
+
if model is None:
|
| 273 |
+
model = "gpt-4o-mini"
|
| 274 |
+
return ChatGPTSender(api_key=api_key, model=model)
|
| 275 |
+
|
| 276 |
+
elif provider == "grok":
|
| 277 |
+
if model is None:
|
| 278 |
+
model = "grok-beta"
|
| 279 |
+
return GrokSender(api_key=api_key, model=model)
|
| 280 |
+
|
| 281 |
+
else:
|
| 282 |
+
raise ValueError(f"Provider نامعتبر: {provider}. باید 'chatgpt' یا 'grok' باشد")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# مدلهای موجود برای هر provider
|
| 286 |
+
AVAILABLE_MODELS = {
|
| 287 |
+
"chatgpt": [
|
| 288 |
+
"gpt-4o-mini",
|
| 289 |
+
"gpt-4o",
|
| 290 |
+
"gpt-4-turbo",
|
| 291 |
+
"gpt-3.5-turbo"
|
| 292 |
+
],
|
| 293 |
+
"grok": [
|
| 294 |
+
"grok-beta", # رایگان در بتا
|
| 295 |
+
"grok-3-mini", # ارزانتر
|
| 296 |
+
"grok-3", # flagship
|
| 297 |
+
"grok-2-1212" # نسخه قدیمیتر
|
| 298 |
+
]
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
print("=" * 60)
|
| 304 |
+
print("🤖 LLM Sender Unified - مثال استفاده")
|
| 305 |
+
print("=" * 60)
|
| 306 |
+
|
| 307 |
+
# مثال 1: ChatGPT
|
| 308 |
+
print("\n1️⃣ ChatGPT:")
|
| 309 |
+
chatgpt = create_llm_sender("chatgpt")
|
| 310 |
+
if chatgpt.api_key:
|
| 311 |
+
response = chatgpt.send_simple("سلام")
|
| 312 |
+
print(f"✅ پاسخ: {response[:100]}...")
|
| 313 |
+
else:
|
| 314 |
+
print("⚠️ کلید OpenAI API تنظیم نشده است!")
|
| 315 |
+
|
| 316 |
+
# مثال 2: Grok
|
| 317 |
+
print("\n2️⃣ Grok:")
|
| 318 |
+
grok = create_llm_sender("grok", model="grok-beta")
|
| 319 |
+
if grok.api_key:
|
| 320 |
+
response = grok.send_simple("سلام")
|
| 321 |
+
print(f"✅ پاسخ: {response[:100]}...")
|
| 322 |
+
else:
|
| 323 |
+
print("⚠️ کلید xAI API تنظیم نشده است!")
|
| 324 |
+
|
| 325 |
+
# مثال 3: لیست مدلها
|
| 326 |
+
print("\n3️⃣ مدلهای موجود:")
|
| 327 |
+
for provider, models in AVAILABLE_MODELS.items():
|
| 328 |
+
print(f"\n{provider.upper()}:")
|
| 329 |
+
for model in models:
|
| 330 |
+
print(f" - {model}")
|