import os from pathlib import Path from typing import List, Dict import logging logger = logging.getLogger(__name__) def get_recent_history(role_key: str, limit: int = 10) -> List[Dict[str, str]]: """ Читает последние limit сообщений из лога subjects/{role_key}.log и возвращает в формате списка словарей для OpenRouter API. Формат лога: "User: ...\nAI: ...\n\n" """ from core.project_context import ProjectContext ctx = ProjectContext.get_instance() project_path_str = ctx.get_current_project_path() if not project_path_str: logger.warning("Project path is not set, cannot retrieve chat history.") return [] log_path = Path(project_path_str) / "logs" / "subjects" / f"{role_key}.log" if not log_path.exists(): return [] try: with open(log_path, 'r', encoding='utf-8') as f: content = f.read() # Разделяем по двойным переводам строки # Формат записи: "User: {message}\nAI: {reply}\n\n" blocks = content.strip().split('\n\n') messages = [] for block in blocks[-limit:]: # берём последние limit блоков lines = block.strip().split('\n') user_msg = None ai_msg = None for line in lines: if line.startswith('User: '): user_msg = line[6:].strip() elif line.startswith('AI: '): ai_msg = line[4:].strip() if user_msg: messages.append({"role": "user", "content": user_msg}) if ai_msg: messages.append({"role": "assistant", "content": ai_msg}) return messages except Exception as e: logger.error(f"Ошибка при чтении лога истории {role_key}: {e}") return []