Download scripts/fix_openrouter_models.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 5.11 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/fix_openrouter_models.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/scripts/fix_openrouter_models.py
-
curl -L -o fix_openrouter_models.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/fix_openrouter_models.py
5.11 kB
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Фиксация OpenRouter-моделей за ролями сотрудников. | |
| Проверяет все доступные free-модели и выбирает 8 лучших. | |
| """ | |
| import sys | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| import json | |
| import asyncio | |
| import aiohttp | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from datetime import datetime | |
| from dotenv import load_dotenv | |
| # Загружаем переменные окружения для доступа к API ключу | |
| load_dotenv() | |
| # Добавляем корень проекта в путь | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| async def test_model(model_id: str, api_key: str) -> bool: | |
| """Проверить доступность модели через OpenRouter""" | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json", | |
| "HTTP-Referer": "https://huggingface.co/lhc-lab/AI-Colab", | |
| "X-Title": "AI-Colab" | |
| } | |
| data = { | |
| "model": model_id, | |
| "messages": [{"role": "user", "content": "ping"}], | |
| "max_tokens": 5 | |
| } | |
| try: | |
| async with aiohttp.ClientSession() as session: | |
| async with session.post( | |
| "https://openrouter.ai/api/v1/chat/completions", | |
| headers=headers, | |
| json=data, | |
| timeout=15 | |
| ) as resp: | |
| if resp.status == 200: | |
| res = await resp.json() | |
| return "choices" in res | |
| return False | |
| except: | |
| return False | |
| async def fix_assignments(): | |
| """Найти все рабочие модели и зафиксировать 8 для ролей""" | |
| config_path = Path("config/models_config.json") | |
| # Используем utf-8-sig для корректного чтения на Windows | |
| with open(config_path, 'r', encoding='utf-8-sig') as f: | |
| main_config = json.load(f) | |
| current_path = Path("config/current_models.json") | |
| api_key = os.getenv("OPENROUTER_API_KEY") | |
| if not api_key: | |
| print("❌ OPENROUTER_API_KEY не установлен в .env") | |
| return False | |
| # 1. Собираем список всех free-моделей из отчета верификации (там их десятки) | |
| report = main_config.get("verification_report", {}) | |
| details = report.get("details", {}) | |
| if details: | |
| free_models = [m for m in details.keys() if ":free" in m] | |
| else: | |
| # Fallback если отчет пуст | |
| available = main_config.get("available_openrouter_models", []) | |
| free_models = [m for m in available if ":free" in m] | |
| if not free_models: | |
| free_models = [ | |
| "meta-llama/llama-3.2-3b-instruct:free", | |
| "google/gemma-2-2b-it:free", | |
| "qwen/qwen2.5-3b-instruct:free" | |
| ] | |
| print(f"🔍 В базе найдено {len(free_models)} моделей OpenRouter (free)...") | |
| # 2. Блок проверки заремлен согласно воле Сёгуна | |
| # tasks = [test_model(m, api_key) for m in free_models] | |
| # results = await asyncio.gather(*tasks) | |
| # working_models = [free_models[i] for i, is_ok in enumerate(results) if is_ok] | |
| # Доверяем списку из базы | |
| working_models = free_models | |
| print(f"✅ Для фиксации доступно моделей: {len(working_models)}") | |
| if not working_models: | |
| # Если ничего не работает, берем самую стабильную | |
| working_models = ["meta-llama/llama-3.2-3b-instruct:free"] | |
| # 3. Назначаем 8 моделей сотрудникам (Истинные Имена) | |
| or_roles = ["flick", "flock", "click", "clack", "check", "chock", "link", "sync"] | |
| assignments = {} | |
| # Инициализируем менеджер для синхронного обновления | |
| from core.role_binding_manager import RoleBindingManager | |
| manager = RoleBindingManager() | |
| for i, role in enumerate(or_roles): | |
| # Распределяем рабочие модели по ролям | |
| model_id = working_models[i % len(working_models)] | |
| assignments[role] = model_id | |
| # Синхронизируем с RoleBindingManager | |
| manager.switch_binding(role, model_id, reason="OpenRouter fixation script") | |
| print(f"📍 {role} -> {model_id}") | |
| # 4. Сохраняем результат | |
| current_data = { | |
| "assigned_models": assignments, | |
| "working_free_models": working_models, | |
| "last_updated": datetime.now().isoformat(), | |
| "session_id": os.urandom(8).hex() | |
| } | |
| with open(current_path, 'w', encoding='utf-8') as f: | |
| json.dump(current_data, f, ensure_ascii=False, indent=2) | |
| print(f"✅ Фиксация завершена. Файл {current_path} обновлен.") | |
| return True | |
| if __name__ == "__main__": | |
| asyncio.run(fix_assignments()) | |