Download core/role_binding_manager.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/role_binding_manager.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/role_binding_manager.py
-
curl -L -o role_binding_manager.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/role_binding_manager.py
13.6 kB
| # REM [2026-04-08] Zero Module Execution (SPEC_2026_04_08) | |
| import json | |
| import os | |
| import threading | |
| import hashlib | |
| import logging | |
| import asyncio | |
| from typing import Dict, Optional, Any, List, Tuple, Union | |
| from datetime import datetime, timedelta | |
| from pathlib import Path | |
| # REM [2026-04-08] These constants are safe to keep at module level | |
| # Состояния отделов | |
| DEPT_STATE_IDLE = "idle" | |
| DEPT_STATE_BUSY_BY_CEO = "busy_by_ceo" | |
| DEPT_STATE_BUSY_BY_SYSTEM = "busy_by_system" | |
| # Константы | |
| LOCK_TTL_SECONDS = 120 | |
| MAX_ROUNDS_DEFAULT = 2 | |
| # Маппинг отделов и ролей | |
| DEPT_ROLES = { | |
| "A": ["flick", "flock"], | |
| "B": ["click", "clack"], | |
| "C": ["check", "chock"], | |
| "D": ["link", "sync"] | |
| } | |
| _role_manager = None | |
| def get_role_manager(model_manager=None, config_path=None, state_path=None): | |
| """ | |
| Lazy getter for the singleton instance. | |
| This is the ONLY entrypoint to the RoleBindingManager. | |
| """ | |
| global _role_manager | |
| if _role_manager is None: | |
| _role_manager = RoleBindingManager(model_manager, config_path, state_path) | |
| return _role_manager | |
| class RoleBindingManager: | |
| """ | |
| Manages role-to-model bindings with Zero Module Execution invariant. | |
| """ | |
| def __init__(self, model_manager=None, config_path=None, state_path=None): | |
| self.model_manager = model_manager | |
| self.config_path = config_path | |
| self.state_path = state_path | |
| # Internal state (Lazy initialization in _ensure_initialized) | |
| self.project_path = None | |
| self.roles_state = {} | |
| self.models_config = {} | |
| self._bindings = {} # Sticky Memory Cache | |
| # Department locks (Initial state is empty, populated in _ensure_initialized) | |
| self._dept_locks = {} | |
| self._initialized = False | |
| self._prompt_registry = None | |
| # Lazy objects | |
| self._logger = None | |
| self._state_lock = None | |
| def _get_logger(self): | |
| """Lazy logger initialization.""" | |
| if self._logger is None: | |
| self._logger = logging.getLogger(__name__) | |
| return self._logger | |
| def _get_state_lock(self): | |
| """Lazy threading lock initialization.""" | |
| if self._state_lock is None: | |
| self._state_lock = threading.RLock() | |
| return self._state_lock | |
| async def _ensure_initialized(self): | |
| """ | |
| Guarantees loading of state and configuration paths lazily. | |
| Triggers execution ONLY when first used in runtime. | |
| """ | |
| if self._initialized: | |
| return | |
| # LAZY IMPORTS to avoid module execution on import | |
| from core.shared_state import get_shared_state | |
| from core.prompt_registry import PromptRegistry | |
| logger = self._get_logger() | |
| state = get_shared_state() | |
| self.project_path = Path(state.get("current_project_path", ".")) | |
| # Configure paths based on project state | |
| 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" | |
| # Global paths (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" | |
| # Load data | |
| self.roles_state = self._load_state() | |
| self.models_config = self._load_config() | |
| # Ensure state file exists | |
| if not self.state_path.exists(): | |
| self._save_state() | |
| logger.info(f"Created initial roles_state.json at {self.state_path}") | |
| if self._prompt_registry is None: | |
| self._prompt_registry = PromptRegistry() | |
| # Initialize department locks | |
| self._dept_locks = { | |
| dept: {"state": DEPT_STATE_IDLE, "locked_by": None, "expires": None} | |
| for dept in DEPT_ROLES | |
| } | |
| self._initialized = True | |
| logger.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_path | |
| if 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: | |
| self._get_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_path | |
| if path.exists(): | |
| try: | |
| with open(path, 'r', encoding='utf-8') as f: | |
| return json.load(f) | |
| except Exception as e: | |
| self._get_logger().error(f"Error loading roles_state: {e}") | |
| return {} | |
| return {} | |
| def _save_state(self): | |
| if not self.state_path: | |
| return | |
| try: | |
| self.state_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(self.state_path, 'w', encoding='utf-8') as f: | |
| json.dump(self.roles_state, f, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| self._get_logger().error(f"Error saving roles_state: {e}") | |
| def _get_available_models(self) -> List[str]: | |
| models = self.models_config.get('available_openrouter_models', []) | |
| result = [] | |
| for m in models: | |
| if isinstance(m, str): | |
| cleaned = m.strip() | |
| if cleaned: | |
| result.append(cleaned) | |
| elif isinstance(m, dict): | |
| key = m.get("key", "") | |
| if key and isinstance(key, str): | |
| cleaned = key.strip() | |
| if cleaned: | |
| result.append(cleaned) | |
| if not result: | |
| raise RuntimeError("No available models in pool. Run openrouter_models_updater.py first.") | |
| return result | |
| async 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, | |
| **kwargs | |
| ) -> str: | |
| """Возвращает model_id (строку) для роли.""" | |
| await self._ensure_initialized() | |
| logger = self._get_logger() | |
| if override_model_id: | |
| return override_model_id | |
| binding_key = f"{role_key}:{task_id}" if task_id else role_key | |
| if hasattr(self, "_bindings") and binding_key in self._bindings: | |
| return self._bindings[binding_key] | |
| if task_id: | |
| role_state = self.roles_state.get(role_key, {}) | |
| binding = role_state.get(task_id) | |
| if binding and binding.get("status") == "active": | |
| model_id = binding["primary"] | |
| if not hasattr(self, "_bindings"): self._bindings = {} | |
| self._bindings[binding_key] = model_id | |
| return model_id | |
| pool_raw = self._get_available_models() | |
| pool = [] | |
| for m in pool_raw: | |
| m_key = m if isinstance(m, str) else m.get("key") | |
| if exclude and m_key in exclude: | |
| continue | |
| pool.append(m) | |
| if not pool: | |
| if exclude: | |
| logger.warning(f"[BINDING] Failover ineffective for '{role_key}' after excluding {exclude}. Falling back.") | |
| pool = pool_raw | |
| if not pool: | |
| raise RuntimeError(f"No available models for role '{role_key}'") | |
| seed_str = role_key + (task_id or "") | |
| if exclude: | |
| seed_str += "".join(exclude) | |
| seed = int(hashlib.md5(seed_str.encode('utf-8')).hexdigest(), 16) | |
| index = seed % len(pool) | |
| selected = pool[index] | |
| model_id = selected["key"] if isinstance(selected, dict) else selected | |
| if not hasattr(self, "_bindings"): self._bindings = {} | |
| self._bindings[binding_key] = model_id | |
| if not exclude: | |
| if 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() | |
| logger.info(f"[BINDING] Cache MISS: {role_key}:{task_id} -> {model_id}") | |
| else: | |
| logger.info(f"[BINDING] Memory MISS: {role_key} -> {model_id}") | |
| else: | |
| logger.info(f"[BINDING] Failover for {role_key}: {model_id}") | |
| return model_id | |
| async def get_prompt(self, role_key: str) -> str: | |
| 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._get_state_lock(): | |
| if "defaults" not in self.roles_state: | |
| self.roles_state["defaults"] = {} | |
| self.roles_state["defaults"][role_key] = new_model_id | |
| self._save_state() | |
| self._get_logger().info(f"Switch binding for {role_key} to {new_model_id}. Reason: {reason}") | |
| return True | |
| async def get_state(self) -> Dict: | |
| await self._ensure_initialized() | |
| return self.roles_state | |
| async def get_fixed_model(self, role_key: str) -> str: | |
| await self._ensure_initialized() | |
| with self._get_state_lock(): | |
| default_model = self.roles_state.get("defaults", {}).get(role_key) | |
| if default_model: | |
| return default_model | |
| pool = 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") | |
| raise RuntimeError(f"No available models in pool for role '{role_key}'") | |
| 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 selected | |
| return model_id | |
| async def is_department_available(self, dept: str) -> bool: | |
| await self._ensure_initialized() | |
| lock = self._dept_locks.get(dept) | |
| if not lock: return True | |
| return lock["state"] == DEPT_STATE_IDLE | |
| async def lock_department(self, dept: str, state: str, locked_by: str = "system") -> bool: | |
| await self._ensure_initialized() | |
| if not await self.is_department_available(dept): return False | |
| self._dept_locks[dept] = { | |
| "state": state, | |
| "locked_by": locked_by, | |
| "expires": datetime.now() + timedelta(seconds=LOCK_TTL_SECONDS) if LOCK_TTL_SECONDS else None | |
| } | |
| return True | |
| async def unlock_department(self, dept: str): | |
| await self._ensure_initialized() | |
| 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: | |
| await self._ensure_initialized() | |
| 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: | |
| return {"error": f"No roles for department {dept}"} | |
| return await self._run_cycle(dept, roles, request_data, caller) | |
| finally: | |
| self.unlock_department(dept) | |
| async def _run_cycle(self, dept: str, roles: List[str], request_data: Dict, caller: str) -> Any: | |
| # LAZY IMPORTS | |
| from core.model_management import ModelManager | |
| message = request_data.get("message") or "" | |
| session_id = request_data.get("session_id", "default") | |
| is_formal = "[TASK]" in message | |
| current_result = message | |
| last_json = None | |
| mm = ModelManager() | |
| for 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 message | |
| if i > 0: | |
| user_prompt = f"Улучши результат коллеги:\n\n{current_result}" | |
| raw_response = await model.generate(user_prompt, system_prompt=system_prompt) | |
| current_result = raw_response | |
| if is_formal: | |
| try: | |
| start = raw_response.find('{') | |
| end = raw_response.rfind('}') | |
| if start != -1 and end != -1: | |
| last_json = json.loads(raw_response[start:end+1]) | |
| except: | |
| pass | |
| return last_json if (is_formal and last_json) else current_result | |