File size: 9,118 Bytes
9be2851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""

Session and memory management for Grocify Chat

Handles conversation history, user profiles, and session persistence

"""
import json
import logging
from typing import Dict, List, Optional, Any
from datetime import datetime, timedelta
from collections import defaultdict
import asyncio

from schemas import ConversationTurn, SessionMemory
from config import settings

logger = logging.getLogger(__name__)


class MemoryStore:
    """Base class for memory storage backends"""
    
    async def get_session(self, session_id: str) -> Optional[SessionMemory]:
        raise NotImplementedError
    
    async def save_session(self, session: SessionMemory) -> bool:
        raise NotImplementedError
    
    async def delete_session(self, session_id: str) -> bool:
        raise NotImplementedError
    
    async def list_user_sessions(self, user_id: str) -> List[str]:
        raise NotImplementedError


class InMemoryStore(MemoryStore):
    """In-memory session store (for development/testing)"""
    
    def __init__(self):
        self._store: Dict[str, SessionMemory] = {}
        self._user_sessions: Dict[str, List[str]] = defaultdict(list)
        self._lock = asyncio.Lock()
    
    async def get_session(self, session_id: str) -> Optional[SessionMemory]:
        """Retrieve session by ID"""
        async with self._lock:
            session = self._store.get(session_id)
            if session:
                # Check if session expired
                created = datetime.fromisoformat(session.created_at)
                if datetime.now() - created > timedelta(minutes=settings.SESSION_TIMEOUT_MINUTES):
                    await self.delete_session(session_id)
                    return None
            return session
    
    async def save_session(self, session: SessionMemory) -> bool:
        """Save or update session"""
        async with self._lock:
            session.updated_at = datetime.now().isoformat()
            self._store[session.session_id] = session
            
            if session.user_id and session.session_id not in self._user_sessions[session.user_id]:
                self._user_sessions[session.user_id].append(session.session_id)
            
            return True
    
    async def delete_session(self, session_id: str) -> bool:
        """Delete session"""
        async with self._lock:
            if session_id in self._store:
                session = self._store[session_id]
                if session.user_id:
                    if session_id in self._user_sessions[session.user_id]:
                        self._user_sessions[session.user_id].remove(session_id)
                del self._store[session_id]
                return True
            return False
    
    async def list_user_sessions(self, user_id: str) -> List[str]:
        """List all sessions for a user"""
        return self._user_sessions.get(user_id, [])


class RedisStore(MemoryStore):
    """Redis-based session store (for production)"""
    
    def __init__(self, redis_url: str):
        self.redis_url = redis_url
        self._redis = None
        # TODO: Initialize Redis connection
        # import redis.asyncio as redis
        # self._redis = redis.from_url(redis_url)
    
    async def get_session(self, session_id: str) -> Optional[SessionMemory]:
        """Retrieve session from Redis"""
        # TODO: Implement Redis retrieval
        raise NotImplementedError("Redis store not yet implemented")
    
    async def save_session(self, session: SessionMemory) -> bool:
        """Save session to Redis"""
        # TODO: Implement Redis save with expiry
        raise NotImplementedError("Redis store not yet implemented")
    
    async def delete_session(self, session_id: str) -> bool:
        """Delete session from Redis"""
        # TODO: Implement Redis delete
        raise NotImplementedError("Redis store not yet implemented")
    
    async def list_user_sessions(self, user_id: str) -> List[str]:
        """List user sessions from Redis"""
        # TODO: Implement Redis scan
        raise NotImplementedError("Redis store not yet implemented")


class SessionManager:
    """Manages conversation sessions and memory"""
    
    def __init__(self, store: Optional[MemoryStore] = None):
        if store is None:
            if settings.REDIS_URL:
                logger.info("Using Redis store for session management")
                self.store = RedisStore(settings.REDIS_URL)
            else:
                logger.info("Using in-memory store for session management")
                self.store = InMemoryStore()
        else:
            self.store = store
    
    async def get_or_create_session(self, session_id: str, user_id: Optional[str] = None) -> SessionMemory:
        """Get existing session or create new one"""
        session = await self.store.get_session(session_id)
        
        if session is None:
            session = SessionMemory(
                session_id=session_id,
                user_id=user_id,
                conversation=[],
                memory_summary=None,
                user_profile={},
                escalation_count=0,
                failed_attempts=0
            )
            await self.store.save_session(session)
            logger.info(f"Created new session: {session_id}")
        
        return session
    
    async def add_message(self, session_id: str, role: str, content: str, metadata: Optional[Dict] = None):
        """Add a message to conversation history"""
        session = await self.store.get_session(session_id)
        if not session:
            logger.warning(f"Session {session_id} not found, cannot add message")
            return
        
        turn = ConversationTurn(
            role=role,
            content=content,
            metadata=metadata or {}
        )
        
        session.conversation.append(turn)
        
        # Trim conversation to window size
        if len(session.conversation) > settings.MEMORY_WINDOW_SIZE * 2:
            session.conversation = session.conversation[-settings.MEMORY_WINDOW_SIZE * 2:]
        
        await self.store.save_session(session)
    
    async def get_conversation_history(self, session_id: str, limit: Optional[int] = None) -> List[Dict[str, str]]:
        """Get conversation history for session"""
        session = await self.store.get_session(session_id)
        if not session:
            return []
        
        history = session.conversation
        if limit:
            history = history[-limit:]
        
        return [
            {"role": turn.role, "content": turn.content}
            for turn in history
        ]
    
    async def update_memory_summary(self, session_id: str, summary: str):
        """Update memory summary for session"""
        session = await self.store.get_session(session_id)
        if session:
            session.memory_summary = summary
            await self.store.save_session(session)
    
    async def increment_failed_attempts(self, session_id: str) -> int:
        """Increment failed attempt counter"""
        session = await self.store.get_session(session_id)
        if session:
            session.failed_attempts += 1
            await self.store.save_session(session)
            return session.failed_attempts
        return 0
    
    async def reset_failed_attempts(self, session_id: str):
        """Reset failed attempt counter"""
        session = await self.store.get_session(session_id)
        if session:
            session.failed_attempts = 0
            await self.store.save_session(session)
    
    async def increment_escalation_count(self, session_id: str) -> int:
        """Increment escalation counter"""
        session = await self.store.get_session(session_id)
        if session:
            session.escalation_count += 1
            await self.store.save_session(session)
            return session.escalation_count
        return 0
    
    async def update_user_profile(self, session_id: str, profile_data: Dict[str, Any]):
        """Update user profile information"""
        session = await self.store.get_session(session_id)
        if session:
            session.user_profile.update(profile_data)
            await self.store.save_session(session)
    
    async def delete_session(self, session_id: str) -> bool:
        """Delete a session"""
        return await self.store.delete_session(session_id)
    
    async def get_user_sessions(self, user_id: str) -> List[SessionMemory]:
        """Get all sessions for a user"""
        session_ids = await self.store.list_user_sessions(user_id)
        sessions = []
        for sid in session_ids:
            session = await self.store.get_session(sid)
            if session:
                sessions.append(session)
        return sessions


# Global session manager instance
session_manager = SessionManager()