web3cyberservices commited on
Commit
72d6152
·
unverified ·
1 Parent(s): 309408d

Update custom_logic.py

Browse files
Files changed (1) hide show
  1. api/custom_logic.py +32 -13
api/custom_logic.py CHANGED
@@ -16,14 +16,16 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
16
  # --- Безопасный изолированный импорт смежных модулей юзербота ---
17
  try:
18
  from api.user_client import search_in_group, join_telegram_chat
19
- except (ImportError, ModuleNotFoundError):
20
- logger.error("Критическое предупреждение среды: модуль api.user_client не найден на сервере.")
21
- search_in_group, join_telegram_chat = null, null
 
22
 
23
  try:
24
  from api.assistant_factory import AssistantFactory
25
  factory = AssistantFactory(logger_agent=None)
26
- except Exception:
 
27
  factory = None
28
 
29
  # --- Настройки среды и валидация ACL ---
@@ -31,7 +33,9 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
31
  tg_base_url = os.environ.get("TELEGRAM_BASE_URL", "https://api.telegram.org").rstrip("/")
32
 
33
  try:
34
- admin_id = int(os.environ.get("ADMIN_CHAT_ID", 7933414267))
 
 
35
  chat_id = int(chat_id)
36
  except (ValueError, TypeError):
37
  admin_id = 7933414267
@@ -51,6 +55,7 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
51
  except Exception as e:
52
  logger.warning(f"Не удалось получить имя чата: {e}")
53
 
 
54
  if not is_admin and tg_token and chat_id != 0:
55
  try:
56
  await client.post(
@@ -80,7 +85,8 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
80
  except Exception as e: return f"❌ Ошибка транспорта: {str(e)}"
81
 
82
  if text.startswith("/search "):
83
- if not search_in_group: return "❌ Системный вызов заблокирован: модуль api.user_client недоступен на хосте."
 
84
  cmd_body = text[8:].strip().split(" ", 1)
85
  if not cmd_body[0]: return "❌ Укажите параметры поиска."
86
  target_group = cmd_body[0].strip() if cmd_body[0].startswith(("@", "t.me")) else "@web3cyberservices_info"
@@ -90,7 +96,8 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
90
  except Exception as e: return f"❌ Ошибка поиска: {str(e)}"
91
 
92
  if text.startswith("/join "):
93
- if not join_telegram_chat: return "❌ Системный вызов заблокирован: модуль api.user_client недоступен на хосте."
 
94
  invite_link = text[6:].strip()
95
  if not invite_link: return "❌ Укажите инвайт-ссылку."
96
  try:
@@ -126,6 +133,8 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
126
  system_prompt = factory.create_assistant_prompt(base_instruction) if factory else base_instruction
127
 
128
  messages = [{"role": "system", "content": system_prompt}]
 
 
129
  if isinstance(history, str) and history.strip():
130
  try:
131
  json_history = json.loads(history)
@@ -153,26 +162,27 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
153
 
154
  messages.append({"role": "user", "content": text})
155
 
 
156
  provider_pool = []
157
- if api_keys["groq"]:
158
  provider_pool.append({
159
  "name": "Groq Llama 3.3 70B", "url": "https://api.groq.com/openai/v1/chat/completions",
160
  "headers": {"Authorization": f"Bearer {api_keys['groq']}"},
161
  "payload": {"model": "llama-3.3-70b-versatile", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
162
  })
163
- if api_keys["cerebras"]:
164
  provider_pool.append({
165
  "name": "Cerebras Systems", "url": "https://api.cerebras.ai/v1/chat/completions",
166
  "headers": {"Authorization": f"Bearer {api_keys['cerebras']}"},
167
  "payload": {"model": "llama3.3-70b", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
168
  })
169
- if api_keys["sambanova"]:
170
  provider_pool.append({
171
  "name": "SambaNova Cloud", "url": "https://api.sambanova.ai/v1/chat/completions",
172
  "headers": {"Authorization": f"Bearer {api_keys['sambanova']}"},
173
  "payload": {"model": "Meta-Llama-3.3-70B-Instruct", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
174
  })
175
- if api_keys["gemini"]:
176
  provider_pool.append({
177
  "name": "Google Gemini 2.0 Flash", "url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
178
  "headers": {"Authorization": f"Bearer {api_keys['gemini']}"},
@@ -184,16 +194,25 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
184
 
185
  diagnostic_logs = []
186
 
 
187
  for provider in provider_pool:
188
  try:
189
  headers = {**provider["headers"], "Content-Type": "application/json"}
190
  response = await client.post(provider["url"], headers=headers, json=provider["payload"])
 
191
  if response.status_code == 200:
192
- return response.json()['choices'][0]['message']['content']
 
 
 
 
 
 
 
193
 
194
  diagnostic_logs.append(f"• `{provider['name']}` ➔ HTTP {response.status_code}")
195
  except Exception as e:
196
- diagnostic_logs.append(f"• `{provider['name']}` ➔ Ошибка: {str(e)}")
197
  continue
198
 
199
  return f"❌ Все контуры инференса недоступны.\n\n**Отчет системы:**\n" + "\n".join(diagnostic_logs)
 
16
  # --- Безопасный изолированный импорт смежных модулей юзербота ---
17
  try:
18
  from api.user_client import search_in_group, join_telegram_chat
19
+ except (ImportError, ModuleNotFoundError) as e:
20
+ logger.error(f"Критическое предупреждение среды: модуль api.user_client не найден: {e}")
21
+ # ИСПРАВЛЕНО: Строго None вместо null
22
+ search_in_group, join_telegram_chat = None, None
23
 
24
  try:
25
  from api.assistant_factory import AssistantFactory
26
  factory = AssistantFactory(logger_agent=None)
27
+ except Exception as e:
28
+ logger.warning(f"Ошибка инициализации фабрики ассистентов: {e}")
29
  factory = None
30
 
31
  # --- Настройки среды и валидация ACL ---
 
33
  tg_base_url = os.environ.get("TELEGRAM_BASE_URL", "https://api.telegram.org").rstrip("/")
34
 
35
  try:
36
+ # ИСПРАВЛЕНО: Безопасный парсинг переменных окружения
37
+ admin_id_raw = os.environ.get("ADMIN_CHAT_ID", "7933414267")
38
+ admin_id = int(admin_id_raw)
39
  chat_id = int(chat_id)
40
  except (ValueError, TypeError):
41
  admin_id = 7933414267
 
55
  except Exception as e:
56
  logger.warning(f"Не удалось получить имя чата: {e}")
57
 
58
+ # Чат-логгер для пересылки сообщений администратору
59
  if not is_admin and tg_token and chat_id != 0:
60
  try:
61
  await client.post(
 
85
  except Exception as e: return f"❌ Ошибка транспорта: {str(e)}"
86
 
87
  if text.startswith("/search "):
88
+ if search_in_group is None:
89
+ return "❌ Системный вызов заблокирован: модуль api.user_client недоступен на хосте."
90
  cmd_body = text[8:].strip().split(" ", 1)
91
  if not cmd_body[0]: return "❌ Укажите параметры поиска."
92
  target_group = cmd_body[0].strip() if cmd_body[0].startswith(("@", "t.me")) else "@web3cyberservices_info"
 
96
  except Exception as e: return f"❌ Ошибка поиска: {str(e)}"
97
 
98
  if text.startswith("/join "):
99
+ if join_telegram_chat is None:
100
+ return "❌ Системный вызов заблокирован: модуль api.user_client недоступен на хосте."
101
  invite_link = text[6:].strip()
102
  if not invite_link: return "❌ Укажите инвайт-ссылку."
103
  try:
 
133
  system_prompt = factory.create_assistant_prompt(base_instruction) if factory else base_instruction
134
 
135
  messages = [{"role": "system", "content": system_prompt}]
136
+
137
+ # Безопасный парсинг истории диалога
138
  if isinstance(history, str) and history.strip():
139
  try:
140
  json_history = json.loads(history)
 
162
 
163
  messages.append({"role": "user", "content": text})
164
 
165
+ # Формирование пула доступных провайдеров
166
  provider_pool = []
167
+ if api_keys.get("groq"):
168
  provider_pool.append({
169
  "name": "Groq Llama 3.3 70B", "url": "https://api.groq.com/openai/v1/chat/completions",
170
  "headers": {"Authorization": f"Bearer {api_keys['groq']}"},
171
  "payload": {"model": "llama-3.3-70b-versatile", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
172
  })
173
+ if api_keys.get("cerebras"):
174
  provider_pool.append({
175
  "name": "Cerebras Systems", "url": "https://api.cerebras.ai/v1/chat/completions",
176
  "headers": {"Authorization": f"Bearer {api_keys['cerebras']}"},
177
  "payload": {"model": "llama3.3-70b", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
178
  })
179
+ if api_keys.get("sambanova"):
180
  provider_pool.append({
181
  "name": "SambaNova Cloud", "url": "https://api.sambanova.ai/v1/chat/completions",
182
  "headers": {"Authorization": f"Bearer {api_keys['sambanova']}"},
183
  "payload": {"model": "Meta-Llama-3.3-70B-Instruct", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
184
  })
185
+ if api_keys.get("gemini"):
186
  provider_pool.append({
187
  "name": "Google Gemini 2.0 Flash", "url": "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
188
  "headers": {"Authorization": f"Bearer {api_keys['gemini']}"},
 
194
 
195
  diagnostic_logs = []
196
 
197
+ # Каскадный опрос ИИ-моделей
198
  for provider in provider_pool:
199
  try:
200
  headers = {**provider["headers"], "Content-Type": "application/json"}
201
  response = await client.post(provider["url"], headers=headers, json=provider["payload"])
202
+
203
  if response.status_code == 200:
204
+ # ИСПРАВЛЕНО: Безопасное извлечение ключей из JSON без риска выброса KeyError/IndexError
205
+ data = response.json()
206
+ answer = data.get('choices', [{}])[0].get('message', {}).get('content')
207
+ if answer:
208
+ return answer
209
+ else:
210
+ diagnostic_logs.append(f"• `{provider['name']}` ➔ Ошибка: Пустой контент в ответе")
211
+ continue
212
 
213
  diagnostic_logs.append(f"• `{provider['name']}` ➔ HTTP {response.status_code}")
214
  except Exception as e:
215
+ diagnostic_logs.append(f"• `{provider['name']}` ➔ Ошибка сети: {str(e)}")
216
  continue
217
 
218
  return f"❌ Все контуры инференса недоступны.\n\n**Отчет системы:**\n" + "\n".join(diagnostic_logs)