Download core/session_memory.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/session_memory.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/core/session_memory.py
-
curl -L -o session_memory.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/core/session_memory.py
6.08 kB
| import json | |
| import os | |
| import time | |
| from pathlib import Path | |
| from typing import List, Dict, Any, Optional | |
| import aiofiles | |
| import portalocker | |
| class SessionMemory: | |
| def __init__(self, base_dir: str = "D:\\Gemini\\AIColab\\sessions"): | |
| self.base_dir = Path(base_dir) | |
| self.base_dir.mkdir(parents=True, exist_ok=True) | |
| def _get_session_path(self, session_id: str) -> Path: | |
| return self.base_dir / session_id | |
| async def init_session(self, session_id: str, task_description: str, metadata: Dict[str, Any] = None): | |
| """Инициализация структуры директорий сессии.""" | |
| session_path = self._get_session_path(session_id) | |
| dirs = ["pairs", "briefings", "chairman", "soul_layer", ".index"] | |
| for d in dirs: | |
| (session_path / d).mkdir(parents=True, exist_ok=True) | |
| # Сохранение ТЗ | |
| async with aiofiles.open(session_path / "task.md", mode="w", encoding="utf-8") as f: | |
| await f.write(task_description) | |
| # Сохранение метаданных | |
| meta = { | |
| "id": session_id, | |
| "timestamp": time.time(), | |
| "status": "active", | |
| "project_name": metadata.get("project_name", "Untitled Project") if metadata else "Untitled Project" | |
| } | |
| await self._save_json(session_path / "metadata.json", meta) | |
| # Инициализация лога для совместимости со старым кодом | |
| await self._save_json(session_path / "log.json", {"id": session_id, "messages": []}) | |
| async def save_pair_turn(self, session_id: str, pair_id: str, turn_data: Dict[str, Any]): | |
| """Сохранение хода парного диалога.""" | |
| session_path = self._get_session_path(session_id) | |
| pair_file = session_path / "pairs" / f"{pair_id}.jsonl" | |
| async with aiofiles.open(pair_file, mode="a", encoding="utf-8") as f: | |
| # Используем portalocker для защиты от одновременной записи | |
| # portalocker.lock(f, portalocker.LOCK_EX) # portalocker работает с файловыми объектами, а не с aiofiles напрямую | |
| # Для простоты в асинхронной среде пока без блокировки или через обычный open | |
| line = json.dumps({**turn_data, "timestamp": time.time()}, ensure_ascii=False) + "\n" | |
| await f.write(line) | |
| async def load_pair_history(self, session_id: str, pair_id: str) -> List[Dict[str, Any]]: | |
| """Загрузка истории пары.""" | |
| session_path = self._get_session_path(session_id) | |
| pair_file = session_path / "pairs" / f"{pair_id}.jsonl" | |
| if not pair_file.exists(): | |
| return [] | |
| history = [] | |
| async with aiofiles.open(pair_file, mode="r", encoding="utf-8") as f: | |
| async for line in f: | |
| if line.strip(): | |
| history.append(json.loads(line)) | |
| return history | |
| async def save_briefing(self, session_id: str, content: str, participants: List[str]): | |
| """Сохранение результатов оперативки.""" | |
| session_path = self._get_session_path(session_id) | |
| briefing_id = f"briefing_{int(time.time())}" | |
| briefing_data = { | |
| "timestamp": time.time(), | |
| "participants": participants, | |
| "content": content | |
| } | |
| await self._save_json(session_path / "briefings" / f"{briefing_id}.json", briefing_data) | |
| async def save_chairman_synthesis(self, session_id: str, synthesis: str, metadata: Dict[str, Any]): | |
| """Сохранение финального синтеза.""" | |
| session_path = self._get_session_path(session_id) | |
| synthesis_data = { | |
| "timestamp": time.time(), | |
| "content": synthesis, | |
| "metadata": metadata | |
| } | |
| await self._save_json(session_path / "chairman" / "synthesis_final.json", synthesis_data) | |
| async def save_soul_analysis(self, session_id: str, pair_id: str, analysis: Dict[str, Any]): | |
| """Сохранение результатов метаанализа Soul Layer.""" | |
| session_path = self._get_session_path(session_id) | |
| analysis_data = { | |
| "timestamp": time.time(), | |
| "pair_id": pair_id, | |
| "analysis": analysis | |
| } | |
| await self._save_json(session_path / "soul_layer" / f"quality_{pair_id}.json", analysis_data) | |
| async def get_session_context(self, session_id: str, max_tokens: int = 4000) -> Dict[str, Any]: | |
| """Сборка компактного контекста сессии.""" | |
| session_path = self._get_session_path(session_id) | |
| context = { | |
| "task": "", | |
| "latest_pairs": {}, | |
| "latest_briefing": "" | |
| } | |
| if (session_path / "task.md").exists(): | |
| async with aiofiles.open(session_path / "task.md", mode="r", encoding="utf-8") as f: | |
| context["task"] = await f.read() | |
| # Берем последний ход из каждой пары | |
| pairs_dir = session_path / "pairs" | |
| if pairs_dir.exists(): | |
| for pf in pairs_dir.glob("*.jsonl"): | |
| history = await self.load_pair_history(session_id, pf.stem) | |
| if history: | |
| context["latest_pairs"][pf.stem] = history[-1]["content"][:500] # Ограничение | |
| return context | |
| async def _save_json(self, path: Path, data: Dict[str, Any]): | |
| async with aiofiles.open(path, mode="w", encoding="utf-8") as f: | |
| await f.write(json.dumps(data, indent=2, ensure_ascii=False)) | |
| async def _load_json(self, path: Path) -> Dict[str, Any]: | |
| if not path.exists(): | |
| return {} | |
| async with aiofiles.open(path, mode="r", encoding="utf-8") as f: | |
| return json.loads(await f.read()) | |