File size: 2,006 Bytes
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 []