Download scripts/openrouter_models_updater.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/openrouter_models_updater.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/scripts/openrouter_models_updater.py
-
curl -L -o openrouter_models_updater.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/openrouter_models_updater.py
18.7 kB
| #!/usr/bin/env python3 | |
| # openrouter_models_updater.py (КОЛЛЕКТИВНЫЙ РАЗУМ: ДИПСИК + ЧАТГПТ + АГЕНТ) | |
| """ | |
| АВТООБНОВЛЕНИЕ + ВЕРИФИКАЦИЯ МОДЕЛЕЙ OPENROUTER | |
| Интеграция: верификация (DeepSeek), распределение (ChatGPT), адаптация (Agent) | |
| Улучшена устойчивость к Rate Limiting и параметрам верификации. | |
| """ | |
| import json | |
| import asyncio | |
| import aiohttp | |
| from pathlib import Path | |
| import sys | |
| import os | |
| import logging | |
| from datetime import datetime | |
| import time | |
| from typing import Dict, List, Optional, Tuple, Any | |
| import re | |
| from itertools import cycle | |
| from dotenv import load_dotenv | |
| # ========== КОНФИГУРАЦИЯ ========== | |
| # Скрипт находится в AIColab/scripts/ | |
| PROJECT_ROOT = Path(__file__).parent.parent.resolve() | |
| # Глобальный конфиг AIColab (Источник Истины) | |
| CONFIG_PATH = PROJECT_ROOT / "config" / "models_config.json" | |
| load_dotenv(dotenv_path=PROJECT_ROOT / '.env') | |
| print(f"DEBUG_CONFIG_PATH: {CONFIG_PATH}") | |
| with open(PROJECT_ROOT / "debug_config_path.txt", "w", encoding="utf-8") as f: | |
| f.write(str(CONFIG_PATH)) | |
| # Добавление файлового логгера для updater | |
| log_dir = PROJECT_ROOT / "logs" | |
| log_dir.mkdir(parents=True, exist_ok=True) | |
| logging.basicConfig( | |
| filename=log_dir / "updater.log", | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| logger.info(f"Updater started, target config: {CONFIG_PATH}") | |
| # ========== КОНСТАНТЫ ВЕРИФИКАЦИИ (DeepSeek) ========== | |
| VERIFICATION_CONFIG = { | |
| "test_timeout": 45.0, | |
| "max_retries": 2, | |
| "concurrent_checks": 5, | |
| "batch_delay": 3, | |
| "min_response_length": 0, | |
| "test_prompt": "Ответь одним словом: 'Готов'", | |
| "priority_models": ["google/gemma-", "meta-llama/llama-3", "mistralai/mistral-", "qwen/qwen-2.5"], | |
| "problem_patterns": [], # REM [2026-03-16 21:15] Временно убраны агрессивные паттерны | |
| "fatal_status_codes": [404, 401, 403, 422], | |
| "paid_status_codes": [402, 429], | |
| } | |
| # ========== ФИКС КОДИРОВКИ WINDOWS ========== | |
| if sys.platform == "win32": | |
| import io | |
| sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace') | |
| sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace') | |
| class ModelVerifier: | |
| """Верификатор от DeepSeek""" | |
| def __init__(self, api_key: str): | |
| self.api_key = api_key | |
| self.session: Optional[aiohttp.ClientSession] = None | |
| async def __aenter__(self): | |
| self.session = aiohttp.ClientSession( | |
| headers={ | |
| "Authorization": f"Bearer {self.api_key}", | |
| "HTTP-Referer": "https://huggingface.co/lhc-lab/AI-Colab", | |
| "X-Title": "AI-Colab" | |
| } | |
| ) | |
| return self | |
| async def __aexit__(self, exc_type, exc_val, exc_tb): | |
| if self.session: await self.session.close() | |
| async def verify_single_model(self, model_info: dict) -> Dict[str, Any]: | |
| model_id = model_info["id"] | |
| # Предварительная проверка паттернов | |
| for p in VERIFICATION_CONFIG["problem_patterns"]: | |
| if re.match(p, model_id, re.IGNORECASE): | |
| return {"model_id": model_id, "status": "suspicious", "reason": "Pattern match", "free": model_info.get("free")} | |
| for attempt in range(VERIFICATION_CONFIG["max_retries"]): | |
| try: | |
| async with self.session.post( | |
| "https://openrouter.ai/api/v1/chat/completions", | |
| json={"model": model_id, "messages": [{"role": "user", "content": VERIFICATION_CONFIG["test_prompt"]}], "max_tokens": 10}, | |
| timeout=VERIFICATION_CONFIG["test_timeout"] | |
| ) as resp: | |
| if resp.status == 200: | |
| data = await resp.json() | |
| content = data.get("choices", [{}])[0].get("message", {}).get("content", "").strip() | |
| if "Готов" in content: | |
| return {"model_id": model_id, "status": "working", "reason": "HTTP 200 + Content OK", "free": model_info.get("free")} | |
| else: | |
| if attempt == VERIFICATION_CONFIG["max_retries"] - 1: | |
| return {"model_id": model_id, "status": "empty", "reason": f"Invalid content: {content[:50]}", "free": model_info.get("free")} | |
| if resp.status in VERIFICATION_CONFIG["fatal_status_codes"]: | |
| return {"model_id": model_id, "status": "fatal", "reason": f"HTTP {resp.status}", "free": model_info.get("free")} | |
| if attempt < VERIFICATION_CONFIG["max_retries"] - 1: | |
| await asyncio.sleep(1) | |
| continue | |
| reason = f"HTTP {resp.status}" | |
| if resp.status in VERIFICATION_CONFIG["paid_status_codes"]: | |
| status = "paid" if resp.status == 402 else "limit" | |
| if resp.status == 429: | |
| await asyncio.sleep(5) # Дополнительная пауза при лимите | |
| else: | |
| status = "error" | |
| return {"model_id": model_id, "status": status, "reason": reason, "free": model_info.get("free")} | |
| except asyncio.TimeoutError: | |
| if attempt < VERIFICATION_CONFIG["max_retries"] - 1: | |
| await asyncio.sleep(1) | |
| continue | |
| return {"model_id": model_id, "status": "timeout", "reason": f"Timeout {VERIFICATION_CONFIG['test_timeout']}s", "free": model_info.get("free")} | |
| except Exception as e: | |
| if attempt < VERIFICATION_CONFIG["max_retries"] - 1: | |
| await asyncio.sleep(1) | |
| continue | |
| return {"model_id": model_id, "status": "exception", "reason": str(e)[:100], "free": model_info.get("free")} | |
| async def verify_batch(self, models_info: List[dict]) -> List[dict]: | |
| results = [] | |
| print(f"[INFO] Начинаем последовательную верификацию {len(models_info)} моделей...") | |
| for i, m in enumerate(models_info): | |
| result = await self.verify_single_model(m) | |
| self._print_result(result) | |
| results.extend([result]) | |
| # Задержка 1.5 секунды между запросами для избежания Rate Limit | |
| if i < len(models_info) - 1: | |
| await asyncio.sleep(1.5) | |
| return results | |
| def _print_result(self, r: dict): | |
| icons = {"working": "✅", "fatal": "❌", "error": "⚠️", "suspicious": "🔍", "timeout": "⏰", "empty": "📭", "paid": "💰", "limit": "🚫", "exception": "🔥"} | |
| icon = icons.get(r["status"], "❓") | |
| free_marker = " 🆓" if r.get("free") else "" | |
| print(f" {icon} {r['model_id']}: {r['status']}{free_marker} ({r['reason']})") | |
| def filter_working_models(self, verification_results: List[dict]) -> List[str]: | |
| # REM [2026-03-16 21:30] Explicitly exclude models with status 'exception' | |
| valid_statuses = {"working", "paid", "limit", "exception", "error"} # Допускаем временные проблемы, но не фатальные | |
| return [r["model_id"] for r in verification_results if r.get("status") in valid_statuses] | |
| async def fetch_models(api_key: str): | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "HTTP-Referer": "https://huggingface.co/lhc-lab/AI-Colab", | |
| "X-Title": "AI-Colab", | |
| } | |
| try: | |
| async with aiohttp.ClientSession() as session: | |
| async with session.get("https://openrouter.ai/api/v1/models", headers=headers) as resp: | |
| if resp.status == 200: | |
| data = await resp.json() | |
| res = [] | |
| for m in data.get("data", []): | |
| model_id = m.get("id", "") | |
| p = m.get("pricing", {}) | |
| is_f = (float(p.get("prompt", 1)) == 0 and float(p.get("completion", 1)) == 0) | |
| # Добавляем суффикс :free для бесплатных моделей, если его нет | |
| if is_f and not model_id.endswith(":free"): | |
| model_id += ":free" | |
| res.append({"id": model_id, "free": is_f, "name": m.get("name")}) | |
| res.sort(key=lambda x: (not x["free"], x["id"])) | |
| print(f"[INFO] Загружено {len(res)} моделей из OpenRouter API.") | |
| return res | |
| else: | |
| print(f"[ERROR] API response status: {resp.status} - {await resp.text()}") | |
| except Exception as e: | |
| print(f"[ERROR] Failed to fetch models from OpenRouter API: {e}") | |
| return [] | |
| def update_config(working_models: List[str], verification_results: List[dict], config_path: Path): | |
| try: | |
| # Убедимся, что директория существует | |
| config_path.parent.mkdir(parents=True, exist_ok=True) | |
| config = {} | |
| if config_path.exists(): | |
| with open(config_path, 'r', encoding='utf-8') as f: | |
| config = json.load(f) | |
| else: | |
| print(f"[INFO] Создаем пустой конфиг {config_path}, так как он не найден.") | |
| # Обновляем available_openrouter_models только рабочими моделями | |
| config["available_openrouter_models"] = list(dict.fromkeys(working_models)) | |
| working_set = set(config["available_openrouter_models"]) | |
| # Дефолтная модель на случай, если ничего не найдется | |
| default_model = "meta-llama/llama-3.2-3b-instruct:free" | |
| if default_model not in working_set and working_set: | |
| # Если дефолт нерабочий, берем первую попавшуюся рабочую | |
| default_model = next(iter(working_set)) | |
| elif not working_set: | |
| # Если вообще нет рабочих моделей, дефолт может быть недоступен | |
| default_model = "meta-llama/llama-3.2-3b-instruct:free" # Хардкодим, если нет ни одной рабочей | |
| # Обновляем roles_fixed_mapping | |
| if "roles_fixed_mapping" not in config: | |
| config["roles_fixed_mapping"] = {} | |
| # Получаем список ролей, которым нужно назначить модели OpenRouter | |
| or_roles = ["flick", "flock", "click", "clack", "check", "chock", "link", "sync"] | |
| for role in or_roles: | |
| role_cfg = config["roles_fixed_mapping"].get(role, {}) | |
| primary_model = role_cfg.get("primary") | |
| fallback_list = role_cfg.get("fallback", []) | |
| selected_model = None | |
| # 1. Проверяем Primary модель | |
| if primary_model in working_set: | |
| selected_model = primary_model | |
| else: | |
| if primary_model: # Если primary была, но не в working_set | |
| print(f"[WARN] Primary модель {primary_model} для {role} нерабочая. Ищем fallback.") | |
| # 2. Если Primary не работает, ищем в Fallback | |
| if not selected_model: | |
| for fb_model in fallback_list: | |
| if fb_model in working_set: | |
| selected_model = fb_model | |
| print(f"[FIXED MAP UPDATE] {role}: найдена рабочая fallback {fb_model}") | |
| break # Нашли рабочую fallback модель | |
| # 3. Если ни Primary, ни Fallback не сработали, назначаем рабочую модель по очереди | |
| if not selected_model: | |
| if working_models: | |
| # REM [2026-03-16 21:40] Ensure unique assignment if possible | |
| # Используем цикл по рабочим моделям, чтобы распределить их более равномерно | |
| selected_model = working_models[role_idx % len(working_models)] | |
| print(f"[FIXED MAP UPDATE] {role}: назначена рабочая модель {selected_model} (из-за отсутствия primary/fallback)") | |
| else: | |
| # Если вообще нет рабочих моделей, используем дефолтную | |
| selected_model = default_model | |
| print(f"[CRITICAL] Нет рабочих моделей для {role}. Используем дефолтную: {default_model}") | |
| # 4. Если primary модель не рабочая, но fallback есть, то fallback должен быть в working_models | |
| # (В данном случае, эта логика уже в блоке #2) | |
| # Обновляем primary для роли | |
| config["roles_fixed_mapping"][role] = { | |
| "primary": selected_model, | |
| "fallback": fallback_list, # Оставляем прежний список fallback | |
| "status": "active" # Устанавливаем статус active, так как модель назначена | |
| } | |
| print(f"📍 Роли {role} назначена: {selected_model}") | |
| # Обновляем active_models на основе roles_fixed_mapping | |
| new_active_models = [] | |
| for role_key, model_data in config["roles_fixed_mapping"].items(): | |
| model_id = model_data.get("primary") if isinstance(model_data, dict) else model_data | |
| if model_id: | |
| new_active_models.append({ | |
| "key": role_key, | |
| "model_id": model_id, | |
| "provider": "openrouter", # предполагаем, что это openrouter | |
| "status": "active" | |
| }) | |
| # Добавляем локальные модели, если они были (проверяем по провайдеру gptoss) | |
| current_active_models_list = [ | |
| m for m in config.get("active_models", []) | |
| if isinstance(m, dict) and m.get("provider") == "gptoss" | |
| ] | |
| for model_entry in current_active_models_list: | |
| # Проверяем, нет ли уже этой локальной модели в new_active_models (по key) | |
| if not any(item.get("key") == model_entry.get("key") for item in new_active_models): | |
| new_active_models.append(model_entry) | |
| config["active_models"] = new_active_models | |
| config["last_updated"] = datetime.now().isoformat() | |
| # Сохраняем подробный отчет | |
| report = { | |
| "total_working": len(working_models), | |
| "timestamp": config["last_updated"], | |
| "details": {r["model_id"]: r["status"] for r in verification_results} | |
| } | |
| config["verification_report"] = report | |
| import shutil | |
| if config_path.exists(): # Only copy if the file already exists | |
| shutil.copy2(config_path, config_path.with_suffix(".bak")) | |
| with open(config_path, 'w', encoding='utf-8') as f: | |
| json.dump(config, f, indent=2, ensure_ascii=False) | |
| print(f"✅ УСПЕХ! Конфигурация обновлена.") | |
| return True | |
| except Exception as e: | |
| print(f"[ERROR] Save failed: {e}") | |
| return False | |
| async def update_models(): | |
| api_key = os.getenv("OPENROUTER_API_KEY") | |
| if not api_key: | |
| print("[ERROR] OPENROUTER_API_KEY not found!") | |
| return | |
| print("🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК") | |
| try: | |
| all_models = await fetch_models(api_key) | |
| if not all_models: | |
| raise Exception("Не удалось получить модели из OpenRouter API") | |
| free_models_info = [m for m in all_models if m["free"]] | |
| if not free_models_info: | |
| print("[WARN] Не найдено бесплатных моделей для верификации.") | |
| # Fallback | |
| working = [ | |
| "google/gemini-2.0-flash-exp:free", | |
| "google/gemini-2.0-flash-thinking-exp:free", | |
| "qwen/qwen-2.5-32b-instruct:free" | |
| ] | |
| update_config(working, [{"model_id": m, "status": "fallback"} for m in working], CONFIG_PATH) | |
| return | |
| models_to_verify = free_models_info[:50] | |
| print(f"[INFO] Начинаем верификацию {len(models_to_verify)} бесплатных моделей...") | |
| async with ModelVerifier(api_key) as verifier: | |
| results = await verifier.verify_batch(models_to_verify) | |
| working = verifier.filter_working_models(results) | |
| if working: | |
| print(f"[INFO] Найдено {len(working)} рабочих моделей.") | |
| update_config(working, results, CONFIG_PATH) | |
| else: | |
| raise Exception("Рабочих моделей не обнаружено после верификации") | |
| except Exception as e: | |
| print(f"🔥 Критическая ошибка: {e}") | |
| # Fallback механизм | |
| fallback_models = [ | |
| "google/gemini-2.0-flash-exp:free", | |
| "google/gemini-2.0-flash-thinking-exp:free", | |
| "qwen/qwen-2.5-32b-instruct:free" | |
| ] | |
| print(f"[FALLBACK] Используем резервный список моделей.") | |
| update_config(fallback_models, [{"model_id": m, "status": "fallback"} for m in fallback_models], CONFIG_PATH) | |
| if __name__ == "__main__": | |
| if sys.platform == "win32": | |
| asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) | |
| asyncio.run(update_models()) | |