Spaces:
Sleeping
Sleeping
web3cyberservices commited on
Add files via upload
Browse files- api/index.py +56 -275
api/index.py
CHANGED
|
@@ -4,26 +4,19 @@ import importlib
|
|
| 4 |
import inspect
|
| 5 |
import requests
|
| 6 |
from fastapi import FastAPI, Request, BackgroundTasks
|
| 7 |
-
from google import genai
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
-
# 1. Конфигурация среды и от
|
| 12 |
TELEGRAM_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or os.environ.get("TELEGRAM_TOKEN")
|
| 13 |
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 14 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 15 |
-
|
| 16 |
-
# Токен Hugging Face (используется для сборки и как 4-й текстовый ИИ-контур)
|
| 17 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 18 |
|
| 19 |
-
# Парсинг пула ключей Groq
|
| 20 |
GROQ_RAW = os.environ.get("GROQ_API_KEY") or os.environ.get("GROQ_API_KEYS") or ""
|
| 21 |
GROQ_KEYS_POOL = [k.strip() for k in GROQ_RAW.split(",") if k.strip()]
|
| 22 |
|
| 23 |
-
# Конфигурация основного клиента Google Gemini
|
| 24 |
-
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 25 |
-
ai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
| 26 |
-
|
| 27 |
# 2. Конфигурация GitHub интеграции
|
| 28 |
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
|
| 29 |
GITHUB_REPO = os.environ.get("GITHUB_REPO")
|
|
@@ -33,9 +26,7 @@ CUSTOM_LOGIC_FILE = "api/custom_logic.py"
|
|
| 33 |
REQUIREMENTS_FILE = "requirements.txt"
|
| 34 |
|
| 35 |
def send_telegram_message(chat_id: int, text: str):
|
| 36 |
-
|
| 37 |
-
if not TELEGRAM_TOKEN:
|
| 38 |
-
return
|
| 39 |
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
|
| 40 |
try:
|
| 41 |
requests.post(url, json={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}, timeout=15)
|
|
@@ -43,70 +34,43 @@ def send_telegram_message(chat_id: int, text: str):
|
|
| 43 |
print(f"=== [ERROR] Send TG message failed: {str(e)} ===", flush=True)
|
| 44 |
|
| 45 |
def extract_code_block(raw_text: str, lang: str = "python") -> str:
|
| 46 |
-
"""Извлечение чистого Python-кода из разметки markdown."""
|
| 47 |
pattern = r"```" + str(lang) + r"\s*(.*?)\s*```"
|
| 48 |
match = re.search(pattern, raw_text, re.DOTALL | re.IGNORECASE)
|
| 49 |
-
if match
|
| 50 |
-
return match.group(1).strip()
|
| 51 |
-
return raw_text.strip()
|
| 52 |
|
| 53 |
def validate_python_code(code_str: str) -> tuple[bool, str]:
|
| 54 |
-
"""Пре-компиляция кода для жесткой проверки на SyntaxError."""
|
| 55 |
try:
|
| 56 |
compile(code_str, "<string>", "exec")
|
| 57 |
return True, ""
|
| 58 |
except SyntaxError as e:
|
| 59 |
-
return False, f"SyntaxError: {e.msg} (строка {e.lineno}
|
| 60 |
except Exception as e:
|
| 61 |
return False, f"Validation Failed: {str(e)}"
|
| 62 |
|
| 63 |
def get_bot_memory(chat_id: int) -> str:
|
| 64 |
-
|
| 65 |
-
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 66 |
-
return ""
|
| 67 |
url = f"{SUPABASE_URL}/rest/v1/bot_memory?chat_id=eq.{chat_id}&select=context"
|
| 68 |
headers = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}"}
|
| 69 |
try:
|
| 70 |
res = requests.get(url, headers=headers, timeout=5)
|
| 71 |
-
if res.status_code == 200 and res.json()
|
| 72 |
-
|
| 73 |
-
except Exception:
|
| 74 |
-
pass
|
| 75 |
-
return ""
|
| 76 |
|
| 77 |
def save_bot_memory(chat_id: int, new_context: str):
|
| 78 |
-
|
| 79 |
-
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 80 |
-
return
|
| 81 |
url = f"{SUPABASE_URL}/rest/v1/bot_memory"
|
| 82 |
-
headers = {
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
"Content-Type": "application/json",
|
| 86 |
-
"Prefer": "resolution=merge-duplicates"
|
| 87 |
-
}
|
| 88 |
-
payload = {"chat_id": chat_id, "context": new_context}
|
| 89 |
-
try:
|
| 90 |
-
requests.post(url, json=payload, headers=headers, timeout=5)
|
| 91 |
-
except Exception:
|
| 92 |
-
pass
|
| 93 |
|
| 94 |
def get_evolution_system_prompt() -> str:
|
| 95 |
-
return (
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
"Правила кодогенерации:\n"
|
| 100 |
-
"1. Возвращай только чистый код Python внутри блоков ```python ... ```.\n"
|
| 101 |
-
"2. Обязательно реализуй функцию `process_custom_message(user_text: str, chat_id: int, history: str) -> str`.\n"
|
| 102 |
-
"3. Если тебе нужны сторонние библиотеки, в самом конце текстового ответа (ВНЕ БЛОКА КОДА) добавь маркер:\n"
|
| 103 |
-
"[REQUIRED_PACKAGES: библиотека1, библиотека2]"
|
| 104 |
-
)
|
| 105 |
|
| 106 |
def get_file_from_github(target_path: str):
|
| 107 |
-
|
| 108 |
-
if not GITHUB_TOKEN or not GITHUB_REPO:
|
| 109 |
-
return "", None
|
| 110 |
import base64
|
| 111 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}?ref={GITHUB_BRANCH}"
|
| 112 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
|
@@ -115,249 +79,66 @@ def get_file_from_github(target_path: str):
|
|
| 115 |
if res.status_code == 200:
|
| 116 |
data = res.json()
|
| 117 |
return base64.b64decode(data["content"]).decode("utf-8"), data["sha"]
|
| 118 |
-
except
|
| 119 |
-
pass
|
| 120 |
return "", None
|
| 121 |
|
| 122 |
def commit_to_github(target_path: str, new_content: str, commit_message: str) -> bool:
|
| 123 |
-
|
| 124 |
-
if not GITHUB_TOKEN or not GITHUB_REPO:
|
| 125 |
-
return False
|
| 126 |
import base64
|
| 127 |
-
|
| 128 |
-
# Свежий SHA запрашивается прямо перед записью
|
| 129 |
_, sha = get_file_from_github(target_path)
|
| 130 |
-
|
| 131 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}"
|
| 132 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
| 133 |
-
payload = {
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
}
|
| 138 |
-
if sha:
|
| 139 |
-
payload["sha"] = sha
|
| 140 |
-
|
| 141 |
-
try:
|
| 142 |
-
res = requests.put(url, headers=headers, json=payload, timeout=10)
|
| 143 |
-
return res.status_code in [200, 201]
|
| 144 |
-
except Exception:
|
| 145 |
-
pass
|
| 146 |
-
return False
|
| 147 |
-
|
| 148 |
-
def update_requirements_if_needed(raw_ai_text: str):
|
| 149 |
-
"""Парсинг маркера пакетов и интеллектуальное обновление зависимостей."""
|
| 150 |
-
match = re.search(r"\[REQUIRED_PACKAGES:\s*(.*?)\]", raw_ai_text, re.IGNORECASE)
|
| 151 |
-
if not match:
|
| 152 |
-
return
|
| 153 |
-
|
| 154 |
-
packages = [p.strip().lower() for p in match.group(1).split(",") if p.strip()]
|
| 155 |
-
if not packages:
|
| 156 |
-
return
|
| 157 |
-
|
| 158 |
-
current_reqs, _ = get_file_from_github(REQUIREMENTS_FILE)
|
| 159 |
-
if not current_reqs:
|
| 160 |
-
current_reqs = ""
|
| 161 |
-
|
| 162 |
-
existing_lines = [line.strip().lower() for line in current_reqs.split("\n") if line.strip()]
|
| 163 |
-
|
| 164 |
-
updated = False
|
| 165 |
-
new_reqs_content = current_reqs.rstrip()
|
| 166 |
-
|
| 167 |
-
for pkg in packages:
|
| 168 |
-
if not any(pkg == existing.split("==")[0].strip() for existing in existing_lines):
|
| 169 |
-
new_reqs_content += f"\n{pkg}"
|
| 170 |
-
updated = True
|
| 171 |
-
|
| 172 |
-
if updated:
|
| 173 |
-
commit_to_github(REQUIREMENTS_FILE, new_reqs_content.strip() + "\n", "Auto-update dependencies via Evolution Master")
|
| 174 |
|
| 175 |
-
# ---
|
| 176 |
def background_evolution_worker(instruction: str, chat_id: int):
|
| 177 |
-
"
|
| 178 |
-
print(f"=== [BACKGROUND START] Starting mutation for chat {chat_id} ===", flush=True)
|
| 179 |
-
|
| 180 |
current_source, _ = get_file_from_github(CUSTOM_LOGIC_FILE)
|
| 181 |
-
prompt = f"
|
| 182 |
-
system_rules = get_evolution_system_prompt()
|
| 183 |
-
|
| 184 |
-
error_context = ""
|
| 185 |
-
max_retries = 3
|
| 186 |
|
| 187 |
-
for attempt in range(
|
| 188 |
-
full_contents = f"{system_rules}\n\nЗадача:\n{prompt}"
|
| 189 |
-
if error_context:
|
| 190 |
-
full_contents += f"\n\n⚠️ Предыдущий вариант вызвал ошибку компиляции:\n{error_context}\nИсправь синтаксис!"
|
| 191 |
-
|
| 192 |
raw_text = ""
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
if GROQ_KEYS_POOL:
|
| 196 |
-
for idx, current_key in enumerate(GROQ_KEYS_POOL):
|
| 197 |
-
try:
|
| 198 |
-
url = "https://api.groq.com/openai/v1/chat/completions"
|
| 199 |
-
headers = {"Authorization": f"Bearer {current_key}", "Content-Type": "application/json"}
|
| 200 |
-
payload = {
|
| 201 |
-
"model": "llama-3.3-70b-specdec",
|
| 202 |
-
"messages": [
|
| 203 |
-
{"role": "system", "content": system_rules},
|
| 204 |
-
{"role": "user", "content": full_contents}
|
| 205 |
-
],
|
| 206 |
-
"temperature": 0.2
|
| 207 |
-
}
|
| 208 |
-
res = requests.post(url, json=payload, headers=headers, timeout=25)
|
| 209 |
-
if res.status_code == 200:
|
| 210 |
-
raw_text = res.json()["choices"][0]["message"]["content"]
|
| 211 |
-
print(f"=== [INFO] Mutation generated via Groq (Account #{idx+1}) ===", flush=True)
|
| 212 |
-
break
|
| 213 |
-
elif res.status_code == 429:
|
| 214 |
-
print(f"=== [WARN] Groq Account #{idx+1} hit Rate Limit (429). Trying next... ===", flush=True)
|
| 215 |
-
except Exception as ge:
|
| 216 |
-
print(f"=== [WARN] Groq Account #{idx+1} request failed: {str(ge)} ===", flush=True)
|
| 217 |
-
|
| 218 |
-
# ЭШЕЛОН 2: Основной Gemini 2.5 Flash
|
| 219 |
-
if not raw_text and ai_client:
|
| 220 |
try:
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
print("=== [INFO] Mutation generated via Gemini 2.5 Flash ===", flush=True)
|
| 225 |
-
except Exception as gen_err:
|
| 226 |
-
print(f"=== [WARN] Gemini 2.5 Flash attempt {attempt+1} failed: {str(gen_err)} ===", flush=True)
|
| 227 |
-
|
| 228 |
-
# ЭШЕЛОН 3: Исправленный резервный контур Gemini 1.5 Flash (Новый SDK)
|
| 229 |
-
if not raw_text and ai_client:
|
| 230 |
-
try:
|
| 231 |
-
print(f"=== [FALLBACK] Activating Gemini 1.5 Flash Core on attempt {attempt+1} ===", flush=True)
|
| 232 |
-
response = ai_client.models.generate_content(model="gemini-1.5-flash", contents=full_contents)
|
| 233 |
-
if response and response.text:
|
| 234 |
-
raw_text = response.text
|
| 235 |
-
print("=== [INFO] Mutation generated via Gemini 1.5 Flash Fallback ===", flush=True)
|
| 236 |
-
except Exception as fallback_err:
|
| 237 |
-
print(f"=== [CRITICAL] Gemini 1.5 Flash failed: {str(fallback_err)} ===", flush=True)
|
| 238 |
-
|
| 239 |
-
# ЭШЕЛОН 4: Глубокий резерв через Hugging Face Inference API (Модель Qwen-2.5-72B)
|
| 240 |
-
if not raw_text and HF_TOKEN:
|
| 241 |
-
try:
|
| 242 |
-
print(f"=== [FALLBACK] Activating Hugging Face Inference API on attempt {attempt+1} ===", flush=True)
|
| 243 |
-
url = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct"
|
| 244 |
-
headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"}
|
| 245 |
-
payload = {
|
| 246 |
-
"inputs": f"<|system|>\n{system_rules}\n<|user|>\n{full_contents}\n<|assistant|>\n",
|
| 247 |
-
"parameters": {"max_new_tokens": 1500, "temperature": 0.2}
|
| 248 |
-
}
|
| 249 |
-
res = requests.post(url, json=payload, headers=headers, timeout=30)
|
| 250 |
if res.status_code == 200:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
elif isinstance(result_data, dict):
|
| 255 |
-
raw_text = result_data.get("generated_text", "")
|
| 256 |
-
|
| 257 |
-
if raw_text and "<|assistant|>" in raw_text:
|
| 258 |
-
raw_text = raw_text.split("<|assistant|>")[-1].strip()
|
| 259 |
-
|
| 260 |
-
print("=== [INFO] Mutation generated via Hugging Face Inference API ===", flush=True)
|
| 261 |
-
except Exception as hf_err:
|
| 262 |
-
print(f"=== [CRITICAL] Hugging Face Inference API failed: {str(hf_err)} ===", flush=True)
|
| 263 |
-
|
| 264 |
-
if not raw_text:
|
| 265 |
-
continue
|
| 266 |
-
|
| 267 |
-
generated_code = extract_code_block(raw_text)
|
| 268 |
-
is_valid, error_msg = validate_python_code(generated_code)
|
| 269 |
|
| 270 |
-
|
|
|
|
| 271 |
try:
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
return
|
| 282 |
-
|
| 283 |
-
error_context = error_msg
|
| 284 |
-
print(f"=== [RETRY] Attempt {attempt+1} failed syntax check: {error_msg} ===", flush=True)
|
| 285 |
-
|
| 286 |
-
send_telegram_message(chat_id, f"❌ Фоновая мутация провалилась после {max_retries} попыток.\nПоследний лог ошибки: `{error_context or 'Все ИИ-контуры и пулы ключей перегружены'}`")
|
| 287 |
|
| 288 |
-
@app.get("/")
|
| 289 |
-
async def status():
|
| 290 |
-
plugin_status = "not_found"
|
| 291 |
-
try:
|
| 292 |
-
importlib.invalidate_caches()
|
| 293 |
-
import api.custom_logic as custom
|
| 294 |
-
plugin_status = "active and running"
|
| 295 |
-
except SyntaxError as se:
|
| 296 |
-
plugin_status = f"SyntaxError in custom_logic: {str(se)}"
|
| 297 |
-
except ImportError:
|
| 298 |
-
plugin_status = "no custom_logic file yet"
|
| 299 |
-
except Exception as e:
|
| 300 |
-
plugin_status = f"Error: {str(e)}"
|
| 301 |
-
|
| 302 |
-
return {"status": "online", "sandbox_plugins": plugin_status}
|
| 303 |
-
|
| 304 |
-
@app.post("/")
|
| 305 |
@app.post("/tg-webhook")
|
| 306 |
async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
| 307 |
-
|
| 308 |
-
data = await request.json()
|
| 309 |
-
except Exception:
|
| 310 |
-
return {"status": "bad request"}
|
| 311 |
-
|
| 312 |
-
if "message" not in data or "text" not in data["message"]:
|
| 313 |
-
return {"status": "ok"}
|
| 314 |
-
|
| 315 |
chat_id = data["message"]["chat"]["id"]
|
| 316 |
-
|
| 317 |
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text": "❌ Не настроен GITHUB_TOKEN."}
|
| 322 |
-
|
| 323 |
-
background_tasks.add_task(background_evolution_worker, user_text[12:], chat_id)
|
| 324 |
-
return {
|
| 325 |
-
"method": "sendMessage",
|
| 326 |
-
"chat_id": chat_id,
|
| 327 |
-
"text": "⏳ **Запрос на мутацию принят в фоновый поток.**\nЯдро изолировало задачу. Начинаю генерацию кода через многоуровневый каскад ИИ (Groq/Gemini/HF)... Пожалуйста, подождите."
|
| 328 |
-
}
|
| 329 |
-
|
| 330 |
-
history = get_bot_memory(chat_id)
|
| 331 |
|
| 332 |
-
# Вызов кастомных плагинов
|
| 333 |
-
try:
|
| 334 |
-
importlib.invalidate_caches()
|
| 335 |
-
import api.custom_logic as custom
|
| 336 |
-
importlib.reload(custom)
|
| 337 |
-
|
| 338 |
-
if hasattr(custom, "process_custom_message"):
|
| 339 |
-
func = getattr(custom, "process_custom_message")
|
| 340 |
-
if inspect.iscoroutinefunction(func):
|
| 341 |
-
response_text = await func(user_text, chat_id, history)
|
| 342 |
-
else:
|
| 343 |
-
response_text = func(user_text, chat_id, history)
|
| 344 |
-
|
| 345 |
-
if response_text:
|
| 346 |
-
new_context = f"{history}\nUser: {user_text}\nAgent: {response_text}"
|
| 347 |
-
truncated_context = "\n".join(new_context.split("\n")[-20:])
|
| 348 |
-
save_bot_memory(chat_id, truncated_context)
|
| 349 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text": response_text}
|
| 350 |
-
except Exception as plugin_err:
|
| 351 |
-
print(f"=== [PLUGIN ERROR] {str(plugin_err)} ===", flush=True)
|
| 352 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text": f"⚠️ В плагине дефект: {str(plugin_err)}"}
|
| 353 |
-
|
| 354 |
-
# Локальный резервный режим
|
| 355 |
-
if not ai_client and not GROQ_KEYS_POOL and not HF_TOKEN:
|
| 356 |
-
fallback_msg = (
|
| 357 |
-
"🤖 Локальный режим Cyber-Agent.\n\n"
|
| 358 |
-
"⚠️ Внешние ИИ-интерфейсы временно недоступны.\n"
|
| 359 |
-
"Доступны ручные команды плагина, включая /osint."
|
| 360 |
-
)
|
| 361 |
-
return {"method": "sendMessage", "chat_id": chat_id, "text": fallback_msg}
|
| 362 |
-
|
| 363 |
return {"status": "ok"}
|
|
|
|
| 4 |
import inspect
|
| 5 |
import requests
|
| 6 |
from fastapi import FastAPI, Request, BackgroundTasks
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# 1. Конфигурация среды и отказоустойчивых ИИ-пулов
|
| 11 |
TELEGRAM_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or os.environ.get("TELEGRAM_TOKEN")
|
| 12 |
SUPABASE_URL = os.environ.get("SUPABASE_URL")
|
| 13 |
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
|
|
|
|
|
|
| 14 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 15 |
|
| 16 |
+
# Парсинг пула ключей Groq
|
| 17 |
GROQ_RAW = os.environ.get("GROQ_API_KEY") or os.environ.get("GROQ_API_KEYS") or ""
|
| 18 |
GROQ_KEYS_POOL = [k.strip() for k in GROQ_RAW.split(",") if k.strip()]
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# 2. Конфигурация GitHub интеграции
|
| 21 |
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
|
| 22 |
GITHUB_REPO = os.environ.get("GITHUB_REPO")
|
|
|
|
| 26 |
REQUIREMENTS_FILE = "requirements.txt"
|
| 27 |
|
| 28 |
def send_telegram_message(chat_id: int, text: str):
|
| 29 |
+
if not TELEGRAM_TOKEN: return
|
|
|
|
|
|
|
| 30 |
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
|
| 31 |
try:
|
| 32 |
requests.post(url, json={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}, timeout=15)
|
|
|
|
| 34 |
print(f"=== [ERROR] Send TG message failed: {str(e)} ===", flush=True)
|
| 35 |
|
| 36 |
def extract_code_block(raw_text: str, lang: str = "python") -> str:
|
|
|
|
| 37 |
pattern = r"```" + str(lang) + r"\s*(.*?)\s*```"
|
| 38 |
match = re.search(pattern, raw_text, re.DOTALL | re.IGNORECASE)
|
| 39 |
+
return match.group(1).strip() if match else raw_text.strip()
|
|
|
|
|
|
|
| 40 |
|
| 41 |
def validate_python_code(code_str: str) -> tuple[bool, str]:
|
|
|
|
| 42 |
try:
|
| 43 |
compile(code_str, "<string>", "exec")
|
| 44 |
return True, ""
|
| 45 |
except SyntaxError as e:
|
| 46 |
+
return False, f"SyntaxError: {e.msg} (строка {e.lineno})"
|
| 47 |
except Exception as e:
|
| 48 |
return False, f"Validation Failed: {str(e)}"
|
| 49 |
|
| 50 |
def get_bot_memory(chat_id: int) -> str:
|
| 51 |
+
if not SUPABASE_URL or not SUPABASE_KEY: return ""
|
|
|
|
|
|
|
| 52 |
url = f"{SUPABASE_URL}/rest/v1/bot_memory?chat_id=eq.{chat_id}&select=context"
|
| 53 |
headers = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}"}
|
| 54 |
try:
|
| 55 |
res = requests.get(url, headers=headers, timeout=5)
|
| 56 |
+
return res.json()[0]["context"] if res.status_code == 200 and res.json() else ""
|
| 57 |
+
except: return ""
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def save_bot_memory(chat_id: int, new_context: str):
|
| 60 |
+
if not SUPABASE_URL or not SUPABASE_KEY: return
|
|
|
|
|
|
|
| 61 |
url = f"{SUPABASE_URL}/rest/v1/bot_memory"
|
| 62 |
+
headers = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}", "Content-Type": "application/json", "Prefer": "resolution=merge-duplicates"}
|
| 63 |
+
try: requests.post(url, json={"chat_id": chat_id, "context": new_context}, headers=headers, timeout=5)
|
| 64 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
def get_evolution_system_prompt() -> str:
|
| 67 |
+
return ("Ты — автономный модуль расширения логики Web3CyberServices. "
|
| 68 |
+
"Пиши код только для api/custom_logic.py. НЕ меняй index.py. "
|
| 69 |
+
"Правила: чистый Python в ```python ... ```, реализуй функцию `process_custom_message`."
|
| 70 |
+
"Для библиотек используй маркер [REQUIRED_PACKAGES: пак1, пак2].")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
def get_file_from_github(target_path: str):
|
| 73 |
+
if not GITHUB_TOKEN or not GITHUB_REPO: return "", None
|
|
|
|
|
|
|
| 74 |
import base64
|
| 75 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}?ref={GITHUB_BRANCH}"
|
| 76 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
|
|
|
| 79 |
if res.status_code == 200:
|
| 80 |
data = res.json()
|
| 81 |
return base64.b64decode(data["content"]).decode("utf-8"), data["sha"]
|
| 82 |
+
except: pass
|
|
|
|
| 83 |
return "", None
|
| 84 |
|
| 85 |
def commit_to_github(target_path: str, new_content: str, commit_message: str) -> bool:
|
| 86 |
+
if not GITHUB_TOKEN or not GITHUB_REPO: return False
|
|
|
|
|
|
|
| 87 |
import base64
|
|
|
|
|
|
|
| 88 |
_, sha = get_file_from_github(target_path)
|
|
|
|
| 89 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}"
|
| 90 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
| 91 |
+
payload = {"message": commit_message, "content": base64.b64encode(new_content.encode("utf-8")).decode("utf-8"), "branch": GITHUB_BRANCH}
|
| 92 |
+
if sha: payload["sha"] = sha
|
| 93 |
+
try: return requests.put(url, headers=headers, json=payload, timeout=10).status_code in [200, 201]
|
| 94 |
+
except: return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# --- ОПТИМИЗИРОВАННЫЙ ВОРКЕР (БЕЗ GEMINI) ---
|
| 97 |
def background_evolution_worker(instruction: str, chat_id: int):
|
| 98 |
+
print(f"=== [BACKGROUND START] Mutation for {chat_id} ===", flush=True)
|
|
|
|
|
|
|
| 99 |
current_source, _ = get_file_from_github(CUSTOM_LOGIC_FILE)
|
| 100 |
+
prompt = f"{instruction}\n\nТекущий код:\n{current_source}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
for attempt in range(3):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
raw_text = ""
|
| 104 |
+
# 1. Groq Pool
|
| 105 |
+
for idx, key in enumerate(GROQ_KEYS_POOL):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
try:
|
| 107 |
+
res = requests.post("https://api.groq.com/openai/v1/chat/completions",
|
| 108 |
+
headers={"Authorization": f"Bearer {key}"},
|
| 109 |
+
json={"model": "llama-3.3-70b-specdec", "messages": [{"role": "user", "content": prompt}]}, timeout=20)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
if res.status_code == 200:
|
| 111 |
+
raw_text = res.json()["choices"][0]["message"]["content"]
|
| 112 |
+
break
|
| 113 |
+
except: continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# 2. HF Backup
|
| 116 |
+
if not raw_text and HF_TOKEN:
|
| 117 |
try:
|
| 118 |
+
res = requests.post("https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct",
|
| 119 |
+
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 120 |
+
json={"inputs": prompt, "parameters": {"max_new_tokens": 1000}}, timeout=30)
|
| 121 |
+
if res.status_code == 200:
|
| 122 |
+
raw_text = res.json()[0]["generated_text"]
|
| 123 |
+
except: pass
|
| 124 |
+
|
| 125 |
+
if raw_text:
|
| 126 |
+
code = extract_code_block(raw_text)
|
| 127 |
+
valid, msg = validate_python_code(code)
|
| 128 |
+
if valid:
|
| 129 |
+
commit_to_github(CUSTOM_LOGIC_FILE, code, "Evolution")
|
| 130 |
+
send_telegram_message(chat_id, "✅ Эволюция завершена.")
|
| 131 |
return
|
| 132 |
+
send_telegram_message(chat_id, "❌ Ошибка: все ИИ-контуры недоступны.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
@app.post("/tg-webhook")
|
| 135 |
async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
| 136 |
+
data = await request.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
chat_id = data["message"]["chat"]["id"]
|
| 138 |
+
text = data["message"]["text"].strip()
|
| 139 |
|
| 140 |
+
if text.lower().startswith("улучши себя:"):
|
| 141 |
+
background_tasks.add_task(background_evolution_worker, text[12:], chat_id)
|
| 142 |
+
return {"method": "sendMessage", "chat_id": chat_id, "text": "⏳ Мутация запущена..."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
return {"status": "ok"}
|