A.Tuin commited on
Commit ·
8d155db
1
Parent(s): 49f0b2f
правка
Browse filesFiles changed (24)
- AIColab_cuda_2.bat+6-10
- app.py+63-48
- app.py.bakAdded+521
- config/models_config.backup.json+1-1
- config/models_config.bak+22-5
- config/models_config.json+18-35
- config/models_config.json.backup_1770214199+1-1
- config/models_config.json.backup_20260115_002053+1-1
- config/roles_state.jsonDeleted-120
- core/model_management.backup.py+4-4
- core/model_management.py+95-47
- core/model_management_backup.py+2-2
- core/role_binding_manager.py+96-93
- gemini_mcp_server.py+30-5
- integrations/openrouter_adapter.py+17-16
- list.txtAdded
- mcp_server_crash_log.txtAdded+1
- mcp_server_crash_log_25.03.2026Added
- projects/Bestihi.ru/config/roles_state.json+6
- server_crash_log.txt+486-45
- server_crash_log_25.03.2026Added
- tests/test_gpu_config.jsonAdded+1
- tests/test_gpu_load.pyAdded+36
- tests/test_models.pyAdded+112
12345678910111213@ECHO OFFsetlocalcd /d %~dp0echo [DIAGNOSTIC] Starting AIColab Server with CUDA...echo [DIAGNOSTIC] All output redirected to server_crash_log.txt:: ��⨢��� ���㦥��� (� �ॡ����):: call venv_cuda\Scripts\activate:: ����� � ��७��ࠢ������ stdout � stderr � ॠ�쭮� �६���python app.py > server_crash_log.txt 2>&1echo [DIAGNOSTIC] Server stopped or crashed. Check server_crash_log.txt123456789@ECHO OFFTITLE AIColab System (CUDA Enabled)cd D:\Gemini\AIColabREM Запуск MCP Сервера для Консоли Gemini с использованием venv_cudaSTART "Gemini MCP Server CUDA" /MIN .\venv_cuda\Scripts\python.exe gemini_mcp_server.py >> mcp_server_crash_log.txt 2>&1REM Запуск основного веб-интерфейса с использованием venv_cuda.\venv_cuda\Scripts\python.exe -m uvicorn app:app --host 127.0.0.1 --port 5000 >> server_crash_log.txt 2>&1
15 unmodified lines16171819202122232454 unmodified lines798081828384859 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221233 unmodified lines1271281291301311321333 unmodified lines13713813914014114214332 unmodified lines1761771781791801811828 unmodified lines19119219319419519619719852 unmodified lines2512522532542552562572582592606 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330475 unmodified lines38038138238338438538638715 unmodified linesfrom uuid import uuid4from scripts.openrouter_models_updater import update_modelsload_dotenv()app = Quart(__name__, static_folder='static', template_folder='templates')app.config['SECRET_KEY'] = os.urandom(24)54 unmodified lines# except Exception as e:# app.logger.error(f"Ошибка при попытке отключить фиксацию моделей: {e}")app.model_manager = Noneapp.project_context = Noneapp.orchestrator = Noneapp.gcb = None9 unmodified linesasync def get_orchestrator():if not hasattr(app, 'orchestrator') or app.orchestrator is None:from core.llm_integrations.chief_orchestrator import ChiefOrchestratorfrom core.model_management import ModelManager# Убеждаемся, что менеджер моделей готовif not hasattr(app, 'model_manager') or app.model_manager is None:from core.model_management import ModelManagerfrom core.role_binding_manager import RoleBindingManagerapp.model_manager = ModelManager()await app.model_manager._ensure_initialized()app.role_binding_manager = RoleBindingManager()app.logger.info("RoleBindingManager инициализирован")app.orchestrator = ChiefOrchestrator(model_manager=app.model_manager)return app.orchestratorasync def get_role_manager():if not hasattr(app, 'role_binding_manager') or app.role_binding_manager is None:from core.role_binding_manager import RoleBindingManagerapp.role_binding_manager = RoleBindingManager()return app.role_binding_manager@app.route('/api/admin/switch_binding', methods=['POST'])async def admin_switch_binding():"""Админ-эндпоинт для переключения привязки модели к роли."""role_manager = await get_role_manager()data = await request.get_json()role = data.get('role')3 unmodified linesif not role or not model:return jsonify({'success': False, 'error': 'Missing role or model'}), 400success = role_manager.switch_binding(role, model, reason)return jsonify({'success': success})@app.route('/api/ceo/consult', methods=['POST'])3 unmodified linesmessage = data.get('message', '')session_id = data.get('session_id', 'default')role_manager = await get_role_manager()result = await role_manager.run_department("D", {"message": message, "session_id": session_id}, caller="ceo")if result:32 unmodified linesasync def call_secretary(user_message: str, reason_code: str, source_role: str) -> str:"""Формирует промпт и вызывает Secretary (Gemini/Gemma) для генерации объяснения."""role_manager = await get_role_manager()system_prompt = await role_manager.get_prompt('secretary')# Формируем контекст для Секретаря8 unmodified lines)try:# Прямой вызов через gateway.call_geminiresponse = await gateway.call_gemini(user_prompt)# Очистка от возможного JSON в ответе (на случай, если модель проигнорировала инструкцию)stripped = response.strip()52 unmodified linesif not model_key:return jsonify({"error": "Missing model parameter"}), 400if not hasattr(app, 'model_manager') or app.model_manager is None:from core.model_management import ModelManagerapp.model_manager = ModelManager()await app.model_manager._ensure_initialized()source_role = model_key6 unmodified lines# 1. Вызов целевой ролиtry:async with app.model_manager._generate_lock:if model_key == 'ceo':role_manager = await get_role_manager()ceo_model = await app.model_manager.get_model('ceo')system_prompt_ceo = await role_manager.get_prompt('ceo')raw_response = await ceo_model.generate(user_message, system_prompt=system_prompt_ceo)elif model_key == 'chief':orchestrator = await get_orchestrator()raw_response = await orchestrator.orchestrate(user_message, session_id=session_id)elif model_key == 'gemini_direct' or model_key == 'gemini' or model_key == 'secretary':# Прямой запрос к Секретарю (Gemini CLI) - возвращаем протокол для обработки внешним CLIreturn jsonify({"redirect": "secretary", "reason_code": "gemini_direct_call", "user_message": user_message}), 200else:# Сотрудники (Staff models) - ОБРАБОТКА ИСТОРИИ И ЛОГИРОВАНИЕtry:role_manager = await get_role_manager()system_prompt = await role_manager.get_prompt(model_key)# Получаем историю диалога (последние 10 сообщений)from core.log_reader import get_recent_historyhistory_msgs = get_recent_history(model_key, limit=10)# Формируем полный список сообщений для APIfull_messages = []if system_prompt:full_messages.append({"role": "system", "content": system_prompt})full_messages.extend(history_msgs)full_messages.append({"role": "user", "content": user_message})# Вызываем модель с полной историейmodel_inst = await app.model_manager.get_model(role_manager.get_model_for_role(model_key, session_id))staff_response = await model_inst.generate(messages=full_messages)# Записываем диалог в логproject_path = get_current_project()75 unmodified linesasync def get_model_mapping():"""Получить маппинг моделей для UI на основе RoleBindingManager"""try:role_manager = await get_role_manager()state = role_manager.get_state()roles = state.get('roles', {})mapping = {}15 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535454 unmodified lines1091101111121131149 unmodified lines1241251261271281291301311321331341351361371381391401411421433 unmodified lines1471481491501511521533 unmodified lines15715815916016116216332 unmodified lines1961971981992002012028 unmodified lines21121221321421521621721821952 unmodified lines2722732742752762772782796 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831975 unmodified lines39539639739839940040140215 unmodified linesfrom uuid import uuid4from scripts.openrouter_models_updater import update_modelsfrom core.globals import initialize_global # ИМПОРТ initialize_globalfrom core.model_management import ModelManager # ИМПОРТ ModelManagerfrom core.role_binding_manager import RoleBindingManager # ИМПОРТ RoleBindingManagerload_dotenv()# Глобальные геттеры для синглтоновdef get_model_manager() -> ModelManager:return initialize_global("model_manager", lambda: ModelManager())def get_role_manager() -> RoleBindingManager:# RoleBindingManager зависит от ModelManagerreturn initialize_global("role_binding_manager", lambda: RoleBindingManager(model_manager=get_model_manager()))async def call_gemini(prompt: str) -> str:"""Вызов внешнего мозга через WebSocket (Gemini CLI)."""uri = "ws://127.0.0.1:8765"try:import websocketsasync with websockets.connect(uri,open_timeout=10,close_timeout=10) as websocket:await websocket.send(json.dumps({"message": prompt}))response = await websocket.recv()data = json.loads(response)return data.get("response", str(data))except Exception as e:app.logger.error(f"Gemini call failed: {e}")return f"Ошибка связи с Секретарём (Gemini CLI): {e}"app = Quart(__name__, static_folder='static', template_folder='templates')app.config['SECRET_KEY'] = os.urandom(24)54 unmodified lines# except Exception as e:# app.logger.error(f"Ошибка при попытке отключить фиксацию моделей: {e}")app.project_context = Noneapp.orchestrator = Noneapp.gcb = None9 unmodified linesasync def get_orchestrator():if not hasattr(app, 'orchestrator') or app.orchestrator is None:from core.llm_integrations.chief_orchestrator import ChiefOrchestrator# Используем глобальный геттер для ModelManagermodel_manager_instance = get_model_manager()await model_manager_instance._ensure_initialized() # Гарантируем инициализациюapp.orchestrator = ChiefOrchestrator(model_manager=model_manager_instance)return app.orchestrator@app.route('/api/admin/switch_binding', methods=['POST'])async def admin_switch_binding():"""Админ-эндпоинт для переключения привязки модели к роли."""role_manager = get_role_manager()data = await request.get_json()role = data.get('role')3 unmodified linesif not role or not model:return jsonify({'success': False, 'error': 'Missing role or model'}), 400success = await role_manager.switch_binding(role, model, reason)return jsonify({'success': success})@app.route('/api/ceo/consult', methods=['POST'])3 unmodified linesmessage = data.get('message', '')session_id = data.get('session_id', 'default')role_manager = get_role_manager()result = await role_manager.run_department("D", {"message": message, "session_id": session_id}, caller="ceo")if result:32 unmodified linesasync def call_secretary(user_message: str, reason_code: str, source_role: str) -> str:"""Формирует промпт и вызывает Secretary (Gemini/Gemma) для генерации объяснения."""role_manager = get_role_manager()system_prompt = await role_manager.get_prompt('secretary')# Формируем контекст для Секретаря8 unmodified lines)try:# Прямой вызов через локальный WebSocket call_gemini (Gemini CLI)# Здесь используется функция call_gemini, которая связывается с внешним мозгом (Gemini CLI)response = await call_gemini(user_prompt)# Очистка от возможного JSON в ответе (на случай, если модель проигнорировала инструкцию)stripped = response.strip()52 unmodified linesif not model_key:return jsonify({"error": "Missing model parameter"}), 400model_manager = get_model_manager()await model_manager._ensure_initialized()source_role = model_key6 unmodified lines# 1. Вызов целевой ролиtry:async with model_manager._generate_lock:if model_key == 'ceo':role_manager = get_role_manager()app.logger.debug(f"DEBUG: CEO - model_key: {model_key}, type: {type(model_key)}")ceo_model = await model_manager.get_model('ceo') # <-- здесь ключ 'ceo'system_prompt_ceo = await role_manager.get_prompt('ceo')raw_response = await ceo_model.generate(user_message, system_prompt=system_prompt_ceo)elif model_key == 'chief':role_manager = get_role_manager()app.logger.debug(f"DEBUG: Chief - model_key: {model_key}, type: {type(model_key)}")chief_model = await model_manager.get_model('chief') # <-- здесь ключ 'chief'system_prompt_chief = await role_manager.get_prompt('chief')raw_response = await chief_model.generate(user_message, system_prompt=system_prompt_chief)elif model_key == 'gemini_direct' or model_key == 'gemini' or model_key == 'secretary':# Прямой запрос к Секретарю (Gemini CLI) - возвращаем протокол для обработки внешним CLIreturn jsonify({"redirect": "secretary", "reason_code": "gemini_direct_call", "user_message": user_message}), 200else:# Сотрудники (Staff models) - ОБРАБОТКА ИСТОРИИ И ЛОГИРОВАНИЕtry:role_manager = get_role_manager()app.logger.debug(f"DEBUG: Staff - model_key: {model_key}, type: {type(model_key)}")model_id_from_binding = await role_manager.get_model_for_role(model_key, task_id=session_id)app.logger.debug(f"DEBUG: Staff - model_id_from_binding: {model_id_from_binding}, type: {type(model_id_from_binding)}")model_manager = get_model_manager()model_inst = await model_manager.get_model(model_id_from_binding)staff_response = await model_inst.generate(prompt=user_message)# Записываем диалог в логproject_path = get_current_project()75 unmodified linesasync def get_model_mapping():"""Получить маппинг моделей для UI на основе RoleBindingManager"""try:role_manager = get_role_manager()state = await role_manager.get_state()roles = state.get('roles', {})mapping = {}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521from quart import Quart, request, jsonify, websocket, render_template, send_from_directoryfrom typing import Optional, Dictimport asyncioimport loggingimport sysimport osimport jsonfrom datetime import datetimefrom dotenv import load_dotenvfrom core.app_state import get_current_projectfrom core.lab_composition import get_lab_compositionfrom core.prompt_registry import PromptRegistryfrom core.project_context import ProjectContextfrom core.log_reader import get_recent_historyfrom pathlib import Pathfrom uuid import uuid4from scripts.openrouter_models_updater import update_models
from core.globals import initialize_global # ИМПОРТ initialize_globalfrom core.model_management import ModelManager # ИМПОРТ ModelManagerfrom core.role_binding_manager import RoleBindingManager # ИМПОРТ RoleBindingManager
load_dotenv()
# Глобальные геттеры для синглтоновdef get_model_manager() -> ModelManager: return initialize_global("model_manager", lambda: ModelManager())
def get_role_manager() -> RoleBindingManager: # RoleBindingManager зависит от ModelManager return initialize_global("role_binding_manager", lambda: RoleBindingManager(model_manager=get_model_manager()))
async def call_gemini(prompt: str) -> str: """Вызов внешнего мозга через WebSocket (Gemini CLI).""" uri = "ws://127.0.0.1:8765" try: import websockets async with websockets.connect( uri, open_timeout=10, close_timeout=10 ) as websocket: await websocket.send(json.dumps({"message": prompt})) response = await websocket.recv() data = json.loads(response) return data.get("response", str(data)) except Exception as e: app.logger.error(f"Gemini call failed: {e}") return f"Ошибка связи с Секретарём (Gemini CLI): {e}"
app = Quart(__name__, static_folder='static', template_folder='templates')app.config['SECRET_KEY'] = os.urandom(24)
@app.route('/')async def index(): """Главная страница интерфейса""" return await render_template('index.html')
@app.route('/<path:path>')async def send_static(path): """Раздача статических файлов (js, png) из корня static""" return await send_from_directory('static', path)
async def ensure_project_dirs(): """Создать директории для текущего проекта (только если проект выбран)""" from core.project_context import ProjectContext from core.app_state import get_current_project project_path_str = get_current_project() if not project_path_str: app.logger.info("Проект не выбран в SharedState, пропуск создания директорий.") return
ctx = ProjectContext.get_instance() await ctx.ensure_initialized() project_path = ctx.get_current_project_path() # ТОЛЬКО необходимые директории required_dirs = [ "logs", "logs/sessions", "info/ceo", "info/chief", "info/doctor", ] for dir_name in required_dirs: dir_path = project_path / dir_name dir_path.mkdir(parents=True, exist_ok=True) app.logger.info(f"Директории проекта созданы: {project_path}")
# Ленивая инициализация компонентов@app.before_servingasync def startup(): await ensure_project_dirs() # 1. Запуск апдейтера (поиск свободных актеров) asyncio.create_task(update_models()) app.logger.info("🚀 Updater моделей (интегрированный) запущен в фоне") # REM [2026-03-19 13:45] Инициализация фиксации OpenRouter-моделей (закомментировано из-за отсутствия модуля) # try: # from scripts.fix_openrouter_models import fix_assignments # asyncio.create_task(fix_assignments()) # Удалено по указанию Сенсея # app.logger.info("Автоматическая фиксация OpenRouter-моделей отключена.") # except Exception as e: # app.logger.error(f"Ошибка при попытке отключить фиксацию моделей: {e}")
app.project_context = None app.orchestrator = None app.gcb = None app.prompt_registry = PromptRegistry() app.logger.info("Сервер готов к ленивой инициализации")
async def get_gcb(): if not hasattr(app, 'gcb') or app.gcb is None: from core.llm_integrations.gcb_engine import GCBEngine app.gcb = GCBEngine() return app.gcb
async def get_orchestrator(): if not hasattr(app, 'orchestrator') or app.orchestrator is None: from core.llm_integrations.chief_orchestrator import ChiefOrchestrator # Используем глобальный геттер для ModelManager model_manager_instance = get_model_manager() await model_manager_instance._ensure_initialized() # Гарантируем инициализацию app.orchestrator = ChiefOrchestrator(model_manager=model_manager_instance) return app.orchestrator
@app.route('/api/admin/switch_binding', methods=['POST'])async def admin_switch_binding(): """Админ-эндпоинт для переключения привязки модели к роли.""" role_manager = get_role_manager()
data = await request.get_json() role = data.get('role') model = data.get('model') reason = data.get('reason', 'admin_request') if not role or not model: return jsonify({'success': False, 'error': 'Missing role or model'}), 400 success = role_manager.switch_binding(role, model, reason) return jsonify({'success': success})
@app.route('/api/ceo/consult', methods=['POST'])async def ceo_consult(): """Эндпоинт для вызова внешнего консилиума (Отдел D).""" data = await request.get_json() message = data.get('message', '') session_id = data.get('session_id', 'default') role_manager = get_role_manager() result = await role_manager.run_department("D", {"message": message, "session_id": session_id}, caller="ceo") if result: # Преобразуем структурированный ответ в текст для UI proposal = result.get('proposal', 'Нет предложения') weak_points = "\n- ".join(result.get('weak_points', [])) alternatives = "\n- ".join(result.get('alternatives', [])) reply = f"🧠 Внешний Консилиум (Отдел D):\n\n**Предложение:**\n{proposal}\n\n**Слабые стороны:**\n- {weak_points}\n\n**Альтернативы:**\n- {alternatives}" return jsonify({ 'reply': reply, 'model': 'ceo_council', 'session_id': session_id }) else: return jsonify({'error': 'Не удалось получить ответ от консилиума'}), 500
from core.mode_handler import apply_mode_logicfrom core import gateway # Добавлен импорт gatewayimport re
# Логирование redirectdef log_redirect(entry: dict): """Логирует события перенаправления в logs/redirects.jsonl""" try: from core.project_context import ProjectContext ctx = ProjectContext.get_instance() project_path = ctx.get_current_project_path() redirects_log = project_path / "logs" / "redirects.jsonl" redirects_log.parent.mkdir(parents=True, exist_ok=True) with open(redirects_log, "a", encoding="utf-8") as f: f.write(json.dumps(entry, ensure_ascii=False) + "\n") except Exception as e: app.logger.error(f"Failed to log redirect: {e}")
async def call_secretary(user_message: str, reason_code: str, source_role: str) -> str: """Формирует промпт и вызывает Secretary (Gemini/Gemma) для генерации объяснения.""" role_manager = get_role_manager() system_prompt = await role_manager.get_prompt('secretary') # Формируем контекст для Секретаря user_prompt = ( f"ИНСТРУКЦИЯ ДЛЯ СЕКРЕТАРЯ:\n" f"1. Ты получил отказ от роли: {source_role}\n" f"2. Код причины отказа: {reason_code}\n" f"3. Сообщение пользователя: {user_message}\n\n" f"ЗАДАНИЕ: Объясни пользователю причину отказа простыми словами на русском языке. " f"СТРОГО ЗАПРЕЩЕНО ИСПОЛЬЗОВАТЬ JSON ИЛИ ЛЮБЫЕ ТЕХНИЧЕСКИЕ СИМВОЛЫ. " f"ОТВЕЧАЙ ТОЛЬКО ТЕКСТОМ ДЛЯ ЧЕЛОВЕКА." ) try: # Прямой вызов через локальный WebSocket call_gemini (Gemini CLI) # Здесь используется функция call_gemini, которая связывается с внешним мозгом (Gemini CLI) response = await call_gemini(user_prompt) # Очистка от возможного JSON в ответе (на случай, если модель проигнорировала инструкцию) stripped = response.strip() if stripped.startswith('{') and stripped.endswith('}'): try: data = json.loads(stripped) # Ищем человекочитаемые поля for key in ['content', 'response', 'message', 'text', 'reply']: if key in data: return str(data[key]) # Если полей нет, но это JSON - возможно это и есть ошибка if 'redirect' in data or 'reason_code' in data: # Если модель просто вернула протокольный JSON - это провал Секретаря. # Даем дефолтное объяснение на основе reason_code. return f"Роль {source_role} отклонила запрос (код: {reason_code}). Пожалуйста, уточните ваш вопрос." except: pass return response except Exception as e: app.logger.error(f"Secretary call failed: {e}") return "Извините, Секретарь сейчас недоступен."
@app.route('/api/secretary_internal', methods=['POST'])async def secretary_internal_endpoint(): """ Внутренний эндпоинт для вызова Секретаря. Принимает JSON: {"user_message": "...", "reason_code": "...", "source_role": "..."} """ data = await request.get_json() user_message = data.get('user_message', '') reason_code = data.get('reason_code', 'unspecified') source_role = data.get('source_role', 'unknown') response = await call_secretary(user_message, reason_code, source_role) return jsonify({"response": response})
@app.route('/api/chat', methods=['POST'])async def chat(): """DEPRECATED: Используйте /api/secretary для всех запросов.""" resp = jsonify({ 'error': 'This endpoint is deprecated. Use /api/secretary instead.', 'new_endpoint': '/api/secretary' }) resp.headers['Location'] = '/api/secretary' return resp, 410
@app.route('/api/secretary', methods=['POST'])async def secretary(): """Gateway - пассивный транспорт. Направляет запрос к роли и обрабатывает редиректы.""" try: data = await request.get_json() model_key = data.get('model') user_message = data.get('message', data.get('user_message', '')) session_id = data.get('session_id', 'default') if not model_key: return jsonify({"error": "Missing model parameter"}), 400
model_manager = get_model_manager() await model_manager._ensure_initialized()
source_role = model_key # Маппинг имен ролей для UI ROLE_NAMES = { "chief": "Шеф", "ceo": "СЕО", "secretary": "Секретарь", "flick": "Флик", "flock": "Флок", "click": "Клик", "clack": "Клак", "check": "Чек", "chock": "Чок", "link": "Линк", "sync": "Синх" }
# 1. Вызов целевой роли try: async with model_manager._generate_lock: if model_key == 'ceo': role_manager = get_role_manager() app.logger.debug(f"DEBUG: CEO - model_key: {model_key}, type: {type(model_key)}") ceo_model = await model_manager.get_model('ceo') # <-- здесь ключ 'ceo' system_prompt_ceo = await role_manager.get_prompt('ceo') raw_response = await ceo_model.generate(user_message, system_prompt=system_prompt_ceo) elif model_key == 'chief': role_manager = get_role_manager() app.logger.debug(f"DEBUG: Chief - model_key: {model_key}, type: {type(model_key)}") chief_model = await model_manager.get_model('chief') # <-- здесь ключ 'chief' system_prompt_chief = await role_manager.get_prompt('chief') raw_response = await chief_model.generate(user_message, system_prompt=system_prompt_chief) elif model_key == 'gemini_direct' or model_key == 'gemini' or model_key == 'secretary': # Прямой запрос к Секретарю (Gemini CLI) - возвращаем протокол для обработки внешним CLI return jsonify({"redirect": "secretary", "reason_code": "gemini_direct_call", "user_message": user_message}), 200 else: # Сотрудники (Staff models) - ОБРАБОТКА ИСТОРИИ И ЛОГИРОВАНИЕ try: role_manager = get_role_manager() app.logger.debug(f"DEBUG: Staff - model_key: {model_key}, type: {type(model_key)}") model_id_from_binding = role_manager.get_model_for_role(model_key, task_id=session_id) app.logger.debug(f"DEBUG: Staff - model_id_from_binding: {model_id_from_binding}, type: {type(model_id_from_binding)}") model_manager = get_model_manager() model_inst = await model_manager.get_model(model_id_from_binding) staff_response = await model_inst.generate(prompt=user_message) # Записываем диалог в лог project_path = get_current_project() if project_path: log_dir = Path(project_path) / "logs" / "subjects" log_dir.mkdir(parents=True, exist_ok=True) with open(log_dir / f"{model_key}.log", "a", encoding="utf-8") as f: f.write(f"User: {user_message}\nAI: {staff_response}\n\n") # Прямой возврат для Staff-моделей display_name = ROLE_NAMES.get(model_key, model_key.capitalize()) # СТАРАЯ ПРАВКА (БЕЗ MODEL_ID): # return jsonify({"response": str(staff_response), "modelInfo": {"key": model_key, "roleName": display_name}}) # НОВАЯ ПРАВКА (ПОДСТАВЛЯЕМ НАЗВАНИЕ МОДЕЛИ В СКОБКИ): return jsonify({ "response": str(staff_response), "modelInfo": { "key": model_key, "roleName": display_name, "modelId": getattr(model_inst, 'short_name', getattr(model_inst, 'model_id', 'unknown')) } }) except Exception as e: app.logger.error(f"Error calling Staff model {model_key}: {e}") return jsonify({"response": f"Ошибка вызова модели {model_key}: {e}", "modelInfo": {"key": model_key, "roleName": model_key}}), 500 except asyncio.TimeoutError: app.logger.error(f"Timeout calling {model_key}") secretary_reply = await call_secretary(user_message, "timeout", source_role) return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}}) except Exception as e: app.logger.error(f"Error calling {model_key}: {e}") secretary_reply = await call_secretary(user_message, "technical_error", source_role) return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}})
if not raw_response: secretary_reply = await call_secretary(user_message, "unspecified", source_role) return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}})
# 2. Перехват и интерпретация ответа (HIL Layer) intercepted = gateway.intercept_response(str(raw_response), source_role) if intercepted['type'] == 'redirect': reason_code = intercepted.get('reason_code', 'unspecified') # Логирование редиректа log_redirect({ "timestamp": datetime.now().isoformat(), "role": source_role, "reason_code": reason_code, "user_message": user_message }) secretary_reply = await call_secretary(user_message, reason_code, source_role) return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}}) elif intercepted['type'] == 'gemini': # Ответ требует пояснения Секретаря (например, malformed JSON или статус) reason_code = intercepted.get('reason_code', 'unspecified') secretary_reply = await call_secretary(user_message, reason_code, source_role) return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}}) elif intercepted['type'] == 'directive': # Архитектурная директива (выполняется, но в UI не идет как текст) # В текущей реализации просто логируем и возвращаем "ОК" или скрываем app.logger.info(f"Directive received from {source_role}: {intercepted['directive']}") return jsonify({"response": "Директива принята.", "modelInfo": {"key": source_role, "roleName": ROLE_NAMES.get(source_role, source_role)}})
# Обычный текстовый ответ display_name = ROLE_NAMES.get(source_role, source_role.capitalize()) return jsonify({"response": intercepted['content'], "modelInfo": {"key": source_role, "roleName": display_name}}) except Exception as e: app.logger.error(f"Critical error in Gateway (/api/secretary): {e}") return jsonify({"response": "Technical error occurred.", "modelInfo": {"key": "unknown", "roleName": "Система"}}), 500
@app.route('/api/model_mapping', methods=['GET'])async def get_model_mapping(): """Получить маппинг моделей для UI на основе RoleBindingManager""" try: role_manager = get_role_manager() state = role_manager.get_state() roles = state.get('roles', {}) mapping = {} for key, info in roles.items(): mapping[key] = { "key": key, "model_id": info.get('model_id', 'unknown'), "provider": info.get('provider', 'unknown') } return jsonify({"model_mapping": mapping}) except Exception as e: app.logger.error(f"Ошибка в get_model_mapping: {e}") return jsonify({"model_mapping": {}})
@app.route('/api/files/work', methods=['GET'])async def list_work_files(): try: from pathlib import Path files = [f.name for f in Path('data').glob('*') if f.is_file()] return jsonify(files) except Exception: return jsonify([])
@app.route('/api/files/results', methods=['GET'])async def list_result_files(): try: from pathlib import Path files = [f.name for f in Path('logs').glob('*') if f.is_file()] return jsonify(files) except Exception: return jsonify([])
# GCB Routes@app.route('/api/gcb/queue', methods=['GET'])async def gcb_get_queue(): gcb = await get_gcb() queue = await gcb.get_queue() return jsonify(queue)
@app.route('/api/gcb/execute/<cmd_id>', methods=['POST'])async def gcb_execute_command(cmd_id: str): gcb = await get_gcb() result = await gcb.execute_local(cmd_id) return jsonify(result)
@app.route('/api/briefing', methods=['POST'])async def run_briefing(): data = await request.get_json() topic = data.get('topic', 'Текущий статус проекта') session_id = data.get('session_id') try: orchestrator = await get_orchestrator() summary = await orchestrator.run_briefing(topic, session_id=session_id) return jsonify({"reply": summary}) except Exception as e: app.logger.error(f"Ошибка в /api/briefing: {e}") return jsonify({"error": str(e)}), 500
@app.route('/api/doctor/health-check', methods=['POST'])async def doctor_health_check(): # Заглушка для будущего DoctorProcedureEngine return jsonify({ "reply": "doctor: Система в норме. Процедурный движок на техобслуживании.", "status": "online" })
@app.route('/api/info/<info_type>')async def get_info_content(info_type): """Получить HTML контент для информ-окна""" project_path = get_current_project() # Базовый вид (три колонки) if info_type == 'default': return await render_template('info_default.html') # Оперативка - логи задач Шефа elif info_type == 'operativka': if project_path: log_path = os.path.join(project_path, 'logs', 'chief.log') if os.path.exists(log_path): with open(log_path, 'r', encoding='utf-8') as f: content = f.read() return f'<div style="padding: 15px;"><h3>📋 Оперативка Шефа</h3><pre style="font-size: 11px;">{content}</pre></div>' return '<div style="padding: 15px;">Лог оперативки не найден</div>' # Файлы проекта (по запросу от Gemini) elif info_type == 'project_file': filename = request.args.get('file', '') if project_path and filename: file_path = os.path.join(project_path, filename) if os.path.exists(file_path) and os.path.isfile(file_path): try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() escaped = content.replace('<', '<').replace('>', '>') return f'<div style="padding: 15px;"><h3>📄 {filename}</h3><pre style="font-size: 11px; max-height: 400px; overflow: auto;">{escaped}</pre></div>' except: return f'<div style="padding: 15px;">Ошибка чтения файла {filename}</div>' return '<div style="padding: 15px;">Файл не указан или не найден</div>' # Состав лаборатории (Доктор) elif info_type == 'doctor': composition_text = get_lab_composition() # Старая логика (LEGACY - закомментирована) # html = ''' # <div style="padding: 15px;"> # <h3>🏥 Состав лаборатории</h3> # <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px;"> # ''' # for role, info in composition.items(): # ... # Новая логика: вывод готового текста return f'<div style="padding: 15px;"><pre style="font-size: 12px; white-space: pre-wrap; font-family: inherit;">{composition_text}</pre></div>' return jsonify({'error': 'Unknown info type'}), 404
if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AI-colab/integrations/models/{model_id}","n_ctx": 8192,"n_gpu_layers": 35,"verbose": false4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AIcolab/integrations/models/{model_id}","n_ctx": 8192,"n_gpu_layers": 35,"verbose": false
46 unmodified lines47484950515215 unmodified lines6869707172737475767738 unmodified lines11611711811912012112212312412512612712814 unmodified lines14314414514614714814946 unmodified lines"model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active"}],"available_openrouter_models": [15 unmodified lines"nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-nano-12b-v2-vl:free","nvidia/nemotron-nano-9b-v2:free","openrouter/free:free","qwen/qwen3-4b:free","qwen/qwen3-coder:free","qwen/qwen3-next-80b-a3b-instruct:free","z-ai/glm-4.5-air:free"],"roles_fixed_mapping": {38 unmodified lines"status": "active"}},"last_updated": "2026-03-19T16:24:27.013602","last_updated_by_samurai": "2026-03-16T20:05:00","verification_report": {"total_working": 23,"timestamp": "2026-03-19T16:24:27.013602","details": {"arcee-ai/trinity-large-preview:free": "working","arcee-ai/trinity-mini:free": "limit","cognitivecomputations/dolphin-mistral-24b-venice-edition:free": "limit","google/gemma-3-12b-it:free": "limit",14 unmodified lines"nvidia/nemotron-nano-9b-v2:free": "limit","openai/gpt-oss-120b:free": "fatal","openai/gpt-oss-20b:free": "fatal","openrouter/free:free": "working","qwen/qwen3-4b:free": "limit","qwen/qwen3-coder:free": "limit","qwen/qwen3-next-80b-a3b-instruct:free": "limit",46 unmodified lines474849505152535455565758596061626364656615 unmodified lines8283848586878889909192939438 unmodified lines13313413513613713813914014114214314414514 unmodified lines16016116216316416516646 unmodified lines"model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active"},{"key": "ceo","model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active","system_prompt_file": "core/ceo.txt"},{"key": "chief","model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active","system_prompt_file": "core/chief.txt"}],"available_openrouter_models": [15 unmodified lines"nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-nano-12b-v2-vl:free","nvidia/nemotron-nano-9b-v2:free","openai/gpt-oss-120b:free","openai/gpt-oss-20b:free","openrouter/free:free","qwen/qwen3-4b:free","qwen/qwen3-coder:free","qwen/qwen3-next-80b-a3b-instruct:free","stepfun/step-3.5-flash:free","z-ai/glm-4.5-air:free"],"roles_fixed_mapping": {38 unmodified lines"status": "active"}},"last_updated": "2026-03-25T22:00:17.641736","last_updated_by_samurai": "2026-03-16T20:05:00","verification_report": {"total_working": 22,"timestamp": "2026-03-25T22:00:17.641736","details": {"arcee-ai/trinity-large-preview:free": "limit","arcee-ai/trinity-mini:free": "limit","cognitivecomputations/dolphin-mistral-24b-venice-edition:free": "limit","google/gemma-3-12b-it:free": "limit",14 unmodified lines"nvidia/nemotron-nano-9b-v2:free": "limit","openai/gpt-oss-120b:free": "fatal","openai/gpt-oss-20b:free": "fatal","openrouter/free:free": "exception","qwen/qwen3-4b:free": "limit","qwen/qwen3-coder:free": "limit","qwen/qwen3-next-80b-a3b-instruct:free": "limit",
46 unmodified lines47484950515215 unmodified lines68697071727342 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315446 unmodified lines"model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active"}],"available_openrouter_models": [15 unmodified lines"nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-nano-12b-v2-vl:free","nvidia/nemotron-nano-9b-v2:free","openrouter/free:free","qwen/qwen3-4b:free","qwen/qwen3-coder:free",42 unmodified lines"status": "active"}},"last_updated": "2026-03-23T17:05:19.247361","last_updated_by_samurai": "2026-03-16T20:05:00","verification_report": {"total_working": 23,"timestamp": "2026-03-23T17:05:19.247361","details": {"arcee-ai/trinity-large-preview:free": "limit","arcee-ai/trinity-mini:free": "limit","cognitivecomputations/dolphin-mistral-24b-venice-edition:free": "limit","google/gemma-3-12b-it:free": "limit","google/gemma-3-27b-it:free": "limit","google/gemma-3-4b-it:free": "limit","google/gemma-3n-e2b-it:free": "limit","google/gemma-3n-e4b-it:free": "limit","liquid/lfm-2.5-1.2b-instruct:free": "limit","liquid/lfm-2.5-1.2b-thinking:free": "limit","meta-llama/llama-3.2-3b-instruct:free": "limit","meta-llama/llama-3.3-70b-instruct:free": "limit","minimax/minimax-m2.5:free": "fatal","mistralai/mistral-small-3.1-24b-instruct:free": "limit","nousresearch/hermes-3-llama-3.1-405b:free": "limit","nvidia/nemotron-3-nano-30b-a3b:free": "limit","nvidia/nemotron-3-super-120b-a12b:free": "limit","nvidia/nemotron-nano-12b-v2-vl:free": "limit","nvidia/nemotron-nano-9b-v2:free": "limit","openai/gpt-oss-120b:free": "fatal","openai/gpt-oss-20b:free": "fatal","openrouter/free:free": "limit","qwen/qwen3-4b:free": "limit","qwen/qwen3-coder:free": "limit","qwen/qwen3-next-80b-a3b-instruct:free": "limit","stepfun/step-3.5-flash:free": "exception","z-ai/glm-4.5-air:free": "limit"}}}46 unmodified lines474849505152535455565758596061626364656615 unmodified lines828384858687888942 unmodified lines13213313413513613746 unmodified lines"model_id": "arcee-ai/trinity-large-preview:free","provider": "openrouter","status": "active"},{"key": "ceo","model_id": "D:/Gemini/AIColab/integrations/models/gemma-2-2b/gemma-2-2b-it.Q4_K_M.gguf","provider": "gptoss","status": "active","system_prompt_file": "core/ceo.txt"},{"key": "chief","model_id": "D:/Gemini/AIColab/integrations/models/Phi-3-mini/Phi-3-mini-4k-instruct-v0.gguf","provider": "gptoss","status": "active","system_prompt_file": "core/chief.txt"}],"available_openrouter_models": [15 unmodified lines"nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-nano-12b-v2-vl:free","nvidia/nemotron-nano-9b-v2:free","openai/gpt-oss-120b:free","openai/gpt-oss-20b:free","openrouter/free:free","qwen/qwen3-4b:free","qwen/qwen3-coder:free",42 unmodified lines"status": "active"}},"last_updated": "2026-03-25T23:45:00.000000","last_updated_by_samurai": "2026-03-25T23:45:00"}
4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AI-colab/integrations/models/{model_id}","n_ctx": 8192,"n_gpu_layers": 35,"verbose": false4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AIcolab/integrations/models/{model_id}","n_ctx": 8192,"n_gpu_layers": 35,"verbose": false
4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AI-colab/integrations/models/{model_id}","n_ctx": 4096,"n_gpu_layers": 0,"verbose": false4 unmodified lines5678910114 unmodified lines"api_url": "https://openrouter.ai/api/v1/chat/completions"},"gptoss": {"model_path_template": "D:/Gemini/AIcolab/integrations/models/{model_id}","n_ctx": 4096,"n_gpu_layers": 0,"verbose": false
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120{ "version": 4, "last_updated": "2026-02-24T20:04:23.241554", "roles": { "chief": { "type": "subject", "model_id": "Phi-3-mini-4k-instruct-q4.gguf", "provider": "gptoss", "locked": false, "locked_by": null }, "ceo": { "type": "subject", "model_id": "gemma-2-2b-it.Q4_K_M.gguf", "provider": "gptoss", "locked": false, "locked_by": null }, "E": { "type": "tool", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "flick": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "flock": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "click": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "clack": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "check": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "chock": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "link": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null }, "sync": { "type": "subject", "model_id": "arcee-ai/trinity-large-preview:free", "provider": "openrouter", "locked": false, "locked_by": null } }, "departments": { "A": { "state": "idle", "locked_at": null, "locked_by": null, "ttl": 120, "max_rounds": 2 }, "B": { "state": "idle", "locked_at": null, "locked_by": null, "ttl": 120, "max_rounds": 2 }, "C": { "state": "idle", "locked_at": null, "locked_by": null, "ttl": 120, "max_rounds": 2 }, "D": { "state": "idle", "locked_at": null, "locked_by": null, "ttl": 120, "max_rounds": 3 }, "E": { "state": "idle", "locked_at": null, "locked_by": null, "ttl": 120, "max_rounds": 1 } }}10 unmodified lines11121314151617288 unmodified lines306307308309310311312313314315316317318140 unmodified lines45946046146246346446510 unmodified linesload_dotenv()logging.basicConfig(level=logging.INFO)PROMPTS_DIR = Path("D:/Gemini/AI-colab/prompts")PROMPTS_DIR.mkdir(exist_ok=True)class BaseModelProvider(ABC):288 unmodified linesclass ModelManager:_instance = Nonedef __new__(cls, config_path="D:/Gemini/AI-colab/config/models_config.json"):if cls._instance is None:cls._instance = super(ModelManager, cls).__new__(cls)cls._instance._initialized = Falsereturn cls._instancedef __init__(self, config_path="D:/Gemini/AI-colab/config/models_config.json"):if self._initialized:returnself.config_path = config_path140 unmodified lines"""Печать диагностики GPU"""status = self.get_gpu_status()print("\n" + "="*50)print("GPU ДИАГНОСТИКА AI-Colab")print("="*50)for key, value in status.items():10 unmodified lines11121314151617288 unmodified lines306307308309310311312313314315316317318140 unmodified lines45946046146246346446510 unmodified linesload_dotenv()logging.basicConfig(level=logging.INFO)PROMPTS_DIR = Path("D:/Gemini/AIcolab/prompts")PROMPTS_DIR.mkdir(exist_ok=True)class BaseModelProvider(ABC):288 unmodified linesclass ModelManager:_instance = Nonedef __new__(cls, config_path="D:/Gemini/AIcolab/config/models_config.json"):if cls._instance is None:cls._instance = super(ModelManager, cls).__new__(cls)cls._instance._initialized = Falsereturn cls._instancedef __init__(self, config_path="D:/Gemini/AIcolab/config/models_config.json"):if self._initialized:returnself.config_path = config_path140 unmodified lines"""Печать диагностики GPU"""status = self.get_gpu_status()print("\n" + "="*50)print("GPU ДИАГНОСТИКА AIcolab")print("="*50)for key, value in status.items():
12345678 unmodified lines161718192021229 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586873 unmodified lines919293949596972 unmodified lines100101102103104105106import jsonimport loggingimport asynciofrom typing import Dict, Optionalimport osfrom pathlib import Path8 unmodified linescls._instance = super().__new__(cls)return cls._instancedef __init__(self):if not hasattr(self, '_initialized'):self._initialized = Falseself._models = {}9 unmodified lineslogger.info("ModelManager инициализирован")async def _load_config(self):"""Загрузка конфигурации моделей"""config_path = "config/models_config.json"if os.path.exists(config_path):with open(config_path, 'r', encoding='utf-8') as f:self._config = json.load(f)logger.info(f"Загружен конфиг с {len(self._config.get('active_models', []))} моделями")else:logger.error("Конфиг не найден!")self._config = {"active_models": []}async def get_model(self, key: str, require_context: bool = False):"""Получить модель по ключу. Локальные модели кэшируются для скорости."""await self._ensure_initialized()# Если модель уже загружена - просто возвращаемif key in self._models:return self._models[key]# Ищем конфигурацию моделиmodel_config = Nonefor model_cfg in self._config.get('active_models', []):# Защита: пропускаем строки, битые записи (Шаг 3 ТЗ)if not isinstance(model_cfg, dict):logger.warning(f"Skipping invalid model_cfg: {model_cfg}")continueif model_cfg.get('key') == key:model_config = model_cfgbreakif not model_config:raise ValueError(f"Модель '{key}' не найдена в конфигурации")provider = model_config.get('provider')if provider == 'gptoss':from integrations.gptoss_adapter import GptOssModelmodel = GptOssModel(model_config)await model.load_model()self._models[key] = model # Кэшируемreturn modelelif provider == 'openrouter':from integrations.openrouter_adapter import OpenRouterModelmodel = OpenRouterModel(model_config)self._models[key] = modelreturn modelelse:raise ValueError(f"Неизвестный провайдер: {provider}")def set_binding_manager(self, role_binding_manager):"""Устанавливает менеджер привязок для возможности инвалидации кэша."""self.role_binding_manager = role_binding_manager3 unmodified lines"""Очистить кэш всех моделей (ручной сброс)"""for key, model in self._models.items():if hasattr(model, 'unload_model'):await model.unload_model()self._models.clear()import gcgc.collect()2 unmodified lines"""Удалить модель из кэша по ключу роли"""if key in self._models:logger.info(f"Инвалидация модели для роли: {key}")# Мы не вызываем unload_model() здесь, так как это может быть синхронный вызов# из менеджера, а unload_model обычно асинхронный.# Просто удаляем из кэша, чтобы следующий get_model загрузил новую версию.del self._models[key]12345678 unmodified lines161718192021229 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341353 unmodified lines1391401411421431441451461471482 unmodified lines151152153154import jsonimport loggingimport asynciofrom typing import Dict, Optional, Anyimport osfrom pathlib import Path8 unmodified linescls._instance = super().__new__(cls)return cls._instancedef __init__(self, *args, **kwargs):if not hasattr(self, '_initialized'):self._initialized = Falseself._models = {}9 unmodified lineslogger.info("ModelManager инициализирован")async def _load_config(self):"""Загрузка конфигурации моделей из корня проекта."""try:# Корень проекта (D:/gemini)root_path = Path(__file__).parent.parent.parentconfig_path = root_path / "config" / "models_config.json"# Дополнительная проверка по абсолютному путиif not config_path.exists():config_path = Path("D:/gemini/config/models_config.json")except:config_path = Path("D:/gemini/config/models_config.json")if config_path.exists():try:with open(config_path, 'r', encoding='utf-8') as f:self._config = json.load(f)logger.info(f"Загружен конфиг с {len(self._config.get('active_models', {}))} моделями из {config_path}")except Exception as e:logger.error(f"Ошибка парсинга JSON конфига: {e}")self._config = {"active_models": {}, "model_providers": {}}else:logger.error(f"Конфиг НЕ найден по пути: {config_path}")self._config = {"active_models": {}, "model_providers": {}}async def _load_system_prompt(self, prompt_filename: str) -> str:"""Загружает системный промпт через ProjectContext."""try:from core.project_context import ProjectContextctx = ProjectContext.get_instance()project_path = ctx.get_current_project_path()# Прямое использование prompt_filename, без модификации, но с логированиемprompt_path = project_path / "prompts" / prompt_filenamelogger.info(f"[PROMPT_DIAG] Attempting to load prompt from: {prompt_path}")if prompt_path.exists():with open(prompt_path, 'r', encoding='utf-8') as f:content = f.read()logger.info(f"[PROMPT_DIAG] Successfully loaded prompt ({len(content)} chars)")return contentelse:logger.error(f"[PROMPT_DIAG] Prompt file NOT FOUND: {prompt_path}")except Exception as e:logger.error(f"[PROMPT_DIAG] Exception loading prompt: {e}")return ""async def _load_local_model(self, model_config: Dict, provider_config: Dict):from integrations.gptoss_adapter import GptOssModelmodel = GptOssModel(model_config)return modelasync def _load_openrouter_adapter(self, model_config: Dict, provider_config: Dict):from integrations.openrouter_adapter import OpenRouterModelmodel = OpenRouterModel(model_config)return modelasync def get_model(self, key: str) -> Any:"""Получить модель по ключу."""await self._ensure_initialized()if key in self._models:return self._models[key]model_config = Noneprovider_config = None# 1. Поиск в active_models (для локальных и явно определенных OpenRouter)if key in self._config.get('active_models', {}):model_config = self._config['active_models'][key].copy()provider = model_config.get('provider')provider_config = self._config.get('model_providers', {}).get(provider, {})logger.info(f"[DEBUG] Found model '{key}' in active_models with provider '{provider}'.")# 2. Поиск в available_openrouter_models (список ID OpenRouter)elif key in self._config.get("available_openrouter_models", []):model_config = {"key": key, "model_id": key, "provider": "openrouter"}provider_config = self._config.get('model_providers', {}).get("openrouter", {})logger.info(f"[DEBUG] Found model ID '{key}' in available_openrouter_models.")else:raise ValueError(f"Модель '{key}' не найдена в конфигурации.")# Добавляем system_prompt_file, если естьif 'system_prompt_file' in model_config:model_config['system_prompt'] = await self._load_system_prompt(model_config['system_prompt_file'])else:model_config['system_prompt'] = model_config.get('system_prompt', "")provider = model_config.get('provider')if provider == 'gptoss':model = await self._load_local_model(model_config, provider_config)elif provider == 'openrouter':model = await self._load_openrouter_adapter(model_config, provider_config)else:raise ValueError(f"Неизвестный провайдер: {provider} для модели {key}")self._models[key] = modelreturn modeldef set_binding_manager(self, role_binding_manager):"""Устанавливает менеджер привязок для возможности инвалидации кэша."""self.role_binding_manager = role_binding_manager3 unmodified lines"""Очистить кэш всех моделей (ручной сброс)"""for key, model in self._models.items():if hasattr(model, 'unload_model'):if asyncio.iscoroutinefunction(model.unload_model):await model.unload_model()else:model.unload_model()self._models.clear()import gcgc.collect()2 unmodified lines"""Удалить модель из кэша по ключу роли"""if key in self._models:logger.info(f"Инвалидация модели для роли: {key}")del self._models[key]
108 unmodified lines109110111112113114115116117118119120121108 unmodified linesclass ModelManager:_instance = Nonedef __new__(cls, config_path="D:/Gemini/AI-colab/config/models_config.json"):if cls._instance is None:cls._instance = super(ModelManager, cls).__new__(cls)cls._instance._initialized = Falsereturn cls._instancedef __init__(self, config_path="D:/Gemini/AI-colab/config/models_config.json"):if self._initialized:returnself.config_path = config_path108 unmodified lines109110111112113114115116117118119120121108 unmodified linesclass ModelManager:_instance = Nonedef __new__(cls, config_path="D:/Gemini/AIcolab/config/models_config.json"):if cls._instance is None:cls._instance = super(ModelManager, cls).__new__(cls)cls._instance._initialized = Falsereturn cls._instancedef __init__(self, config_path="D:/Gemini/AIcolab/config/models_config.json"):if self._initialized:returnself.config_path = config_path
44 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485864 unmodified lines9192939495963 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line1781791801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line2062072082092102112122132142152162172181 unmodified line22022122222322422522622722822923023123223323423515 unmodified lines2512522532542552562574 unmodified lines26226326426526626726844 unmodified linesif hasattr(self, '_initialized') and self._initialized:returnstate = get_shared_state()self.project_path = Path(state.get("current_project_path", "."))self.model_manager = model_manager# Пути к конфигам (приоритет проекту)self.config_path = Path(config_path) if config_path else self.project_path / "config" / "models_config.json"self.state_path = Path(state_path) if state_path else self.project_path / "config" / "roles_state.json"# Глобальные пути (fallback)self.global_config_path = Path(__file__).parent.parent / "config" / "models_config.json"self.global_state_path = Path(__file__).parent.parent / "config" / "roles_state.json"self._state_lock = threading.RLock()self.roles_state = self._load_state()self.models_config = self._load_config()self._prompt_registry = PromptRegistry()# Состояние блокировок отделов (в памяти)self._dept_locks = {dept: {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None} for dept in DEPT_ROLES}self._initialized = Truelogger.info("RoleBindingManager initialized. State: %s", self.state_path)def _load_config(self) -> Dict:path = self.config_path if self.config_path.exists() else self.global_config_pathif not path.exists():return {"available_openrouter_models": [], "active_models": []}try:with open(path, 'r', encoding='utf-8') as f:return json.load(f)except Exception as e:logger.error(f"Error loading models_config: {e}")return {"available_openrouter_models": [], "active_models": []}def _load_state(self) -> Dict:path = self.state_path if self.state_path.exists() else self.global_state_pathif path.exists():try:with open(path, 'r', encoding='utf-8') as f:4 unmodified linesreturn {}def _save_state(self):try:self.state_path.parent.mkdir(parents=True, exist_ok=True)with open(self.state_path, 'w', encoding='utf-8') as f:3 unmodified linesdef _get_available_models(self) -> list:models = self.models_config.get("available_openrouter_models", [])return [m for m in models if isinstance(m, dict) and m.get("status") != "error"]def get_model_for_role(self, role_key: str, task_id: Optional[str] = None, override_model_id: Optional[str] = None, exclude: Optional[List[str]] = None) -> str:"""Возвращает ID модели (Sticky Session)."""if override_model_id:return override_model_id# Sticky Session logicwith self._state_lock:if task_id:role_data = self.roles_state.get(role_key, {})if task_id in role_data:binding = role_data[task_id]if binding.get("status") == "active":model_id = binding["primary"]# Если модель в списке исключенных, форсируем новый выборif not exclude or model_id not in exclude:return model_id# Dynamic selectionpool = self._get_available_models()if exclude:pool = [m for m in pool if (m.get("key") if isinstance(m, dict) else m) not in exclude]if not pool:# Fallback to active_models if available_openrouter_models is emptypool = [m for m in self.models_config.get("active_models", []) if isinstance(m, dict)]if exclude:pool = [m for m in pool if m.get("key") not in exclude]if not pool:logger.warning("No models in pool after exclusion, using fallback string")return "google/gemini-2.0-flash-lite-preview-02-05:free"seed_str = f"{role_key}{task_id or ''}{len(exclude) if exclude else ''}"seed = int(hashlib.md5(seed_str.encode()).hexdigest(), 16)selected = pool[seed % len(pool)]model_id = selected.get("key") if isinstance(selected, dict) else selected# Persist bindingif task_id:if role_key not in self.roles_state:self.roles_state[role_key] = {}self.roles_state[role_key][task_id] = {"primary": model_id, "status": "active", "timestamp": datetime.now().isoformat()}self._save_state()# ===== DOCTOR INTEGRATION (Phase 2) =====# TODO: Uncomment only when Doctor logic is ready# ⚠️ DO NOT UNCOMMENT UNTIL:# 1. Doctor logic is fully implemented# 2. DOCTOR_ENABLED = True# 3. Tested in isolation# NOTE: pool must exist and be List[str]# from core.doctor import DoctorStub# doctor = DoctorStub()# decision = doctor.select_model(role_key, task_id, None, pool)# if decision is not None:# return decision# REM [2026-03-23] alternative return (Architecture Map style)# return selectedreturn model_idasync def get_prompt(self, role_key: str) -> str:"""Делегирует получение промпта в PromptRegistry."""return self._prompt_registry.get_prompt(role_key)def switch_binding(self, role_key: str, new_model_id: str, reason: str = "") -> bool:"""Административная смена модели для роли (глобально или в рамках текущего проекта)."""with self._state_lock:# Для простоты сох��аняем как дефолтную модель в stateif "defaults" not in self.roles_state:self.roles_state["defaults"] = {}self.roles_state["defaults"][role_key] = new_model_id1 unmodified linelogger.info(f"Switch binding for {role_key} to {new_model_id}. Reason: {reason}")return Truedef get_state(self) -> Dict:return self.roles_statedef get_fixed_model(self, role_key: str) -> str:"""Возвращает фиксированную модель для роли (без привязки к task_id)."""with self._state_lock:# Сначала проверяем дефолтную модель, если она была установлена через switch_bindingdefault_model = self.roles_state.get("defaults", {}).get(role_key)if default_model:return default_model# Если нет дефолта, используем логику динамического выбора без task_id# Это имитирует старое поведение, когда модель выбиралась один разpool = self._get_available_models()if not pool:pool = [m for m in self.models_config.get("active_models", []) if isinstance(m, dict)]if not pool:logger.warning(f"No models in pool for {role_key}, using hardcoded fallback.")return "google/gemini-2.0-flash-lite-preview-02-05:free"seed_str = f"{role_key}" # Без task_id для фиксированного выбораseed = int(hashlib.md5(seed_str.encode()).hexdigest(), 16)selected = pool[seed % len(pool)]model_id = selected.get("key") if isinstance(selected, dict) else selected1 unmodified line# --- Методы для работы отделов (Legacy support for app.py) ---def is_department_available(self, dept: str) -> bool:lock = self._dept_locks.get(dept)if not lock: return Truereturn lock["state"] == DEPT_STATE_IDLEdef lock_department(self, dept: str, state: str, locked_by: str = "system") -> bool:if not self.is_department_available(dept): return Falseself._dept_locks[dept] = {"state": state,"locked_by": locked_by,1 unmodified line}return Truedef unlock_department(self, dept: str):if dept in self._dept_locks:self._dept_locks[dept] = {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None}async def run_department(self, dept: str, request_data: Dict, caller: str = "system") -> Any:"""Запуск цикла работы отдела."""if not self.is_department_available(dept):return {"error": f"Department {dept} is busy"}self.lock_department(dept, DEPT_STATE_BUSY_BY_SYSTEM, locked_by=caller)try:roles = DEPT_ROLES.get(dept, [])if not roles:15 unmodified linesfor i, role_key in enumerate(roles):system_prompt = await self.get_prompt(role_key)model_id = self.get_model_for_role(role_key, task_id=session_id)model = await mm.get_model(model_id)user_prompt = current_result if i > 0 else message4 unmodified linescurrent_result = raw_responseif is_formal:# Упрощенная валидация JSONtry:start = raw_response.find('{')end = raw_response.rfind('}')44 unmodified lines454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061074 unmodified lines1121131141151161171181193 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801 unmodified line1821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified line2092102112122132142152162172182192202212221 unmodified line22422522622722822923023123223323423523623723823915 unmodified lines2552562572582592602614 unmodified lines26626726826927027144 unmodified linesif hasattr(self, '_initialized') and self._initialized:returnself.model_manager = model_managerself._state_lock = threading.RLock()self._prompt_registry = None # Ленивая инициализация# Параметры путей (будут установлены в _ensure_initialized)self.project_path = Noneself.config_path = config_pathself.state_path = state_pathself.roles_state = {}self.models_config = {}# Состояние блокировок отделов (в памяти)self._dept_locks = {dept: {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None} for dept in DEPT_ROLES}self._initialized = Falselogger.info("RoleBindingManager created (waiting for initialization)")async def _ensure_initialized(self):"""Гарантирует загрузку состояния и путей из shared_state."""if self._initialized:returnstate = get_shared_state()self.project_path = Path(state.get("current_project_path", "."))# Пути к конфигам (приоритет проекту)if not self.config_path:self.config_path = self.project_path / "config" / "models_config.json"if not self.state_path:self.state_path = self.project_path / "config" / "roles_state.json"# Глобальные пути (fallback)self.global_config_path = Path(__file__).parent.parent / "config" / "models_config.json"self.global_state_path = Path(__file__).parent.parent / "config" / "roles_state.json"self.roles_state = self._load_state()self.models_config = self._load_config()if self._prompt_registry is None:self._prompt_registry = PromptRegistry()self._initialized = Truelogger.info("RoleBindingManager initialized. Project: %s", self.project_path)def _load_config(self) -> Dict:path = self.config_path if self.config_path and self.config_path.exists() else self.global_config_pathif not path.exists():return {"available_openrouter_models": [], "active_models": {}}try:with open(path, 'r', encoding='utf-8') as f:return json.load(f)except Exception as e:logger.error(f"Error loading models_config: {e}")return {"available_openrouter_models": [], "active_models": {}}def _load_state(self) -> Dict:path = self.state_path if self.state_path and self.state_path.exists() else self.global_state_pathif path.exists():try:with open(path, 'r', encoding='utf-8') as f:4 unmodified linesreturn {}def _save_state(self):if not self.state_path:returntry:self.state_path.parent.mkdir(parents=True, exist_ok=True)with open(self.state_path, 'w', encoding='utf-8') as f:3 unmodified linesdef _get_available_models(self) -> list:models = self.models_config.get("available_openrouter_models", [])return [m for m in models if isinstance(m, str) and m]async def get_model_for_role(self, role_key: str, task_id: Optional[str] = None, override_model_id: Optional[str] = None, exclude: Optional[str] = None) -> str:await self._ensure_initialized()if override_model_id:return override_model_idif task_id:role_state = self.roles_state.get(role_key, {})binding = role_state.get(task_id)if binding and binding.get("status") == "active":return binding["primary"]pool = self._get_available_models()if not pool:# Fallback to active_models if availableactive = self.models_config.get("active_models", {})if role_key in active:return active[role_key].get("model_id", "unknown")raise RuntimeError("No available models in pool. Run updater first.")# Исключаем модель, если она указанаif exclude:pool = [m for m in pool if m != exclude]if not pool:# Если после исключения ничего не осталось, берем из общего пула (или возвращаем ошибку)pool = self._get_available_models()seed_str = role_key + (task_id or "")seed = int(hashlib.md5(seed_str.encode('utf-8')).hexdigest(), 16)selected = pool[seed % len(pool)]model_id = selected["key"] if isinstance(selected, dict) else selectedif task_id:if role_key not in self.roles_state:self.roles_state[role_key] = {}self.roles_state[role_key][task_id] = {"primary": model_id, "status": "active"}self._save_state()return model_idasync def get_prompt(self, role_key: str) -> str:"""Делегирует получение промпта в PromptRegistry."""await self._ensure_initialized()return self._prompt_registry.get_prompt(role_key)async def switch_binding(self, role_key: str, new_model_id: str, reason: str = "") -> bool:"""Административная смена модели для роли."""await self._ensure_initialized()with self._state_lock:if "defaults" not in self.roles_state:self.roles_state["defaults"] = {}self.roles_state["defaults"][role_key] = new_model_id1 unmodified linelogger.info(f"Switch binding for {role_key} to {new_model_id}. Reason: {reason}")return Trueasync def get_state(self) -> Dict:await self._ensure_initialized()return self.roles_stateasync def get_fixed_model(self, role_key: str) -> str:"""Возвращает фиксированную модель для роли."""await self._ensure_initialized()with self._state_lock:default_model = self.roles_state.get("defaults", {}).get(role_key)if default_model:return default_modelpool = self._get_available_models()if not pool:active = self.models_config.get("active_models", {})if role_key in active:return active[role_key].get("model_id")return "google/gemini-2.0-flash-lite-preview-02-05:free"seed_str = f"{role_key}"seed = int(hashlib.md5(seed_str.encode()).hexdigest(), 16)selected = pool[seed % len(pool)]model_id = selected.get("key") if isinstance(selected, dict) else selected1 unmodified line# --- Методы для работы отделов (Legacy support for app.py) ---async def is_department_available(self, dept: str) -> bool:await self._ensure_initialized()lock = self._dept_locks.get(dept)if not lock: return Truereturn lock["state"] == DEPT_STATE_IDLEasync def lock_department(self, dept: str, state: str, locked_by: str = "system") -> bool:if not await self.is_department_available(dept): return Falseself._dept_locks[dept] = {"state": state,"locked_by": locked_by,1 unmodified line}return Trueasync def unlock_department(self, dept: str):if dept in self._dept_locks:self._dept_locks[dept] = {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None}async def run_department(self, dept: str, request_data: Dict, caller: str = "system") -> Any:"""Запуск цикла работы отдела."""if not await self.is_department_available(dept):return {"error": f"Department {dept} is busy"}await self.lock_department(dept, DEPT_STATE_BUSY_BY_SYSTEM, locked_by=caller)try:roles = DEPT_ROLES.get(dept, [])if not roles:15 unmodified linesfor i, role_key in enumerate(roles):system_prompt = await self.get_prompt(role_key)model_id = await self.get_model_for_role(role_key, task_id=session_id)model = await mm.get_model(model_id)user_prompt = current_result if i > 0 else message4 unmodified linescurrent_result = raw_responseif is_formal:try:start = raw_response.find('{')end = raw_response.rfind('}')
210 unmodified lines2112122132142152162172182192202212222231 unmodified line225226227228229230231210 unmodified linesasync def process(self, sid, ws, msg):try:data = json.loads(msg)directive = Directive(action=ActionType(data["directive"]["action"]),tool=data["directive"]["tool"],parameters=data["directive"]["parameters"])result = await self.sessions[sid].execute(directive)# Преобразуем результат в словарь вручную для надежностиresult_dict = {"success": result.success,1 unmodified line"error": result.error,"metadata": result.metadata}await ws.send(json.dumps({"type": "execution_result","session_id": sid,210 unmodified lines2112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472481 unmodified line250251252253254255256210 unmodified linesasync def process(self, sid, ws, msg):try:data = json.loads(msg)# Логируем входящее сообщение для диагностикиprint(f"[DEBUG_MCP] Received message: {data}")if "directive" not in data or not isinstance(data["directive"], dict):raise ValueError("Message must contain a 'directive' object with 'action', 'tool', and 'parameters'.")data = json.loads(msg)# Логируем входящее сообщение для диагностикиprint(f"[DEBUG_MCP] Received message: {data}")if "directive" not in data or not isinstance(data["directive"], dict):error_message = "Message must contain a 'directive' object with 'action', 'tool', and 'parameters'. Provided data: " + str(data.get("directive", "None"))print(f"[ERROR] {error_message}")raise ValueError(error_message)directive_data = data["directive"]# Проверка наличия обязательных полей в directiveif not all(k in directive_data for k in ["action", "tool", "parameters"]):error_message = f"Directive object is missing required keys. Found: {directive_data.keys()}"print(f"[ERROR] {error_message}")raise ValueError(error_message)directive = Directive(action=ActionType(directive_data["action"]),tool=directive_data["tool"],parameters=directive_data["parameters"])result = await self.sessions[sid].execute(directive)# Преобразуем результат в словарь вручную для надежностиresult_dict = {"success": result.success,1 unmodified line"error": result.error,"metadata": result.metadata}await ws.send(json.dumps({"type": "execution_result","session_id": sid,
16 unmodified lines1718192021222324252627282930313233343536373839404142434445464762 unmodified lines11011111211311411511611711811912012116 unmodified linesself.config = configself.role_key = config.get("key") # например 'flick'self.api_key = os.getenv("OPENROUTER_API_KEY")if not self.api_key:raise ValueError("OPENROUTER_API_KEY не установлен")# Получаем фиксированный model_id из RoleBindingManagerrbm = RoleBindingManager()self.model_id = rbm.get_fixed_model(self.role_key)if not self.model_id:# Fallback на модель по умолчанию, если фиксация не найдена в statefallback_model = config.get("model_id") or "meta-llama/llama-3.2-3b-instruct:free"logger.warning(f"Для роли {self.role_key} не найдена фиксированная модель в RoleBindingManager, используется fallback: {fallback_model}")self.model_id = fallback_modelself.short_name = config.get("short_name", self.model_id.split('/')[-1].split(':')[0]) # short_name для UI# Если даже fallback пустой - эскалацияif not self.model_id:raise ConfigError(f"Критическая ошибка: для роли {self.role_key} не задана модель и отсутствует fallback.")else:logger.info(f"Для роли {self.role_key} используется зафиксированная модель из реестра: {self.model_id}")async def generate(self, prompt=None, system_prompt=None, messages=None, **kwargs):"""Генерация ответа. Если передан messages (список словарей с полями role/content),используем его как полную историю. Иначе формируем из system_prompt и prompt."""return await self._generate_with_retry(prompt, system_prompt, messages=messages, retry_count=0, **kwargs)async def _generate_with_retry(self, prompt, system_prompt, messages=None, retry_count=0, **kwargs):62 unmodified lines"""Выполняет поиск новой модели и повторный запрос."""rbm = RoleBindingManager()# REM [2026-03-16 21:05] new_model_id = rbm.get_next_available_model(self.role_key, exclude=self.model_id)new_model_id = rbm.get_model_for_role(self.role_key, task_id=kwargs.get('task_id', 'default'), exclude=self.model_id)if new_model_id and new_model_id != self.model_id:old_model = self.model_id# Фиксируем новую привязку в реестреrbm.switch_binding(self.role_key, new_model_id, reason=f"auto_failover:{error_reason}")# Обновляем текущий экземплярself.model_id = new_model_idlogger.info(f"🔄 Роль {self.role_key} успешно переключена: {old_model} -> {new_model_id}")16 unmodified lines171819202122232425262728293031323334353637383940414243444546474862 unmodified lines11111211311411511611711811912012112216 unmodified linesself.config = configself.role_key = config.get("key") # например 'flick'self.api_key = os.getenv("OPENROUTER_API_KEY")self.model_id = None # Будет получено в generateself.short_name = config.get("short_name", "unknown")if not self.api_key:raise ValueError("OPENROUTER_API_KEY не установлен")async def _ensure_model_id(self):if self.model_id:returnrbm = RoleBindingManager()self.model_id = await rbm.get_fixed_model(self.role_key)if not self.model_id:fallback_model = self.config.get("model_id") or "meta-llama/llama-3.2-3b-instruct:free"logger.warning(f"Для роли {self.role_key} не найдена фиксированная модель, используется fallback: {fallback_model}")self.model_id = fallback_modelif not self.short_name or self.short_name == "unknown":self.short_name = self.model_id.split('/')[-1].split(':')[0]async def generate(self, prompt=None, system_prompt=None, messages=None, **kwargs):"""Генерация ответа."""await self._ensure_model_id()return await self._generate_with_retry(prompt, system_prompt, messages=messages, retry_count=0, **kwargs)async def _generate_with_retry(self, prompt, system_prompt, messages=None, retry_count=0, **kwargs):62 unmodified lines"""Выполняет поиск новой модели и повторный запрос."""rbm = RoleBindingManager()# REM [2026-03-16 21:05] new_model_id = rbm.get_next_available_model(self.role_key, exclude=self.model_id)new_model_id = await rbm.get_model_for_role(self.role_key, task_id=kwargs.get('task_id', 'default'), exclude=self.model_id)if new_model_id and new_model_id != self.model_id:old_model = self.model_id# Фиксируем новую привязку в реестреawait rbm.switch_binding(self.role_key, new_model_id, reason=f"auto_failover:{str(error_reason)}")# Обновляем текущий экземплярself.model_id = new_model_idlogger.info(f"🔄 Роль {self.role_key} успешно переключена: {old_model} -> {new_model_id}")
1[ERROR] Error processing message: 'directive'28 unmodified lines293031323328 unmodified lines"status": "active","timestamp": "2026-03-23T17:05:08.446521"}}}28 unmodified lines293031323334353637383928 unmodified lines"status": "active","timestamp": "2026-03-23T17:05:08.446521"}},"arcee-ai/trinity-large-preview:free": {"default": {"primary": "arcee-ai/trinity-large-preview:free","status": "active"}}}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970[2026-03-23 17:08:22,185] INFO in app: Директории проекта созданы: d:\gemini\aicolab\projects\Bestihi.ru[2026-03-23 17:08:22,186] INFO in app: 🚀 Updater моделей (интегрированный) запущен в фоне[2026-03-23 17:08:22,187] INFO in app: Сервер готов к ленивой инициализации[2026-03-23 17:08:22 +0200] [10592] [INFO] Running on http://0.0.0.0:5000 (CTRL + C to quit)* Serving Quart app 'app'* Debug mode: True* Please use an ASGI server (e.g. Hypercorn) directly in production* Running on http://0.0.0.0:5000 (CTRL + C to quit)🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 349 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:25 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 39020[2026-03-23 17:08:26 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 16392🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50607 GET / 1.1 200 23647 10971[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50607 GET /A.png 1.1 404 207 14961[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50608 GET /B.png 1.1 404 207 27924[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50610 GET /api/project/current 1.1 404 207 17952[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50611 GET /C.png 1.1 404 207 23936[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50612 GET /D.png 1.1 404 207 18949[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50613 GET /api/model_mapping 1.1 200 26 22911[2026-03-23 17:08:31 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 66896🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:36 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 16951🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:41 +0200] [10592] [INFO] 127.0.0.1:50618 GET /api/gcb/queue 1.1 200 3 10105🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:46 +0200] [10592] [INFO] 127.0.0.1:50618 GET /api/gcb/queue 1.1 200 3 32215[2026-03-23 17:08:46 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 200 939 9979648🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:51 +0200] [10592] [INFO] 127.0.0.1:50618 GET /api/gcb/queue 1.1 200 3 10132[2026-03-23 17:08:51,567] ERROR in app: Error calling Staff model flock: OpenRouter ошибка 400 для check: {"error":{"message":"check is not a valid model ID","code":400},"user_id":"user_35tu3hSfootJ7QgoZdM2P9iLXjE"}[2026-03-23 17:08:51 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 500 404 1190645🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:56 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 13963[2026-03-23 17:08:56,996] ERROR in app: Error calling Staff model click: OpenRouter ошибка 400 для check: {"error":{"message":"check is not a valid model ID","code":400},"user_id":"user_35tu3hSfootJ7QgoZdM2P9iLXjE"}🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)[2026-03-23 17:08:57 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 500 404 203395❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)[2026-03-23 17:09:01 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 22309[2026-03-23 17:09:02,673] ERROR in app: Error calling Staff model clack: OpenRouter ошибка 400 для check: {"error":{"message":"check is not a valid model ID","code":400},"user_id":"user_35tu3hSfootJ7QgoZdM2P9iLXjE"}🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:02 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 500 404 183915🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:06 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 15931[2026-03-23 17:09:10,240] ERROR in app: Error calling ceo: Модель 'ceo' не найдена в конфигурации[2026-03-23 17:09:10,240] ERROR in app: Secretary call failed: module 'core.gateway' has no attribute 'call_gemini'🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:10 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 200 343 5984🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:11 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 8976🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:16 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 19905ChiefOrchestrator delayed initialization warning: Модель 'chief' не найдена в конфигурации[2026-03-23 17:09:17,354] ERROR in app: Error calling chief: Chief model not available. Check your models_config.json and project context.[2026-03-23 17:09:17,354] ERROR in app: Secretary call failed: module 'core.gateway' has no attribute 'call_gemini'🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)[2026-03-23 17:09:17 +0200] [10592] [INFO] 127.0.0.1:50607 POST /api/secretary 1.1 200 343 9998❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)[2026-03-23 17:09:19 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 19166[2026-03-23 17:09:21 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 9941[2026-03-23 17:09:26 +0200] [10592] [INFO] 127.0.0.1:50607 GET /api/gcb/queue 1.1 200 3 28425🚫 openrouter/free:free: limit 🆓 (HTTP 429)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511INFO: Started server process [1540]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)INFO: 127.0.0.1:64944 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64944 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:64944 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:64945 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:64944 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:64947 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64947 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:64947 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:64944 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:64945 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64945 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:64945 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:64944 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:64947 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64947 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\ceo_system.txtD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (4096) < n_ctx_train (8192) -- the full capacity of the model will not be utilizedllama_kv_cache_unified_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)INFO: 127.0.0.1:64948 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64951 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64951 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64947 - "POST /api/secretary HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:11:45,947] ERROR in app: Error calling Staff model flick: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:64951 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:64951 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64951 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\chief_system.txtINFO: 127.0.0.1:64956 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64957 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64958 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64959 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64951 - "POST /api/secretary HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:12:13,585] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:64956 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:64956 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64956 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64964 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64965 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64965 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64965 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64969 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64970 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64970 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64972 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:13:05,351] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:64972 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:64972 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64972 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64975 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64976 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64976 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64976 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64977 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64978 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64978 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64978 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64979 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64979 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64980 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64981 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64981 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64983 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64984 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64984 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64984 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:64986 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for connections to close. (CTRL+C to force quit)INFO: 127.0.0.1:64972 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:64979 - "POST /api/secretary HTTP/1.1" 200 OKINFO: Finished server process [1540]INFO: ASGI 'lifespan' protocol appears unsupported.🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 347 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)🚫 openrouter/free:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-4b:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-coder:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-next-80b-a3b-instruct:free: limit 🆓 (HTTP 429)🔥 stepfun/step-3.5-flash:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 z-ai/glm-4.5-air:free: limit 🆓 (HTTP 429)[INFO] Найдено 23 рабочих моделей.📍 Роли flick назначена: arcee-ai/trinity-large-preview:free📍 Роли flock назначена: arcee-ai/trinity-large-preview:free📍 Роли click назначена: arcee-ai/trinity-large-preview:free📍 Роли clack назначена: arcee-ai/trinity-large-preview:free📍 Роли check назначена: arcee-ai/trinity-large-preview:free📍 Роли chock назначена: arcee-ai/trinity-large-preview:free📍 Роли link назначена: arcee-ai/trinity-large-preview:free📍 Роли sync назначена: arcee-ai/trinity-large-preview:free✅ У��ПЕХ! Конфигурация обновлена.INFO: Started server process [9624]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)INFO: 127.0.0.1:65419 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:65419 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:65418 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:65418 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65421 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65421 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65421 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65426 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65426 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65426 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65426 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65430 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\ceo_system.txtD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (4096) < n_ctx_train (8192) -- the full capacity of the model will not be utilizedllama_kv_cache_unified_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)INFO: 127.0.0.1:65431 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65430 - "POST /api/secretary HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:59:40,460] ERROR in app: Error calling Staff model flick: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:65431 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:65431 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\chief_system.txtINFO: 127.0.0.1:65435 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65436 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65431 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:65431 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:59:56,347] ERROR in app: Error calling Staff model sync: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:65435 - "POST /api/secretary HTTP/1.1" 500 Internal Server Error⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 21:59:59,525] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:65435 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:65435 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65439 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65439 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:65439 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65440 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65440 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65442 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:65441 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for application shutdown.INFO: Application shutdown complete.INFO: Finished server process [9624]🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 347 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)🔥 openrouter/free:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 qwen/qwen3-4b:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-coder:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-next-80b-a3b-instruct:free: limit 🆓 (HTTP 429)🔥 stepfun/step-3.5-flash:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 z-ai/glm-4.5-air:free: limit 🆓 (HTTP 429)[INFO] Найдено 22 рабочих моделей.📍 Роли flick назначена: arcee-ai/trinity-large-preview:free📍 Роли flock назначена: arcee-ai/trinity-large-preview:free📍 Роли click назначена: arcee-ai/trinity-large-preview:free📍 Роли clack назначена: arcee-ai/trinity-large-preview:free📍 Роли check назначена: arcee-ai/trinity-large-preview:free📍 Роли chock назначена: arcee-ai/trinity-large-preview:free📍 Роли link назначена: arcee-ai/trinity-large-preview:free📍 Роли sync назначена: arcee-ai/trinity-large-preview:free✅ УСПЕХ! Конфигурация обновлена.INFO: Started server process [8392]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)INFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:49294 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\ceo_system.txtD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (4096) < n_ctx_train (8192) -- the full capacity of the model will not be utilizedllama_kv_cache_unified_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)INFO: 127.0.0.1:49294 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49294 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "POST /api/secretary HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 22:09:50,746] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:49287 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\chief_system.txtINFO: 127.0.0.1:49298 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49298 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49298 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49287 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:49302 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 22:10:17,280] ERROR in app: Error calling Staff model flick: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:49287 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:49287 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49303 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49303 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:49304 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for application shutdown.INFO: Application shutdown complete.INFO: Finished server process [8392]🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 347 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)🚫 openrouter/free:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-4b:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-coder:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-next-80b-a3b-instruct:free: limit 🆓 (HTTP 429)INFO: Started server process [5432]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)INFO: 127.0.0.1:50090 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50090 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50091 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50091 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50091 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50092 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50092 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\ceo_system.txtD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (4096) < n_ctx_train (8192) -- the full capacity of the model will not be utilizedllama_kv_cache_unified_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)INFO: 127.0.0.1:50096 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 23:00:48,063] ERROR in app: Error calling Staff model flick: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:50095 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:50095 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\chief_system.txtINFO: 127.0.0.1:50099 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50099 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:50095 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50100 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 23:01:40,674] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:50101 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50101 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for application shutdown.INFO: Application shutdown complete.INFO: Finished server process [5432]🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 347 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)🔥 openrouter/free:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 qwen/qwen3-4b:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-coder:free: limit 🆓 (HTTP 429)🚫 qwen/qwen3-next-80b-a3b-instruct:free: limit 🆓 (HTTP 429)🔥 stepfun/step-3.5-flash:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 z-ai/glm-4.5-air:free: limit 🆓 (HTTP 429)[INFO] Найдено 22 рабочих моделей.📍 Роли flick назначена: arcee-ai/trinity-large-preview:free📍 Роли flock назначена: arcee-ai/trinity-large-preview:free📍 Роли click назначена: arcee-ai/trinity-large-preview:free📍 Роли clack назначена: arcee-ai/trinity-large-preview:free📍 Роли check назначена: arcee-ai/trinity-large-preview:free📍 Роли chock назначена: arcee-ai/trinity-large-preview:free📍 Роли link назначена: arcee-ai/trinity-large-preview:free📍 Роли sync назначена: arcee-ai/trinity-large-preview:free✅ УСПЕХ! Конфигурация обновлена.INFO: Started server process [11220]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)INFO: 127.0.0.1:50227 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50228 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50230 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50231 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50229 - "GET /chat.js HTTP/1.1" 200 OKINFO: 127.0.0.1:50229 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50231 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50229 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50230 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50230 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50230 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50229 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50231 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50228 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50227 - "GET /chat.js HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50227 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50228 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50227 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50228 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50231 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50229 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50227 - "GET /chat.js HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50229 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50227 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50229 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50229 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50229 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50227 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50231 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50228 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50230 - "GET /chat.js HTTP/1.1" 200 OKINFO: 127.0.0.1:50230 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50228 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50230 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50228 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50240 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\ceo_system.txtD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (4096) < n_ctx_train (8192) -- the full capacity of the model will not be utilizedllama_kv_cache_unified_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)INFO: 127.0.0.1:50242 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50240 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:50242 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 23:06:11,545] ERROR in app: Error calling Staff model flick: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:50240 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:50240 - "GET /api/gcb/queue HTTP/1.1" 200 OK[PROMPT_DIAG] Prompt file NOT FOUND: d:\gemini\aicolab\projects\Bestihi.ru\prompts\chief_system.txtINFO: 127.0.0.1:50245 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50247 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50240 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:50240 - "GET /api/gcb/queue HTTP/1.1" 200 OK⚠️ Ошибка 429 для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free). Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)⏰ Сбой (таймаут/сеть) для arcee-ai/trinity-large-preview:free (arcee-ai/trinity-large-preview:free): Failover failed: No fallback models for arcee-ai/trinity-large-preview:free. Попытка авто-переключения...❌ Нет доступных fallback-моделей для роли arcee-ai/trinity-large-preview:free (текущая: arcee-ai/trinity-large-preview:free)[2026-03-25 23:06:31,538] ERROR in app: Error calling Staff model doctor: Failover failed: No fallback models for arcee-ai/trinity-large-preview:freeINFO: 127.0.0.1:50245 - "POST /api/secretary HTTP/1.1" 500 Internal Server ErrorINFO: 127.0.0.1:50245 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50245 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50251 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50253 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for application shutdown.INFO: Application shutdown complete.INFO: Finished server process [11220]🚀 СИНХРОНИЗАЦИЯ КОЛЛЕКТИВНОГО РАЗУМА: ЗАПУСК[INFO] Загружено 347 моделей из OpenRouter API.[INFO] Начинаем верификацию 27 бесплатных моделей...[INFO] Начинаем последовательную верификацию 27 моделей...🚫 arcee-ai/trinity-large-preview:free: limit 🆓 (HTTP 429)🚫 arcee-ai/trinity-mini:free: limit 🆓 (HTTP 429)🚫 cognitivecomputations/dolphin-mistral-24b-venice-edition:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-12b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-27b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3-4b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e2b-it:free: limit 🆓 (HTTP 429)🚫 google/gemma-3n-e4b-it:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-instruct:free: limit 🆓 (HTTP 429)🚫 liquid/lfm-2.5-1.2b-thinking:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.2-3b-instruct:free: limit 🆓 (HTTP 429)🚫 meta-llama/llama-3.3-70b-instruct:free: limit 🆓 (HTTP 429)❌ minimax/minimax-m2.5:free: fatal 🆓 (HTTP 404)🚫 mistralai/mistral-small-3.1-24b-instruct:free: limit 🆓 (HTTP 429)🚫 nousresearch/hermes-3-llama-3.1-405b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-nano-30b-a3b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-3-super-120b-a12b:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-12b-v2-vl:free: limit 🆓 (HTTP 429)🚫 nvidia/nemotron-nano-9b-v2:free: limit 🆓 (HTTP 429)❌ openai/gpt-oss-120b:free: fatal 🆓 (HTTP 404)❌ openai/gpt-oss-20b:free: fatal 🆓 (HTTP 404)🔥 openrouter/free:free: exception 🆓 ('NoneType' object has no attribute 'strip')🚫 qwen/qwen3-4b:free: limit 🆓 (HTTP 429)
1{"active_models": [{"key": "test_gpu", "model_id": "integrations/models/SmolLM2-360M-Instruct-GGUF/smollm2-360m-instruct-q8_0.gguf", "provider": "gptoss", "n_gpu_layers": 20, "n_ctx": 2048}]}123456789101112131415161718192021222324252627282930313233343536
import sysimport ossys.path.insert(0, os.getcwd())import jsontry: from core.llm_integrations.gptoss_adapter import GptOssModelexcept ImportError: from integrations.gptoss_adapter import GptOssModel
print("Loading test config...")with open("test_gpu_config.json", "r") as f: config = json.load(f)
model_config = config["active_models"][0]print(f"Model config: {model_config}")
print("\nCreating model instance...")model = GptOssModel(model_config)
print("\nAttempting to load model...")try: model.load_model() print("SUCCESS: Model loaded") if hasattr(model, 'model'): print(f"Model type: {type(model.model)}") else: print("WARNING: Model instance has no 'model' attribute") model.unload_model() print("Model unloaded")except Exception as e: print(f"FAILURE: Load error: {e}") import traceback traceback.print_exc()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112#!/usr/bin/env python3"""Тестовая загрузка новых моделей с мониторингом VRAM"""import subprocessimport timeimport jsonfrom pathlib import Pathimport sys
def monitor_vram(): """Мониторинг использования VRAM""" try: result = subprocess.run( ['nvidia-smi', '--query-gpu=memory.used,memory.total', '--format=csv,noheader,nounits'], capture_output=True, text=True ) if result.returncode == 0: used, total = result.stdout.strip().split(', ') return int(used), int(total) except: pass return None, None
def test_model_load(model_config_key, config_file="AIColab/config/models_config.json"): """Тест загрузки конкретной модели""" # Добавляем корневую папку AIColab в sys.path для импорта sys.path.append(str(Path("AIColab").resolve())) # Загружаем конфиг with open(config_file, 'r', encoding='utf-8') as f: config = json.load(f) # Находим конфиг модели model_config = None for model in config['active_models']: if model['key'] == model_config_key: model_config = model break if not model_config: print(f"❌ Модель {model_config_key} не найдена в конфиге") return False print(f"🔄 Тестируем загрузку: {model_config_key}") print(f" Модель: {model_config.get('model_id')}") # Пытаемся получить параметры из llama_params или корня конфига l_params = model_config.get('llama_params', model_config) print(f" n_ctx: {l_params.get('n_ctx')}") print(f" n_gpu_layers: {l_params.get('n_gpu_layers')}") # Начальное использование VRAM vram_before, total = monitor_vram() if vram_before: print(f" VRAM до загрузки: {vram_before} MB / {total} MB") try: # Импортируем и создаем адаптер from integrations.gptoss_adapter import GptOssModel adapter = GptOssModel(model_config) print(f" ✅ Адаптер создан") async def _load_and_generate(): # load_model берет параметры из self.config напрямую или из llama_params? # В текущей реализации gptoss_adapter.py (которую я правил ранее) # параметры берутся из self.config.get(...) # Чтобы тест был честным, временно дополним конфиг для адаптера if 'llama_params' in model_config: model_config.update(model_config['llama_params']) await adapter.load_model() print(f" ✅ Модель {model_config_key} загружена.") test_prompt = "[INTRO] Тестовый запрос." response = await adapter.generate(test_prompt) print(f" ✅ Ответ получен (первые 50 симв): {response[:50]}...") await adapter.unload_model() return True import asyncio ok = asyncio.run(_load_and_generate()) # VRAM после vram_after, _ = monitor_vram() if vram_after and vram_before: print(f" 📊 Использование VRAM: +{vram_after - vram_before} MB") return ok except Exception as e: print(f" ❌ Ошибка загрузки: {e}") return False
if __name__ == "__main__": print("🎌 ТЕСТ ЗАГРУЗКИ НОВЫХ МОДЕЛЕЙ") print("=" * 50) # Тестируем Шефа chief_ok = test_model_load("chief") print("\n" + "=" * 50 + "\n") # Тестируем СЕО ceo_ok = test_model_load("ceo") print("\n" + "=" * 50) if chief_ok and ceo_ok: print("✅ ОБЕ МОДЕЛИ УСПЕШНО ЗАГРУЖЕНЫ!") else: print("❌ ЕСТЬ ПРОБЛЕМЫ С ЗАГРУЗКОЙ МОДЕЛЕЙ")AIColab_cuda_2.bat+6-10
app.py+63-48
app.py.bakAdded+521
config/models_config.backup.json+1-1
config/models_config.bak+22-5
config/models_config.json+18-35
config/models_config.json.backup_1770214199+1-1
config/models_config.json.backup_20260115_002053+1-1
config/roles_state.jsonDeleted-120
core/model_management.backup.py+4-4
core/model_management.py+95-47
core/model_management_backup.py+2-2
core/role_binding_manager.py+96-93
gemini_mcp_server.py+30-5
integrations/openrouter_adapter.py+17-16
list.txtAdded
mcp_server_crash_log.txtAdded+1
mcp_server_crash_log_25.03.2026Added
projects/Bestihi.ru/config/roles_state.json+6
server_crash_log.txt+486-45
server_crash_log_25.03.2026Added
tests/test_gpu_config.jsonAdded+1
tests/test_gpu_load.pyAdded+36
tests/test_models.pyAdded+112