A.Tuin commited on
Commit ·
91b0cb8
1
Parent(s): a5c876b
end tests
Browse filesFiles changed (4)
5 unmodified lines678995 unmodified linesREM Запуск MCP Сервера для Консоли Gemini с использованием venv_cudaSTART "Gemini MCP Server CUDA" /MIN .\venv_cuda\Scripts\python.exe gemini_mcp_server.pyREM Запуск основного веб-интерфейса с использованием venv_cuda.\venv_cuda\Scripts\python.exe -m uvicorn app:app --host 127.0.0.1 --port 5000.\venv_cuda\Scripts\python.exe -m uvicorn app2:app --host 127.0.0.1 --port 5000227 unmodified lines228229230231232233234235227 unmodified lines async def startup(): await ensure_project_dirs() ensure_project_model_pool() # Diagnostic app.logger.info(f"STARTUP DIAG: role_mgr={hasattr(app, 'role_binding_manager')}, model_mgr={hasattr(app, 'model_manager')}") # app.add_background_task(update_models) # app.logger.info("🚀 Updater моделей (интегрированный) запущен в фоне") app.project_context = None3 unmodified lines4567891011121314151617181920212223242526272829301 unmodified line323334143536373844 unmodified lines8384856586878889909192937273747594959697989910010110210310481828384105106107108109110111112113114115116117118119120121929394122123124125126127991001011281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671683 unmodified linesimport loggingimport asyncioimport timefrom enum import Enum
class DoctorState(Enum): INIT = "INIT" READY = "READY" PROCESSING = "PROCESSING" ERROR = "ERROR"
async def send_protocol_message(ws, msg_type: str, payload: dict, state: DoctorState): """ Unified protocol layer for Doctor WebSocket. Invariant: All outgoing messages MUST pass through this function. """ message = { "type": msg_type, "source": "doctor", "state": state.value, "payload": payload, "timestamp": datetime.now().isoformat() } await ws.send_json(message)
# ZERO EXECUTION: импорты core перенесены внутрь обработчика или методов# чтобы избежать гонки при старте.1 unmodified linelogger = logging.getLogger(__name__)
START_TIME = time.time()INIT_TIMEOUT = 10INIT_TIMEOUT = 30
def _is_system_ready(app): """Проверяет готовность менеджеров в объекте app."""44 unmodified lines # он использует глобальный объект websocket из quart. from quart import websocket as ws logger.info("[DOCTOR_WS] Connection attempt...") current_state = DoctorState.INIT logger.info(f"[DOCTOR_WS] Connection attempt. State: {current_state.value}") # Guard: System Ready status = _is_system_ready(app) if status is False: await ws.accept() await ws.send_json({ "type": "system", "text": "⚠️ Система ещё инициализируется. Повторите через 2-3 секунды." }) await send_protocol_message( ws, "system", {"text": "⚠️ Система ещё инициализируется. Повторите через 2-3 секунды."}, current_state ) await ws.close(code=1013) return
if status == "FAILED": current_state = DoctorState.ERROR await ws.accept() await ws.send_json({ "type": "error", "text": "❌ System failed to initialize" }) await send_protocol_message( ws, "error", {"text": "❌ System failed to initialize"}, current_state ) await ws.close(code=1013) return
await ws.accept() # Переход: INIT -> READY old_state = current_state current_state = DoctorState.READY logger.info(f"[STATE] {old_state.value} → {current_state.value}") logger.info("[DOCTOR_WS] Connection accepted.") session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" # chat_file = Path("AIColab/chats/doctor") / f"{session_id}.json" # Пока не используем для минимизации engine = await DoctorEngine.get_instance(app) try: engine = await DoctorEngine.get_instance(app) while True: data = await ws.receive_json() user_message = data.get("message", "") response = await engine.process(user_message) await ws.send_json(response) # Обработка legacy формата if not isinstance(data, dict): logger.warning(f"[DOCTOR_WS] Deprecated format received: {data}") user_message = str(data) else: user_message = data.get("message", "")
# Переход: READY -> PROCESSING old_state = current_state current_state = DoctorState.PROCESSING logger.info(f"[STATE] {old_state.value} → {current_state.value}")
try: response = await engine.process(user_message) await send_protocol_message(ws, "message", response, current_state) # Переход: PROCESSING -> READY old_state = current_state current_state = DoctorState.READY logger.info(f"[STATE] {old_state.value} → {current_state.value}") except Exception as proc_e: logger.error(f"[DOCTOR_WS] Processing error: {proc_e}") current_state = DoctorState.ERROR await send_protocol_message( ws, "error", {"text": f"Error during processing: {str(proc_e)}"}, current_state ) # Попытка восстановления: ERROR -> READY current_state = DoctorState.READY logger.info(f"[STATE] ERROR → {current_state.value} (Recovery)")
except Exception as e: logger.error(f"[DOCTOR_WS] Connection error: {e}") current_state = DoctorState.ERROR finally: logger.info(f"[DOCTOR_WS] Closing connection. Final state: {current_state.value}") try: await ws.close() except:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from pathlib import Pathfrom datetime import datetimeimport jsonimport loggingimport asyncioimport time
# ZERO EXECUTION: импорты core перенесены внутрь обработчика или методов# чтобы избежать гонки при старте.
logger = logging.getLogger(__name__)
START_TIME = time.time()INIT_TIMEOUT = 10
def _is_system_ready(app): """Проверяет готовность менеджеров в объекте app.""" if time.time() - START_TIME > INIT_TIMEOUT: return "FAILED"
# Проверяем наличие проинициализированных менеджеров в app if not ( hasattr(app, "role_binding_manager") and app.role_binding_manager is not None and hasattr(app, "model_manager") and app.model_manager is not None ): return False
return True
class DoctorEngine: _instance = None
def __init__(self, role_manager, model_manager): self.role_manager = role_manager self.model_manager = model_manager
@classmethod async def get_instance(cls, app): """Lazy singleton creation with dependency injection from app.""" if cls._instance is None: # В этот момент мы уверены, что менеджеры в app есть (проверено в _is_system_ready) cls._instance = cls(app.role_binding_manager, app.model_manager) return cls._instance
async def process(self, message: str): # Реализация процесса (заглушка для совместимости со SPEC) msg = (message or "").strip().lower() if msg == "ping": return {"response": "pong"} return {"error": f"Command '{msg}' not recognized by DoctorEngine"}
def register_doctor_ws(app): """ Synchronous registration of the Doctor WebSocket endpoint. Includes duplicate registration guard. """ if getattr(app, "_doctor_ws_registered", False): return
@app.websocket("/ws/doctor") async def doctor_ws(): # Важно: Quart WebSocket хендлер не принимает аргумент websocket, # он использует глобальный объект websocket из quart. from quart import websocket as ws logger.info("[DOCTOR_WS] Connection attempt...") # Guard: System Ready status = _is_system_ready(app) if status is False: await ws.accept() await ws.send_json({ "type": "system", "text": "⚠️ Система ещё инициализируется. Повторите через 2-3 секунды." }) await ws.close(code=1013) return
if status == "FAILED": await ws.accept() await ws.send_json({ "type": "error", "text": "❌ System failed to initialize" }) await ws.close(code=1013) return
await ws.accept() logger.info("[DOCTOR_WS] Connection accepted.") session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" # chat_file = Path("AIColab/chats/doctor") / f"{session_id}.json" # Пока не используем для минимизации engine = await DoctorEngine.get_instance(app) try: while True: data = await ws.receive_json() user_message = data.get("message", "") response = await engine.process(user_message) await ws.send_json(response) except Exception as e: logger.error(f"[DOCTOR_WS] Connection error: {e}") finally: try: await ws.close() except: pass
app._doctor_ws_registered = True logger.info("[WS] /ws/doctor registered")AIColab_cuda.bat+1-1
app2.py+2
doctor_ws_module.py+77-16
doctor_ws_module.py.bak.20260409_state_machineAdded+111