File size: 5,113 Bytes
49f0b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/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())