web3cyberservices commited on
Commit
d201083
·
unverified ·
1 Parent(s): fca65a3

Update custom_logic.py

Browse files
Files changed (1) hide show
  1. api/custom_logic.py +67 -169
api/custom_logic.py CHANGED
@@ -18,7 +18,6 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
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:
@@ -28,184 +27,83 @@ async def process_custom_message(text: str, chat_id: int, history: str, tg_messa
28
  logger.warning(f"Ошибка инициализации фабрики ассистентов: {e}")
29
  factory = None
30
 
31
- # --- Настройки среды и валидация ACL ---
32
- tg_token = os.environ.get("TELEGRAM_BOT_TOKEN") or os.environ.get("TELEGRAM_TOKEN")
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
42
- chat_id = 0
43
-
44
- is_admin = (chat_id == admin_id)
45
- text = text.strip()
46
-
47
- async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=5.0)) as client:
48
-
49
- user_name = "Пользователь"
50
- if tg_token and chat_id != 0:
51
- try:
52
- chat_res = await client.post(f"{tg_base_url}/bot{tg_token}/getChat", json={"chat_id": chat_id})
53
- if chat_res.status_code == 200:
54
- user_name = chat_res.json().get("result", {}).get("first_name", "Пользователь")
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(
62
- f"{tg_base_url}/bot{tg_token}/sendMessage",
63
- json={
64
- "chat_id": admin_id,
65
- "text": f"🔔 **Чат-логгер:**\nПользователь {user_name} (`{chat_id}`) написал:\n\n_{text}_",
66
- "parse_mode": "Markdown"
67
- }
68
- )
69
- except Exception:
70
- pass
71
-
72
- # =====================================================================
73
- # БЛОК СИСТЕМНЫХ КОМАНД (ACL ЗАЩИТА)
74
- # =====================================================================
75
- if text.startswith(("/", "!")) and not is_admin:
76
- return f"⚠️ {user_name}, у вашего аккаунта отсутствует доступ к ядру Web3CyberAgent."
77
-
78
- if text.startswith("/send "):
79
- if not tg_token: return "❌ Ошибка среды: Токен Telegram не найден."
80
- cmd_body = text[6:].strip().split(" ", 1)
81
- if len(cmd_body) < 2: return "❌ Формат: `/send <chat_id> <текст>`"
82
- try:
83
- res = await client.post(f"{tg_base_url}/bot{tg_token}/sendMessage", json={"chat_id": cmd_body[0].strip(), "text": cmd_body[1].strip(), "parse_mode": "Markdown"})
84
- return "✅ Отправлено." if res.status_code == 200 else f"❌ Ошибка: {res.text}"
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"
93
- query = cmd_body[1].strip() if len(cmd_body) > 1 else text[8:].strip()
94
- try:
95
- return await search_in_group(target_group, query)
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:
104
- return await join_telegram_chat(invite_link)
105
- except Exception as e: return f"❌ Ошибка выполнения системного вызова: {str(e)}"
106
-
107
- if text == "/reload_rules":
108
- return factory.hot_reload_rules() if factory else "⚠️ Фабрика не активна."
109
-
110
- # =====================================================================
111
- # БЛОК ИИ-ДИАЛОГА (ОПТИМИЗИРОВАННЫЙ АСИНХРОННЫЙ СТЕК)
112
- # =====================================================================
113
- api_keys = {
114
- "cerebras": os.environ.get("CEREBRAS_API_KEY"),
115
- "sambanova": os.environ.get("SAMBANOVA_API_KEY"),
116
- "mistral": os.environ.get("MISTRAL_API_KEY"),
117
- "gemini": os.environ.get("GEMINI_API_KEY"),
118
- "groq": os.environ.get("GROQ_API_KEY")
119
- }
120
-
121
- # Инжектируем контекст DOM-дерева и куки в промпт для расширения Chrome
122
- context_payload = ""
123
- if page_code:
124
- context_payload += f"\n[КОНТЕКСТ СТРАНИЦЫ АУДИТА]:\nРазмер DOM: {len(page_code)} символов.\n"
125
- if page_cookies:
126
- context_payload += f"[СЕССИОННЫЕ COOKIES]: {page_cookies}\n"
127
-
128
- base_instruction = (
129
- f"Ты — Cyber-Agent, ИИ-помощник контура Web3CyberServices. "
130
- f"Помогаешь в OSINT, пентесте и автоматизации. Сейчас общаешься с {user_name}. "
131
- f"Отвечай развернуто, технически грамотно и структурировано.{context_payload}"
132
- )
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)
141
- if isinstance(json_history, list):
142
- messages.extend(json_history)
143
- except json.JSONDecodeError:
144
- current_role = None
145
- current_content = []
146
- for line in history.split('\n'):
147
- if line.startswith('User: '):
148
- if current_role:
149
- messages.append({"role": current_role, "content": '\n'.join(current_content).strip()})
150
- current_role = 'user'
151
- current_content = [line[6:]]
152
- elif line.startswith('Agent: '):
153
- if current_role:
154
- messages.append({"role": current_role, "content": '\n'.join(current_content).strip()})
155
- current_role = 'assistant'
156
- current_content = [line[7:]]
157
- else:
158
- if current_role:
159
- current_content.append(line)
160
- if current_role:
161
- messages.append({"role": current_role, "content": '\n'.join(current_content).strip()})
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']}"},
189
- "payload": {"model": "gemini-2.0-flash", "messages": messages, "max_tokens": 2048, "temperature": 0.5}
190
- })
191
-
192
- if not provider_pool:
193
- return "❌ Критическая ошибка конфигурации: Ни один API-ключ ИИ-провайдеров не найден в переменных окружения."
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
 
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
  search_in_group, join_telegram_chat = None, None
22
 
23
  try:
 
27
  logger.warning(f"Ошибка инициализации фабрики ассистентов: {e}")
28
  factory = None
29
 
30
+ # --- Настройки среды и валидация базовых промптов ---
31
+ base_instruction = (
32
+ "Ты — ведущий искусственный интеллект ИБ-агента школы Web3CyberServices. "
33
+ "Твоя речь должна быть точной, уверенной и лаконичной. "
34
+ "ОБЯЗАТЕЛЬНО обращайся к пользователю только по титулу 'Gospodin'."
35
+ )
36
 
37
+ # ИСПРАВЛЕНО: Добавлен await для асинхронного метода фабрики системного промпта.
38
+ # Это предотвращает передачу объекта корутины в JSON-пакеты.
39
+ if factory:
40
+ try:
41
+ system_prompt = await factory.create_assistant_prompt(base_instruction)
42
+ except Exception as fe:
43
+ logger.error(f"Ошибка при генерации динамического промпта: {fe}")
44
+ system_prompt = base_instruction
45
+ else:
46
+ system_prompt = base_instruction
47
+
48
+ # Формирование структуры сообщений для OpenAI-совместимых эндпоинтов
49
+ messages = [{"role": "system", "content": system_prompt}]
50
+ if history:
51
+ messages.append({"role": "system", "content": f"Предыдущий контекст беседы:\n{history}"})
52
+ messages.append({"role": "user", "content": text})
53
+
54
+ # --- Сбор пула ИИ-провайдеров с обработкой отказоустойчивости ---
55
+ provider_pool = []
56
+
57
+ gemini_key = os.environ.get("GEMINI_API_KEY")
58
+ if gemini_key:
59
+ provider_pool.append({
60
+ "name": "Gemini 2.0 Flash",
61
+ "url": f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={gemini_key}",
62
+ "headers": {},
63
+ "payload": {
64
+ "contents": [{
65
+ "parts": [{"text": f"{system_prompt}\n\nИстория контекста:\n{history}\n\nТекущая команда Господина: {text}"}]
66
+ }]
67
+ }
68
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ groq_key = os.environ.get("GROQ_API_KEY")
71
+ if groq_key:
72
+ provider_pool.append({
73
+ "name": "Groq Llama 3.3",
74
+ "url": "https://api.groq.com/openai/v1/chat/completions",
75
+ "headers": {"Authorization": f"Bearer {groq_key}"},
76
+ "payload": {
77
+ "model": "llama-3.3-70b-versatile",
78
+ "messages": messages,
79
+ "max_tokens": 2048,
80
+ "temperature": 0.4
81
+ }
82
+ })
83
+
84
+ if not provider_pool:
85
+ return "❌ Критическая ошибка конфигурации: Ни один API-ключ ИИ-провайдеров не найден в переменных окружения."
86
+
87
+ diagnostic_logs = []
88
+
89
+ # Единая асинхронная сессия для отправки запросов
90
+ async with httpx.AsyncClient(timeout=30.0) as client:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  for provider in provider_pool:
92
  try:
93
  headers = {**provider["headers"], "Content-Type": "application/json"}
94
  response = await client.post(provider["url"], headers=headers, json=provider["payload"])
95
 
96
  if response.status_code == 200:
 
97
  data = response.json()
98
+
99
+ # ИСПРАВЛЕНО: Раздельный безопасный разбор JSON структур под каждого провайдера
100
+ if "gemini" in provider["name"].lower():
101
+ answer = data.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text')
102
+ else:
103
+ answer = data.get('choices', [{}])[0].get('message', {}).get('content')
104
+
105
  if answer:
106
+ return answer.strip()
107
  else:
108
  diagnostic_logs.append(f"• `{provider['name']}` ➔ Ошибка: Пустой контент в ответе")
109
  continue