Spaces:
Sleeping
Sleeping
web3cyberservices commited on
Add files via upload
Browse files- api/index.py +46 -30
api/index.py
CHANGED
|
@@ -24,20 +24,19 @@ CUSTOM_LOGIC_FILE = "api/custom_logic.py"
|
|
| 24 |
REQUIREMENTS_FILE = "requirements.txt"
|
| 25 |
|
| 26 |
ai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
| 27 |
-
TARGET_MODEL = "gemini-2.5-flash"
|
| 28 |
|
| 29 |
def send_telegram_message(chat_id: int, text: str):
|
| 30 |
-
"""Прямая отправка сообщений в Telegram вне контекста вебхука."""
|
| 31 |
if not TELEGRAM_TOKEN:
|
| 32 |
return
|
| 33 |
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
|
| 34 |
try:
|
| 35 |
-
requests.post(url, json={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}, timeout=
|
| 36 |
except Exception as e:
|
| 37 |
print(f"=== [ERROR] Send TG message failed: {str(e)} ===", flush=True)
|
| 38 |
|
| 39 |
def extract_code_block(raw_text: str, lang: str = "python") -> str:
|
| 40 |
-
"""Извлечение чистого Python-кода."""
|
| 41 |
pattern = r"```" + str(lang) + r"\s*(.*?)\s*```"
|
| 42 |
match = re.search(pattern, raw_text, re.DOTALL | re.IGNORECASE)
|
| 43 |
if match:
|
|
@@ -113,11 +112,15 @@ def get_file_from_github(target_path: str):
|
|
| 113 |
pass
|
| 114 |
return "", None
|
| 115 |
|
| 116 |
-
def commit_to_github(target_path: str, new_content: str,
|
| 117 |
-
"""Запись файла в репозиторий GitHub."""
|
| 118 |
if not GITHUB_TOKEN or not GITHUB_REPO:
|
| 119 |
return False
|
| 120 |
import base64
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}"
|
| 122 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
| 123 |
payload = {
|
|
@@ -127,6 +130,7 @@ def commit_to_github(target_path: str, new_content: str, sha: str, commit_messag
|
|
| 127 |
}
|
| 128 |
if sha:
|
| 129 |
payload["sha"] = sha
|
|
|
|
| 130 |
try:
|
| 131 |
res = requests.put(url, headers=headers, json=payload, timeout=10)
|
| 132 |
return res.status_code in [200, 201]
|
|
@@ -135,7 +139,7 @@ def commit_to_github(target_path: str, new_content: str, sha: str, commit_messag
|
|
| 135 |
return False
|
| 136 |
|
| 137 |
def update_requirements_if_needed(raw_ai_text: str):
|
| 138 |
-
"""Парсинг маркера пакетов и обновление
|
| 139 |
match = re.search(r"\[REQUIRED_PACKAGES:\s*(.*?)\]", raw_ai_text, re.IGNORECASE)
|
| 140 |
if not match:
|
| 141 |
return
|
|
@@ -144,8 +148,8 @@ def update_requirements_if_needed(raw_ai_text: str):
|
|
| 144 |
if not packages:
|
| 145 |
return
|
| 146 |
|
| 147 |
-
current_reqs,
|
| 148 |
-
if
|
| 149 |
current_reqs = ""
|
| 150 |
|
| 151 |
existing_lines = [line.strip().lower() for line in current_reqs.split("\n") if line.strip()]
|
|
@@ -154,32 +158,34 @@ def update_requirements_if_needed(raw_ai_text: str):
|
|
| 154 |
new_reqs_content = current_reqs.rstrip()
|
| 155 |
|
| 156 |
for pkg in packages:
|
|
|
|
| 157 |
if not any(pkg == existing.split("==")[0].strip() for existing in existing_lines):
|
| 158 |
new_reqs_content += f"\n{pkg}"
|
| 159 |
updated = True
|
| 160 |
|
| 161 |
if updated:
|
| 162 |
-
commit_to_github(REQUIREMENTS_FILE, new_reqs_content.strip() + "\n",
|
| 163 |
|
| 164 |
-
# --- ФОНОВЫЙ КОНТУР МУТАЦИИ ---
|
| 165 |
def background_evolution_worker(instruction: str, chat_id: int):
|
| 166 |
-
"""
|
| 167 |
print(f"=== [BACKGROUND START] Starting mutation for chat {chat_id} ===", flush=True)
|
| 168 |
|
| 169 |
-
current_source,
|
| 170 |
prompt = f"Добавь/обнови функционал по инструкции: {instruction}\n\nТекущий код кастомной логики:\n{current_source}"
|
| 171 |
system_rules = get_evolution_system_prompt()
|
| 172 |
|
| 173 |
error_context = ""
|
| 174 |
max_retries = 3
|
| 175 |
-
raw_text = ""
|
| 176 |
|
| 177 |
for attempt in range(max_retries):
|
| 178 |
full_contents = f"{system_rules}\n\nЗадача:\n{prompt}"
|
| 179 |
if error_context:
|
| 180 |
full_contents += f"\n\n⚠️ Предыдущий вариант вызвал ошибку компиляции:\n{error_context}\nИсправь синтаксис!"
|
| 181 |
|
| 182 |
-
|
|
|
|
|
|
|
| 183 |
if GROQ_API_KEY:
|
| 184 |
try:
|
| 185 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
|
@@ -192,22 +198,33 @@ def background_evolution_worker(instruction: str, chat_id: int):
|
|
| 192 |
],
|
| 193 |
"temperature": 0.2
|
| 194 |
}
|
| 195 |
-
res = requests.post(url, json=payload, headers=headers, timeout=
|
| 196 |
if res.status_code == 200:
|
| 197 |
raw_text = res.json()["choices"][0]["message"]["content"]
|
| 198 |
-
print("=== [INFO] Mutation generated via Groq ===", flush=True)
|
| 199 |
except Exception as ge:
|
| 200 |
print(f"=== [WARN] Groq attempt {attempt+1} failed: {str(ge)} ===", flush=True)
|
| 201 |
|
| 202 |
-
#
|
| 203 |
if not raw_text and ai_client:
|
| 204 |
try:
|
| 205 |
-
response = ai_client.models.generate_content(model=
|
| 206 |
if response and response.text:
|
| 207 |
raw_text = response.text
|
| 208 |
-
print("=== [INFO] Mutation generated via Gemini ===", flush=True)
|
| 209 |
except Exception as gen_err:
|
| 210 |
-
print(f"=== [WARN] Gemini attempt {attempt+1} failed: {str(gen_err)} ===", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
if not raw_text:
|
| 213 |
continue
|
|
@@ -216,24 +233,24 @@ def background_evolution_worker(instruction: str, chat_id: int):
|
|
| 216 |
is_valid, error_msg = validate_python_code(generated_code)
|
| 217 |
|
| 218 |
if is_valid:
|
| 219 |
-
# Обновл
|
| 220 |
try:
|
| 221 |
update_requirements_if_needed(raw_text)
|
| 222 |
except Exception as req_err:
|
| 223 |
print(f"=== [WARN] Requirements update failed: {str(req_err)} ===", flush=True)
|
| 224 |
|
| 225 |
-
#
|
| 226 |
-
if commit_to_github(CUSTOM_LOGIC_FILE, generated_code,
|
| 227 |
-
send_telegram_message(chat_id, "✅ **Эволюция завершена успешно!**\nМодуль `custom_logic.py` обновлен и прошел синтаксический контроль.
|
| 228 |
return
|
| 229 |
else:
|
| 230 |
-
send_telegram_message(chat_id, "❌ Ошибка записи коммита
|
| 231 |
return
|
| 232 |
|
| 233 |
error_context = error_msg
|
| 234 |
print(f"=== [RETRY] Attempt {attempt+1} failed syntax check: {error_msg} ===", flush=True)
|
| 235 |
|
| 236 |
-
send_telegram_message(chat_id, f"❌ Фоновая мутация провалилась после {max_retries} попыток.\nПоследний лог ошибки: `{error_context or 'Все ИИ-контуры
|
| 237 |
|
| 238 |
@app.get("/")
|
| 239 |
async def status():
|
|
@@ -265,12 +282,11 @@ async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
|
| 265 |
chat_id = data["message"]["chat"]["id"]
|
| 266 |
user_text = data["message"]["text"].strip()
|
| 267 |
|
| 268 |
-
# Режим эволюции плагинов (
|
| 269 |
if user_text.lower().startswith("улучши себя:"):
|
| 270 |
if not GITHUB_TOKEN:
|
| 271 |
return {"method": "sendMessage", "chat_id": chat_id, "text": "❌ Не настроен GITHUB_TOKEN."}
|
| 272 |
|
| 273 |
-
# Добавляем задачу в фоновый поток FastAPI и моментально возвращаем ответ Телеграму
|
| 274 |
background_tasks.add_task(background_evolution_worker, user_text[12:], chat_id)
|
| 275 |
return {
|
| 276 |
"method": "sendMessage",
|
|
@@ -302,7 +318,7 @@ async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
|
| 302 |
print(f"=== [PLUGIN ERROR] {str(plugin_err)} ===", flush=True)
|
| 303 |
return {"method": "sendMessage", "chat_id": chat_id, "text": f"⚠️ В плагине дефект: {str(plugin_err)}"}
|
| 304 |
|
| 305 |
-
# Локальный резервный режим (если ИИ-контуры
|
| 306 |
if not ai_client and not GROQ_API_KEY:
|
| 307 |
fallback_msg = (
|
| 308 |
"🤖 Локальный режим Cyber-Agent.\n\n"
|
|
|
|
| 24 |
REQUIREMENTS_FILE = "requirements.txt"
|
| 25 |
|
| 26 |
ai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
|
|
|
| 27 |
|
| 28 |
def send_telegram_message(chat_id: int, text: str):
|
| 29 |
+
"""Прямая отправка сообщений в Telegram вне контекста вебхука с повышенным таймаутом."""
|
| 30 |
if not TELEGRAM_TOKEN:
|
| 31 |
return
|
| 32 |
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
|
| 33 |
try:
|
| 34 |
+
requests.post(url, json={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}, timeout=15)
|
| 35 |
except Exception as e:
|
| 36 |
print(f"=== [ERROR] Send TG message failed: {str(e)} ===", flush=True)
|
| 37 |
|
| 38 |
def extract_code_block(raw_text: str, lang: str = "python") -> str:
|
| 39 |
+
"""Извлечение чистого Python-кода из разметки markdown."""
|
| 40 |
pattern = r"```" + str(lang) + r"\s*(.*?)\s*```"
|
| 41 |
match = re.search(pattern, raw_text, re.DOTALL | re.IGNORECASE)
|
| 42 |
if match:
|
|
|
|
| 112 |
pass
|
| 113 |
return "", None
|
| 114 |
|
| 115 |
+
def commit_to_github(target_path: str, new_content: str, commit_message: str) -> bool:
|
| 116 |
+
"""Запись файла в репозиторий GitHub с динамическим получением актуального SHA."""
|
| 117 |
if not GITHUB_TOKEN or not GITHUB_REPO:
|
| 118 |
return False
|
| 119 |
import base64
|
| 120 |
+
|
| 121 |
+
# Запрашиваем актуальный SHA непосредственно перед записью (Защита от 409 Conflict)
|
| 122 |
+
_, sha = get_file_from_github(target_path)
|
| 123 |
+
|
| 124 |
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{target_path}"
|
| 125 |
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
|
| 126 |
payload = {
|
|
|
|
| 130 |
}
|
| 131 |
if sha:
|
| 132 |
payload["sha"] = sha
|
| 133 |
+
|
| 134 |
try:
|
| 135 |
res = requests.put(url, headers=headers, json=payload, timeout=10)
|
| 136 |
return res.status_code in [200, 201]
|
|
|
|
| 139 |
return False
|
| 140 |
|
| 141 |
def update_requirements_if_needed(raw_ai_text: str):
|
| 142 |
+
"""Парсинг маркера пакетов и интеллектуальное обновление зависимостей."""
|
| 143 |
match = re.search(r"\[REQUIRED_PACKAGES:\s*(.*?)\]", raw_ai_text, re.IGNORECASE)
|
| 144 |
if not match:
|
| 145 |
return
|
|
|
|
| 148 |
if not packages:
|
| 149 |
return
|
| 150 |
|
| 151 |
+
current_reqs, _ = get_file_from_github(REQUIREMENTS_FILE)
|
| 152 |
+
if not current_reqs:
|
| 153 |
current_reqs = ""
|
| 154 |
|
| 155 |
existing_lines = [line.strip().lower() for line in current_reqs.split("\n") if line.strip()]
|
|
|
|
| 158 |
new_reqs_content = current_reqs.rstrip()
|
| 159 |
|
| 160 |
for pkg in packages:
|
| 161 |
+
# Проверка без учета зафиксированных версий (==)
|
| 162 |
if not any(pkg == existing.split("==")[0].strip() for existing in existing_lines):
|
| 163 |
new_reqs_content += f"\n{pkg}"
|
| 164 |
updated = True
|
| 165 |
|
| 166 |
if updated:
|
| 167 |
+
commit_to_github(REQUIREMENTS_FILE, new_reqs_content.strip() + "\n", "Auto-update dependencies via Evolution Master")
|
| 168 |
|
| 169 |
+
# --- СВЕРХУСТОЙЧИВЫЙ ФОНОВЫЙ КОНТУР МУТАЦИИ ---
|
| 170 |
def background_evolution_worker(instruction: str, chat_id: int):
|
| 171 |
+
"""Фоновый воркер с тройным каскадом ИИ-моделей и защитой от перегрузок."""
|
| 172 |
print(f"=== [BACKGROUND START] Starting mutation for chat {chat_id} ===", flush=True)
|
| 173 |
|
| 174 |
+
current_source, _ = get_file_from_github(CUSTOM_LOGIC_FILE)
|
| 175 |
prompt = f"Добавь/обнови функционал по инструкции: {instruction}\n\nТекущий код кастомной логики:\n{current_source}"
|
| 176 |
system_rules = get_evolution_system_prompt()
|
| 177 |
|
| 178 |
error_context = ""
|
| 179 |
max_retries = 3
|
|
|
|
| 180 |
|
| 181 |
for attempt in range(max_retries):
|
| 182 |
full_contents = f"{system_rules}\n\nЗадача:\n{prompt}"
|
| 183 |
if error_context:
|
| 184 |
full_contents += f"\n\n⚠️ Предыдущий вариант вызвал ошибку компиляции:\n{error_context}\nИсправь синтаксис!"
|
| 185 |
|
| 186 |
+
raw_text = ""
|
| 187 |
+
|
| 188 |
+
# Контур 1: Быстрый Groq (Llama-3.3)
|
| 189 |
if GROQ_API_KEY:
|
| 190 |
try:
|
| 191 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
|
|
|
| 198 |
],
|
| 199 |
"temperature": 0.2
|
| 200 |
}
|
| 201 |
+
res = requests.post(url, json=payload, headers=headers, timeout=25)
|
| 202 |
if res.status_code == 200:
|
| 203 |
raw_text = res.json()["choices"][0]["message"]["content"]
|
| 204 |
+
print("=== [INFO] Mutation generated via Groq (Llama-3.3) ===", flush=True)
|
| 205 |
except Exception as ge:
|
| 206 |
print(f"=== [WARN] Groq attempt {attempt+1} failed: {str(ge)} ===", flush=True)
|
| 207 |
|
| 208 |
+
# Контур 2: Основной Gemini 2.5 Flash
|
| 209 |
if not raw_text and ai_client:
|
| 210 |
try:
|
| 211 |
+
response = ai_client.models.generate_content(model="gemini-2.5-flash", contents=full_contents)
|
| 212 |
if response and response.text:
|
| 213 |
raw_text = response.text
|
| 214 |
+
print("=== [INFO] Mutation generated via Gemini 2.5 Flash ===", flush=True)
|
| 215 |
except Exception as gen_err:
|
| 216 |
+
print(f"=== [WARN] Gemini 2.5 Flash attempt {attempt+1} failed: {str(gen_err)} ===", flush=True)
|
| 217 |
+
|
| 218 |
+
# Контур 3: Сверхстабильный резервный Gemini 1.5 Flash (Защита от 503)
|
| 219 |
+
if not raw_text and ai_client:
|
| 220 |
+
try:
|
| 221 |
+
print(f"=== [FALLBACK] Activating Gemini 1.5 Flash Core on attempt {attempt+1} ===", flush=True)
|
| 222 |
+
response = ai_client.models.generate_content(model="gemini-1.5-flash", contents=full_contents)
|
| 223 |
+
if response and response.text:
|
| 224 |
+
raw_text = response.text
|
| 225 |
+
print("=== [INFO] Mutation generated via Gemini 1.5 Flash Fallback ===", flush=True)
|
| 226 |
+
except Exception as fallback_err:
|
| 227 |
+
print(f"=== [CRITICAL] Gemini 1.5 Flash failed: {str(fallback_err)} ===", flush=True)
|
| 228 |
|
| 229 |
if not raw_text:
|
| 230 |
continue
|
|
|
|
| 233 |
is_valid, error_msg = validate_python_code(generated_code)
|
| 234 |
|
| 235 |
if is_valid:
|
| 236 |
+
# Обновление зависимостей
|
| 237 |
try:
|
| 238 |
update_requirements_if_needed(raw_text)
|
| 239 |
except Exception as req_err:
|
| 240 |
print(f"=== [WARN] Requirements update failed: {str(req_err)} ===", flush=True)
|
| 241 |
|
| 242 |
+
# Коммит кода плагина
|
| 243 |
+
if commit_to_github(CUSTOM_LOGIC_FILE, generated_code, "Plugin Autonomous Guarded Evolution"):
|
| 244 |
+
send_telegram_message(chat_id, "✅ **Эволюция завершена успешно!**\nМодуль `custom_logic.py` обновлен через каскадный контур ИИ и успешно прошел синтаксический контроль.")
|
| 245 |
return
|
| 246 |
else:
|
| 247 |
+
send_telegram_message(chat_id, "❌ Ошибка записи коммита в репозиторий GitHub.")
|
| 248 |
return
|
| 249 |
|
| 250 |
error_context = error_msg
|
| 251 |
print(f"=== [RETRY] Attempt {attempt+1} failed syntax check: {error_msg} ===", flush=True)
|
| 252 |
|
| 253 |
+
send_telegram_message(chat_id, f"❌ Фоновая мутация провалилась после {max_retries} попыток.\nПоследний лог ошибки: `{error_context or 'Все ИИ-контуры перегружены (503 / 429)'}`")
|
| 254 |
|
| 255 |
@app.get("/")
|
| 256 |
async def status():
|
|
|
|
| 282 |
chat_id = data["message"]["chat"]["id"]
|
| 283 |
user_text = data["message"]["text"].strip()
|
| 284 |
|
| 285 |
+
# Режим эволюции плагинов (Асинхронный запуск)
|
| 286 |
if user_text.lower().startswith("улучши себя:"):
|
| 287 |
if not GITHUB_TOKEN:
|
| 288 |
return {"method": "sendMessage", "chat_id": chat_id, "text": "❌ Не настроен GITHUB_TOKEN."}
|
| 289 |
|
|
|
|
| 290 |
background_tasks.add_task(background_evolution_worker, user_text[12:], chat_id)
|
| 291 |
return {
|
| 292 |
"method": "sendMessage",
|
|
|
|
| 318 |
print(f"=== [PLUGIN ERROR] {str(plugin_err)} ===", flush=True)
|
| 319 |
return {"method": "sendMessage", "chat_id": chat_id, "text": f"⚠️ В плагине дефект: {str(plugin_err)}"}
|
| 320 |
|
| 321 |
+
# Локальный резервный режим (если ИИ-контуры упали, а команда не распознана плагином)
|
| 322 |
if not ai_client and not GROQ_API_KEY:
|
| 323 |
fallback_msg = (
|
| 324 |
"🤖 Локальный режим Cyber-Agent.\n\n"
|