abhidgp1978 commited on
Commit
2eca8d7
Β·
verified Β·
1 Parent(s): 9ad81dc

Update memory_store.py

Browse files
Files changed (1) hide show
  1. memory_store.py +79 -78
memory_store.py CHANGED
@@ -1,106 +1,107 @@
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}")
 
1
  import os
2
+ import json
3
  import faiss
 
4
  import hashlib
5
+ import pandas as pd
6
  from datetime import datetime
 
 
7
  from sentence_transformers import SentenceTransformer
8
+ from huggingface_hub import HfApi, upload_file
9
+ from datasets import Dataset
10
+ import numpy as np
11
 
12
+ # Constants
 
 
13
  DATASET_REPO = "abhidgp1978/agentchat_logs"
14
+ FAISS_PATH = "memory/faiss_index.bin"
15
+ HASHES_FILE = "memory/faiss_hashes.json"
16
 
17
+ # Load model
18
  model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
19
 
20
+ # Initialize FAISS index
21
+ embedding_dim = 384
22
+ try:
23
+ if os.path.exists(FAISS_PATH):
24
+ print("βœ… Loading FAISS index from file.")
 
 
 
 
 
 
 
 
 
 
 
 
25
  faiss_index = faiss.read_index(FAISS_PATH)
26
+ else:
27
+ raise FileNotFoundError("No existing FAISS index.")
28
+ except Exception as e:
29
+ print(f"⚠️ Failed to load FAISS index: {e}")
 
 
30
  print("πŸ†• Creating new empty FAISS index.")
31
+ faiss_index = faiss.IndexFlatL2(embedding_dim)
32
 
33
+ # Load previously logged hashes to avoid duplicate FAISS entries
34
+ if os.path.exists(HASHES_FILE):
35
+ with open(HASHES_FILE, "r") as f:
36
+ hash_cache = set(json.load(f))
37
+ else:
38
+ hash_cache = set()
39
 
 
40
  def build_or_update_index(profession, query, answer):
41
+ full_text = f"{profession.strip()} | {query.strip()} | {answer.strip()}"
42
+ emb = model.encode([full_text])
43
+ entry_hash = hashlib.md5(full_text.encode()).hexdigest()
44
 
45
+ if entry_hash in hash_cache:
 
 
 
 
46
  print("🟑 Duplicate entry detected β€” skipping FAISS update.")
47
+ return
48
 
49
+ faiss_index.add(np.array(emb).astype("float32"))
50
+ faiss.write_index(faiss_index, FAISS_PATH)
51
+ hash_cache.add(entry_hash)
 
 
 
52
 
53
+ # Save updated hash set
54
+ with open(HASHES_FILE, "w") as f:
55
+ json.dump(list(hash_cache), f)
 
 
56
 
57
+ print("βœ… Updated FAISS and saved to memory/faiss_index.bin")
 
 
 
 
 
 
 
 
58
 
59
+ # Attempt to upload FAISS file
60
+ token = os.getenv("agentchat_token")
61
+ if token:
62
+ try:
63
+ upload_file(
64
+ path_or_fileobj=FAISS_PATH,
65
+ path_in_repo="memory/faiss_index.bin",
66
+ repo_id="abhidgp1978/agentchat",
67
+ repo_type="space",
68
+ token=token
69
+ )
70
+ print("βœ… FAISS pushed to Hugging Face space repo.")
71
+ except Exception as e:
72
+ print(f"❌ Failed to push FAISS to Hugging Face: {e}")
73
+ else:
74
+ print("❌ HF_TOKEN not set β€” skipping FAISS upload.")
75
 
76
+ def search_similar(text, k=5):
77
+ emb = model.encode([text])
78
+ D, I = faiss_index.search(np.array(emb).astype("float32"), k)
79
+ return D[0], I[0]
80
+
81
+ def log_chat(query, answer):
82
+ token = os.getenv("agentchat_token")
83
+ if not token:
84
+ print("❌ HF_TOKEN not set β€” cannot log to dataset.")
85
  return
86
 
87
  try:
88
+ from datasets import load_dataset
89
+ ds = load_dataset(DATASET_REPO, split="train")
90
+ df = ds.to_pandas()
91
+ except Exception:
92
+ df = pd.DataFrame(columns=["query", "answer", "timestamp"])
93
+
94
+ # Append new row
95
+ new_row = pd.DataFrame([{
96
+ "query": query,
97
+ "answer": answer,
98
+ "timestamp": datetime.utcnow().isoformat()
99
+ }])
100
+
101
+ df = pd.concat([df, new_row], ignore_index=True)
102
+ try:
103
+ updated_dataset = Dataset.from_pandas(df)
104
+ updated_dataset.push_to_hub(DATASET_REPO, token=token)
105
  print("βœ… Chat log pushed to Hugging Face Dataset")
106
  except Exception as e:
107
  print(f"❌ Failed to log chat: {e}")