prashantmatlani commited on
Commit
2fe5352
·
1 Parent(s): 337ae5c

updated - memory_store, persistent memory in api_server, app.js

Browse files
Files changed (3) hide show
  1. api_server.py +7 -9
  2. core/memory_store.py +25 -22
  3. web/app.js +25 -21
api_server.py CHANGED
@@ -206,9 +206,9 @@ def chat(req: ChatRequest, background_tasks: BackgroundTasks):
206
  # -----------------------------
207
  output = handle_turn(state, message)
208
 
209
- # -----------------------------------
210
- # SAVE AFTER EVERY TURN (PERSISTENCE)
211
- # -----------------------------------
212
  save_state(session_id, state)
213
 
214
  # -----------------------------
@@ -239,15 +239,13 @@ def chat(req: ChatRequest, background_tasks: BackgroundTasks):
239
  # ---- GET SESSION DATA, PAST CONVERSATION ----
240
  @app.get("/session/{session_id}")
241
  def get_session(session_id: str):
242
- state = load_state(session_id)
243
 
244
- if not state:
 
 
245
  return {"error": "Session not found"}
246
 
247
- return {
248
- "history": state.history,
249
- "agent_histories": state.agent_histories
250
- }
251
 
252
 
253
 
 
206
  # -----------------------------
207
  output = handle_turn(state, message)
208
 
209
+ # -----------------------------------------
210
+ # SAVE STATE AFTER EVERY TURN (PERSISTENCE)
211
+ # -----------------------------------------
212
  save_state(session_id, state)
213
 
214
  # -----------------------------
 
239
  # ---- GET SESSION DATA, PAST CONVERSATION ----
240
  @app.get("/session/{session_id}")
241
  def get_session(session_id: str):
 
242
 
243
+ data = load_state(session_id)
244
+
245
+ if not data:
246
  return {"error": "Session not found"}
247
 
248
+ return data
 
 
 
249
 
250
 
251
 
core/memory_store.py CHANGED
@@ -3,6 +3,7 @@
3
 
4
  import json
5
  import os
 
6
 
7
  MEMORY_DIR = "memory"
8
 
@@ -10,37 +11,39 @@ if not os.path.exists(MEMORY_DIR):
10
  os.makedirs(MEMORY_DIR)
11
 
12
 
 
 
 
 
 
 
 
 
 
 
13
  def save_state(session_id, state):
14
- path = f"{MEMORY_DIR}/{session_id}.json"
 
15
 
16
  data = {
 
 
 
 
17
  "history": state.history,
18
- "agent_histories": state.agent_histories,
19
- "initial_query": state.initial_query,
20
- "current_agent": state.current_agent,
21
- "stage": state.stage
22
  }
23
 
24
- with open(path, "w") as f:
25
- json.dump(data, f)
26
 
27
 
28
  def load_state(session_id):
29
- path = f"{MEMORY_DIR}/{session_id}.json"
30
 
31
- if not os.path.exists(path):
32
- return None
33
 
34
- with open(path, "r") as f:
35
- data = json.load(f)
36
-
37
- from core.conversation_manager import ConversationState
38
-
39
- state = ConversationState()
40
- state.history = data.get("history", [])
41
- state.agent_histories = data.get("agent_histories", {})
42
- state.initial_query = data.get("initial_query")
43
- state.current_agent = data.get("current_agent", "jung")
44
- state.stage = data.get("stage", "jung")
45
 
46
- return state
 
 
3
 
4
  import json
5
  import os
6
+ from datetime import datetime
7
 
8
  MEMORY_DIR = "memory"
9
 
 
11
  os.makedirs(MEMORY_DIR)
12
 
13
 
14
+ def generate_label(history):
15
+ """
16
+ Simple label generator (can upgrade later with LLM)
17
+ """
18
+ for msg in history:
19
+ if msg["role"] == "client":
20
+ return msg["content"][:40]
21
+ return "Conversation"
22
+
23
+
24
  def save_state(session_id, state):
25
+
26
+ filepath = os.path.join(MEMORY_DIR, f"{session_id}.json")
27
 
28
  data = {
29
+ "session_id": session_id,
30
+ "created_at": getattr(state, "created_at", datetime.now().isoformat()),
31
+ "last_updated": datetime.now().isoformat(),
32
+ "label": generate_label(state.history),
33
  "history": state.history,
34
+ "agents": getattr(state, "agent_logs", {})
 
 
 
35
  }
36
 
37
+ with open(filepath, "w", encoding="utf-8") as f:
38
+ json.dump(data, f, indent=2)
39
 
40
 
41
  def load_state(session_id):
 
42
 
43
+ filepath = os.path.join(MEMORY_DIR, f"{session_id}.json")
 
44
 
45
+ if not os.path.exists(filepath):
46
+ return None
 
 
 
 
 
 
 
 
 
47
 
48
+ with open(filepath, "r", encoding="utf-8") as f:
49
+ return json.load(f)
web/app.js CHANGED
@@ -135,10 +135,6 @@ function switchToConversationMode() {
135
  //function loadSession() {
136
  async function loadSession() {
137
 
138
- document.getElementById("session_display").value = input
139
- window.conversationStarted = true
140
- switchToConversationMode()
141
-
142
  const input = document.getElementById("session_input").value
143
 
144
  if (!input) return
@@ -153,19 +149,29 @@ async function loadSession() {
153
  return
154
  }
155
 
156
- // Restore chat visually
 
 
 
 
 
 
 
157
  const chatBox = document.getElementById("chat")
158
  chatBox.innerHTML = ""
159
 
 
160
  data.history.forEach(msg => {
 
161
  if (msg.role === "client") {
162
  appendMessage("user", msg.content)
163
  } else {
164
  updateThinking(msg.content, "jung")
165
  }
 
166
  })
167
 
168
- //console.log("♻️ Loading session:", input)
169
  }
170
 
171
 
@@ -431,41 +437,39 @@ function formatEpistemic(text) {
431
  .replace(/\n/g, "<br>")
432
  }
433
 
434
- // -------------------------------
435
  // END SESSION
436
- // -------------------------------
437
  async function endSession() {
438
 
439
  console.log("🛑 Ending session")
440
 
 
 
441
  await fetch(window.location.origin + "/chat", {
442
  method: "POST",
443
  headers: { "Content-Type": "application/json" },
444
  body: JSON.stringify({
445
- session_id: window.session_id,
446
  message: "end session"
447
  })
448
  })
449
 
 
 
 
 
 
450
  window.session_id = null
 
 
451
  document.getElementById("chat").innerHTML = ""
 
452
  }
453
 
454
  // ---------------------------------------------------------
455
  // ENTER(SEND ACTION) & SHIFT+ENTER(INSERT NEW LINE) CONTROL
456
  // ---------------------------------------------------------
457
- //document.getElementById("main_input").addEventListener("keydown", function (e) {
458
- // if (e.key === "Enter" && !e.shiftKey) {
459
- // e.preventDefault()
460
-
461
- // if (window.conversationStarted) {
462
- // fuel()
463
- // } else {
464
- // fire()
465
- // }
466
- // }
467
- //})
468
-
469
  window.addEventListener("DOMContentLoaded", () => {
470
  const input = document.getElementById("main_input")
471
 
 
135
  //function loadSession() {
136
  async function loadSession() {
137
 
 
 
 
 
138
  const input = document.getElementById("session_input").value
139
 
140
  if (!input) return
 
149
  return
150
  }
151
 
152
+ // Set session display
153
+ document.getElementById("session_display").value = input
154
+
155
+ // Switch UI mode
156
+ window.conversationStarted = true
157
+ switchToConversationMode()
158
+
159
+ // Clear chat - Restore chat visually
160
  const chatBox = document.getElementById("chat")
161
  chatBox.innerHTML = ""
162
 
163
+ // Restore messages
164
  data.history.forEach(msg => {
165
+
166
  if (msg.role === "client") {
167
  appendMessage("user", msg.content)
168
  } else {
169
  updateThinking(msg.content, "jung")
170
  }
171
+
172
  })
173
 
174
+ console.log("♻️ Session loaded:", input)
175
  }
176
 
177
 
 
437
  .replace(/\n/g, "<br>")
438
  }
439
 
440
+ // ------------
441
  // END SESSION
442
+ // ------------
443
  async function endSession() {
444
 
445
  console.log("🛑 Ending session")
446
 
447
+ const sessionId = window.session_id
448
+
449
  await fetch(window.location.origin + "/chat", {
450
  method: "POST",
451
  headers: { "Content-Type": "application/json" },
452
  body: JSON.stringify({
453
+ session_id: sessionId,
454
  message: "end session"
455
  })
456
  })
457
 
458
+ // 🔥 POPUP MESSAGE
459
+ if (sessionId) {
460
+ alert(`Session ended.\n\nUse Session ID: ${sessionId} to resume later.`)
461
+ }
462
+
463
  window.session_id = null
464
+ window.conversationStarted = false
465
+
466
  document.getElementById("chat").innerHTML = ""
467
+ document.getElementById("session_display").value = ""
468
  }
469
 
470
  // ---------------------------------------------------------
471
  // ENTER(SEND ACTION) & SHIFT+ENTER(INSERT NEW LINE) CONTROL
472
  // ---------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
473
  window.addEventListener("DOMContentLoaded", () => {
474
  const input = document.getElementById("main_input")
475