File size: 8,232 Bytes
d810052
f202266
d810052
f202266
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
d810052
 
 
 
 
f202266
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
d810052
 
 
 
 
f202266
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
f202266
d810052
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
d810052
 
 
 
ccbdc68
f202266
d810052
f202266
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
f202266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccbdc68
f202266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccbdc68
f202266
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException, Request, Cookie
from typing import Dict, Optional
from services.api.db.token_utils import decode_token
from services.api.chatbot.core import get_chat_response, get_chat_response_lecture, clear_chat_history, clear_lecture_chat_history
from services.utils.chat_cache import get_chat_history, append_chat_message, clear_user_chat_history
from pydantic import BaseModel

router = APIRouter()

class ChatMessage(BaseModel):
    message: str

@router.post("/chat")
async def chat_endpoint(message: ChatMessage, request: Request, auth_token: str = Cookie(None)):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            username = user_data.get('username')  # Get username from token
            if not username:
                raise HTTPException(status_code=401, detail="Invalid token: missing username")
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Get chatbot response
        chat_history = get_chat_history(username)
        append_chat_message(username, message.message, is_user=True)
        
        response = get_chat_response(username, message.message)
        append_chat_message(username, response, is_user=False)
        
        return {"answer": response, "history": get_chat_history(username)}

    except Exception as e:
        print(f"Chat error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/chat/lecture/{lecture_id}")
async def lecture_chat_endpoint(
    lecture_id: int, 
    message: ChatMessage, 
    request: Request, 
    auth_token: str = Cookie(None)
):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            username = user_data.get('username')  # Get username from token
            if not username:
                raise HTTPException(status_code=401, detail="Invalid token: missing username")
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Get chatbot response for specific lecture
        chat_history = get_chat_history(username)
        append_chat_message(username, message.message, is_user=True)
        
        response = get_chat_response_lecture(username, message.message, lecture_id)
        append_chat_message(username, response, is_user=False)
        
        return {"answer": response, "history": get_chat_history(username)}

    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Lecture chat error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/chat/history")
async def clear_history_endpoint(request: Request, auth_token: str = Cookie(None), lectureId: Optional[int] = None):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            username = user_data.get('username')  # Get username from token
            if not username:
                raise HTTPException(status_code=401, detail="Invalid token: missing username")
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Clear Valkey cache
        clear_user_chat_history(username)
        
        # Clear memory-based chat histories based on lectureId
        if lectureId is not None:
            # Only clear the specific lecture chat
            clear_lecture_chat_history(username, lectureId)
        else:
            # Clear both regular and all lecture chat histories for this user
            clear_chat_history(username)
            clear_lecture_chat_history(username)
        
        # Return empty history for frontend to use
        return {"status": "success", "message": "Chat history cleared", "history": []}

    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Clear history error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/chat/history/{lecture_id}")
async def get_history_endpoint(
    lecture_id: int,
    request: Request, 
    auth_token: str = Cookie(None)
):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            username = user_data.get('username')  # Get username from token
            if not username:
                raise HTTPException(status_code=401, detail="Invalid token: missing username")
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Get chat history from Valkey
        chat_history = get_chat_history(username)
        
        # Return the chat history - make sure formatting is consistent
        return {"history": chat_history, "message": "History retrieved successfully"}

    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Get history error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/chat/history")
async def get_general_history_endpoint(
    request: Request, 
    auth_token: str = Cookie(None)
):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            username = user_data.get('username')  # Get username from token
            if not username:
                raise HTTPException(status_code=401, detail="Invalid token: missing username")
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Get chat history from Valkey
        chat_history = get_chat_history(username)
        
        # Return the chat history with a debugging message
        print(f"Returning chat history for {username}: {len(chat_history)} messages")
        return {"history": chat_history, "message": "History retrieved successfully"}

    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Get history error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))