File size: 8,338 Bytes
d7dfeff
 
5306da4
d7dfeff
 
 
 
 
 
 
5306da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7dfeff
 
5306da4
 
 
 
 
 
 
d7dfeff
 
5306da4
 
 
 
 
 
 
 
 
 
 
d7dfeff
 
5306da4
d7dfeff
 
 
 
5306da4
 
d7dfeff
5306da4
d7dfeff
 
 
 
5306da4
 
d7dfeff
 
 
 
 
 
 
5306da4
d7dfeff
 
 
 
5306da4
 
d7dfeff
 
5306da4
 
 
 
 
 
 
 
 
d7dfeff
5306da4
 
 
 
 
 
 
 
 
 
 
d7dfeff
 
 
5306da4
d7dfeff
 
5306da4
 
d7dfeff
5306da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import pickle
import os
from datetime import datetime, timezone

FILE_PATH = "chat_history.pkl"

if not os.path.exists(FILE_PATH):
    with open(FILE_PATH, "wb") as file:
        pickle.dump({}, file)


async def save_context_detail(session_id, name, title, summary, categories):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        now = datetime.now(timezone.utc).isoformat()

        if session_id not in data:
            print("Session id not in data")
            data[session_id] = {
                "title": "New Chat",
                "createdAt": now,
                "lastUpdatedAt": now,
                "chat": [],
                "context": [],
                "prompt": "",
            }

        session = data.get(session_id)
        contexts = session.get("context", [])

        contexts.append({"name": name, "title": title,
                        "summary": summary, "categories": categories})

        data[session_id]["lastUpdatedAt"] = now

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

    except Exception as e:
        print(f"Error saving context entry: {e}")


def clear_context_detail(session_id):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        now = datetime.now(timezone.utc).isoformat()

        if session_id not in data:
            print("Session id not in data")
            return False

        data[session_id]["context"] = []

        data[session_id]["lastUpdatedAt"] = now

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

    except Exception as e:
        print(f"Error saving context entry: {e}")


def save_chat_entry(session_id, role, transcript):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        now = datetime.now(timezone.utc).isoformat()

        if session_id not in data:
            print("Session id not in data")
            data[session_id] = {
                "title": "New Chat",
                "createdAt": now,
                "lastUpdatedAt": now,
                "chat": [],
                "context": [],
                "prompt": "",
            }

        messages = data[session_id]["chat"]

        if role == "user":
            messages.append({
                "role": role,
                "transcript": transcript
            })
        else:
            if messages and messages[-1]["role"] == "assistant":
                messages[-1]["transcript"] += " " + transcript
            else:
                messages.append({
                    "role": role,
                    "transcript": transcript
                })

        data[session_id]["lastUpdatedAt"] = now

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

    except Exception as e:
        print(f"Error saving chat entry: {e}")


def get_chat_history(session_id, limit=15):
    try:
        with open(FILE_PATH, "rb") as file:
            data = pickle.load(file)

        session = data.get(session_id)
        if not session or not isinstance(session, dict):
            return []

        # or "messages" if you’ve standardized on that
        # messages = session.get("chat", [])

        # message_history = []
        # for entry in messages:
        #     role = entry.get('role', '')
        #     transcript = entry.get('transcript', '')
        #     if role and transcript:
        #         message_history.append({"role": role, "content": transcript})

        # return message_history[-15:]

        tail = session.get("chat", [])[-limit:]
        chat_history = [
            {"role": msg["role"], "content": msg["transcript"]}
            for msg in tail
            if msg.get("role") and msg.get("transcript")
        ]

        user_prompt = session.get("prompt", "")
        return chat_history, user_prompt

    except (FileNotFoundError, pickle.UnpicklingError) as e:
        print(f"Error reading or parsing the file: {e}")
        return []
    except Exception as e:
        print(f"Unexpected error: {e}")
        return []


def get_all_chat_details():
    try:
        with open(FILE_PATH, "rb") as file:
            data = pickle.load(file)

        chat_list = []

        for session_id, chat in data.items():
            if not isinstance(chat, dict):
                continue

            messages = []
            for entry in chat.get("chat", []):
                role = entry.get("role", "")
                transcript = entry.get("transcript", "")
                if role and transcript:
                    messages.append({
                        "role": role,
                        "content": transcript
                    })

            chat_list.append({
                "id": session_id,
                "title": chat.get("title", "Untitled"),
                "createdAt": chat.get("createdAt"),
                "lastUpdatedAt": chat.get("lastUpdatedAt"),
                "chat": messages,
                "context": chat.get("context", []),
                "prompt": chat.get("prompt", ""),
            })

        return chat_list

    except (FileNotFoundError, EOFError):
        return []

    except Exception as e:
        print(f"Error reading chats: {e}")
        return []


def create_chat_entry(session_id):
    try:
        # Load existing data or initialize an empty dict
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        now = datetime.now(timezone.utc).isoformat()

        if session_id not in data:
            data[session_id] = {
                "title": "New Chat",
                "createdAt": now,
                "lastUpdatedAt": now,
                "chat": [],
                "context": [],
            }

            # Save the updated data back to file
            with open(FILE_PATH, "wb") as file:
                pickle.dump(data, file)

        return True

    except Exception as e:
        print(f"Error create chat entry : {e}")
        return False


def rename_chat_title(session_id, title):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        if session_id not in data:
            return False

        data[session_id]["title"] = title
        data[session_id]["lastUpdatedAt"] = datetime.now(
            timezone.utc).isoformat()

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

        print(f"Renamed chat: {data[session_id]}")
        return True

    except Exception as e:
        print(f"Error renaming chat title: {e}")
        return False


def save_system_prompt(session_id, prompt):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        now = datetime.now(timezone.utc).isoformat()

        if session_id not in data:
            return False

        data[session_id]["prompt"] = prompt
        data[session_id]["lastUpdatedAt"] = now

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

        print(f"Saved Prompt : {data[session_id]}")
        return True

    except Exception as e:
        print(f"Error saving context entry: {e}")
        return False


def delete_chat(session_id):
    try:
        try:
            with open(FILE_PATH, "rb") as file:
                data = pickle.load(file)
        except (FileNotFoundError, EOFError):
            data = {}

        if session_id not in data:
            return True

        data.pop(session_id)

        with open(FILE_PATH, "wb") as file:
            pickle.dump(data, file)

        if session_id not in data:
            return True

        return False

    except Exception as e:
        print(f"Error deleting chat: {e}")
        return False