abhidgp1978 commited on
Commit
41f8bf2
Β·
verified Β·
1 Parent(s): a30dfb8

Update memory_store.py

Browse files
Files changed (1) hide show
  1. memory_store.py +78 -60
memory_store.py CHANGED
@@ -1,88 +1,106 @@
1
  import os
2
- import hashlib
3
  import faiss
4
  import pickle
 
5
  import numpy as np
6
- import pandas as pd
7
  from datetime import datetime
8
- from datasets import Dataset
9
  from huggingface_hub import HfApi
 
10
  from sentence_transformers import SentenceTransformer
11
 
12
- # === Paths and constants ===
13
- EMBED_DIM = 384
14
  FAISS_PATH = "memory/faiss_index.bin"
15
- HASH_STORE_PATH = "memory/hash_store.pkl"
16
  DATASET_REPO = "abhidgp1978/agentchat_logs"
17
 
18
- # === Embedding Model ===
19
- model = SentenceTransformer("all-MiniLM-L6-v2")
20
 
21
  # === FAISS Setup ===
22
- hash_store = set()
23
- if os.path.exists(HASH_STORE_PATH):
24
- with open(HASH_STORE_PATH, "rb") as f:
25
- hash_store = pickle.load(f)
26
 
27
- try:
28
- if os.path.exists(FAISS_PATH):
 
 
 
 
 
 
 
 
 
 
 
29
  faiss_index = faiss.read_index(FAISS_PATH)
30
  print("βœ… FAISS index loaded from file.")
31
- else:
32
- raise FileNotFoundError
33
- except Exception as e:
34
- print(f"⚠️ Failed to load FAISS index: {e}")
35
- faiss_index = faiss.IndexFlatL2(EMBED_DIM)
36
  print("πŸ†• Creating new empty FAISS index.")
37
- faiss.write_index(faiss_index, FAISS_PATH)
38
 
39
- # === Logging Function ===
40
- def log_chat(query, answer):
41
- try:
42
- print(f"πŸ“ Logging: {query} β†’ {answer}")
43
- data = {"query": [query], "answer": [answer], "timestamp": [datetime.utcnow().isoformat()]}
44
- df = pd.DataFrame(data)
45
 
46
- dataset = Dataset.from_pandas(df)
47
- try:
48
- existing = Dataset.from_hub(DATASET_REPO, split="train")
49
- combined = existing.concatenate(dataset)
50
- except Exception:
51
- combined = dataset
52
 
53
- combined.push_to_hub(DATASET_REPO, split="train")
54
- print("βœ… Chat log pushed to Hugging Face Dataset")
55
- except Exception as e:
56
- print(f"❌ Failed to log chat: {e}")
 
 
57
 
58
- # === FAISS Helper ===
59
- def build_or_update_index(profession, query, answer):
60
- try:
61
- raw = f"{profession}|{query}|{answer}"
62
- uid = hashlib.md5(raw.encode()).hexdigest()
63
- if uid in hash_store:
64
- print("🟑 Duplicate entry detected β€” skipping FAISS update.")
65
- return
66
 
67
- vec = model.encode([raw])
68
- faiss_index.add(np.array(vec).astype("float32"))
69
- faiss.write_index(faiss_index, FAISS_PATH)
 
 
70
 
71
- hash_store.add(uid)
72
- with open(HASH_STORE_PATH, "wb") as f:
73
- pickle.dump(hash_store, f)
 
 
 
 
 
 
74
 
75
- print(f"βœ… Updated FAISS and saved to {FAISS_PATH}")
 
 
76
  except Exception as e:
77
- print(f"❌ Failed to update FAISS: {e}")
 
 
 
 
 
 
 
78
 
79
- # === FAISS Search ===
80
- def search_similar(profession, query, top_k=3):
81
  try:
82
- raw = f"{profession}|{query}"
83
- vec = model.encode([raw]).astype("float32")
84
- D, I = faiss_index.search(vec, top_k)
85
- return I, D
86
  except Exception as e:
87
- print(f"❌ Search failed: {e}")
88
- return [], []
 
1
  import os
 
2
  import faiss
3
  import pickle
4
+ import hashlib
5
  import numpy as np
 
6
  from datetime import datetime
 
7
  from huggingface_hub import HfApi
8
+ from datasets import Dataset, DatasetDict, load_dataset
9
  from sentence_transformers import SentenceTransformer
10
 
11
+ # === Paths ===
 
12
  FAISS_PATH = "memory/faiss_index.bin"
13
+ HASH_PATH = "memory/faiss_hashes.pkl"
14
  DATASET_REPO = "abhidgp1978/agentchat_logs"
15
 
16
+ # === Model ===
17
+ model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
18
 
19
  # === FAISS Setup ===
20
+ embedding_size = model.get_sentence_embedding_dimension()
21
+ faiss_index = faiss.IndexFlatL2(embedding_size)
 
 
22
 
23
+ # === Hashing for deduplication ===
24
+ seen_hashes = set()
25
+ if os.path.exists(HASH_PATH):
26
+ try:
27
+ with open(HASH_PATH, "rb") as f:
28
+ seen_hashes = pickle.load(f)
29
+ except Exception as e:
30
+ print(f"⚠️ Failed to load hash cache: {e}")
31
+ seen_hashes = set()
32
+
33
+ # === Load FAISS index if exists ===
34
+ if os.path.exists(FAISS_PATH):
35
+ try:
36
  faiss_index = faiss.read_index(FAISS_PATH)
37
  print("βœ… FAISS index loaded from file.")
38
+ except Exception as e:
39
+ print(f"⚠️ Failed to load FAISS index: {e}")
40
+ faiss_index = faiss.IndexFlatL2(embedding_size)
41
+ print("πŸ†• Creating new empty FAISS index.")
42
+ else:
43
  print("πŸ†• Creating new empty FAISS index.")
 
44
 
45
+ # === Save FAISS index and hashes ===
46
+ def save_faiss_index():
47
+ faiss.write_index(faiss_index, FAISS_PATH)
48
+ with open(HASH_PATH, "wb") as f:
49
+ pickle.dump(seen_hashes, f)
50
+ print("βœ… Updated FAISS and saved to memory/faiss_index.bin")
51
 
52
+ # === Embedding and Search ===
53
+ def build_or_update_index(profession, query, answer):
54
+ full_text = f"[{profession}] {query} => {answer}"
55
+ embedding = model.encode(full_text)
56
+ h = hashlib.sha256(full_text.encode()).hexdigest()
 
57
 
58
+ if h not in seen_hashes:
59
+ seen_hashes.add(h)
60
+ faiss_index.add(np.array([embedding]).astype(np.float32))
61
+ save_faiss_index()
62
+ else:
63
+ print("🟑 Duplicate entry detected β€” skipping FAISS update.")
64
 
65
+ def search_similar(text, k=3):
66
+ embedding = model.encode(text)
67
+ if faiss_index.ntotal == 0:
68
+ return []
69
+ D, I = faiss_index.search(np.array([embedding]).astype(np.float32), k)
70
+ return I[0]
 
 
71
 
72
+ # === Logging to HF Dataset ===
73
+ def log_chat(query, answer):
74
+ timestamp = datetime.utcnow().isoformat()
75
+ row = {"query": query, "answer": answer, "timestamp": timestamp}
76
+ print(f"πŸ“ Logging: {query} β†’ {answer}")
77
 
78
+ # Try to load the dataset
79
+ try:
80
+ dataset = load_dataset(DATASET_REPO, split="train")
81
+ df = dataset.to_pandas()
82
+ df.loc[len(df)] = row
83
+ except Exception as e:
84
+ print(f"⚠️ Could not load existing dataset: {e}")
85
+ import pandas as pd
86
+ df = pd.DataFrame([row])
87
 
88
+ # Convert to Dataset
89
+ try:
90
+ updated_dataset = Dataset.from_pandas(df.reset_index(drop=True))
91
  except Exception as e:
92
+ print(f"❌ Failed to convert DataFrame to Dataset: {e}")
93
+ return
94
+
95
+ # Push to Hugging Face Dataset repo
96
+ hf_token = os.getenv("agentchat_token")
97
+ if not hf_token:
98
+ print("❌ HF_TOKEN not found in environment. Skipping dataset push.")
99
+ return
100
 
 
 
101
  try:
102
+ api = HfApi(token=hf_token)
103
+ DatasetDict({"train": updated_dataset}).push_to_hub(DATASET_REPO, token=hf_token)
104
+ print("βœ… Chat log pushed to Hugging Face Dataset")
 
105
  except Exception as e:
106
+ print(f"❌ Failed to log chat: {e}")