Spaces:
Runtime error
Runtime error
Update context_graph.py
Browse files- context_graph.py +31 -27
context_graph.py
CHANGED
|
@@ -1,33 +1,37 @@
|
|
| 1 |
-
import
|
| 2 |
-
from
|
| 3 |
|
| 4 |
class ContextGraph:
|
| 5 |
-
def __init__(self
|
| 6 |
-
self.
|
| 7 |
-
self.graph = self.load_graph()
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
|
| 11 |
-
with open(self.file_path, "r") as f:
|
| 12 |
-
return json.load(f)
|
| 13 |
-
return defaultdict(list)
|
| 14 |
|
| 15 |
-
def
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from sentence_transformers import SentenceTransformer
|
| 3 |
|
| 4 |
class ContextGraph:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
|
|
|
| 7 |
|
| 8 |
+
def encode(self, text):
|
| 9 |
+
return self.model.encode(text)
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
def connect(self, memory_texts, threshold=0.35):
|
| 12 |
+
"""
|
| 13 |
+
Create relationships between memory nodes based on vector similarity.
|
| 14 |
+
"""
|
| 15 |
+
vectors = [self.encode(t) for t in memory_texts]
|
| 16 |
+
relationships = []
|
| 17 |
|
| 18 |
+
for i, vec1 in enumerate(vectors):
|
| 19 |
+
for j, vec2 in enumerate(vectors):
|
| 20 |
+
if i != j:
|
| 21 |
+
similarity = np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
|
| 22 |
+
if similarity >= threshold:
|
| 23 |
+
relationships.append((memory_texts[i], memory_texts[j], float(similarity)))
|
| 24 |
|
| 25 |
+
return relationships
|
| 26 |
+
|
| 27 |
+
def score_context(self, query, memories):
|
| 28 |
+
"""
|
| 29 |
+
Score stored memories against the new query.
|
| 30 |
+
"""
|
| 31 |
+
query_vec = self.encode(query)
|
| 32 |
+
scored = []
|
| 33 |
+
for mem, vec in memories:
|
| 34 |
+
score = np.dot(query_vec, vec) / (np.linalg.norm(query_vec) * np.linalg.norm(vec))
|
| 35 |
+
scored.append((mem, float(score)))
|
| 36 |
+
|
| 37 |
+
return sorted(scored, key=lambda x: x[1], reverse=True)
|