Tpayne101 commited on
Commit
2911d99
·
verified ·
1 Parent(s): e36f0e1

Update context_graph.py

Browse files
Files changed (1) hide show
  1. context_graph.py +21 -12
context_graph.py CHANGED
@@ -2,31 +2,40 @@ import json
2
  import os
3
 
4
  class ContextGraph:
5
- """
6
- Stores relationships between prompts and responses.
7
- Think of it as a 'map' of what the agent has learned.
8
- """
9
-
10
  def __init__(self, file_path="context_graph.json"):
11
  self.file_path = file_path
12
  self._init_graph()
13
 
14
  def _init_graph(self):
 
15
  if not os.path.exists(self.file_path):
16
  with open(self.file_path, "w") as f:
17
- json.dump({"links": {}}, f)
18
 
19
  def link_context(self, agent_id, key, value):
 
20
  with open(self.file_path, "r") as f:
21
  graph = json.load(f)
22
- if agent_id not in graph["links"]:
23
- graph["links"][agent_id] = {}
24
- graph["links"][agent_id][key] = value
 
 
 
 
25
  with open(self.file_path, "w") as f:
26
  json.dump(graph, f, indent=2)
27
- print(f"[ContextGraph] Linked ({key} {value}) for {agent_id}")
28
 
29
- def get_context(self, agent_id):
 
30
  with open(self.file_path, "r") as f:
31
  graph = json.load(f)
32
- return graph["links"].get(agent_id, {})
 
 
 
 
 
 
 
 
2
  import os
3
 
4
  class ContextGraph:
 
 
 
 
 
5
  def __init__(self, file_path="context_graph.json"):
6
  self.file_path = file_path
7
  self._init_graph()
8
 
9
  def _init_graph(self):
10
+ # Create the graph file if it doesn't exist
11
  if not os.path.exists(self.file_path):
12
  with open(self.file_path, "w") as f:
13
+ json.dump({"context_links": {}}, f)
14
 
15
  def link_context(self, agent_id, key, value):
16
+ # Load the current context graph
17
  with open(self.file_path, "r") as f:
18
  graph = json.load(f)
19
+
20
+ # Add the new link under the correct agent ID
21
+ if agent_id not in graph["context_links"]:
22
+ graph["context_links"][agent_id] = {}
23
+ graph["context_links"][agent_id][key] = value
24
+
25
+ # Save the updated graph
26
  with open(self.file_path, "w") as f:
27
  json.dump(graph, f, indent=2)
28
+ os.sync() # Force Hugging Face to write to disk
29
 
30
+ def query_context(self, agent_id, keyword):
31
+ # Search for any stored memory entries that contain the keyword
32
  with open(self.file_path, "r") as f:
33
  graph = json.load(f)
34
+
35
+ agent_data = graph["context_links"].get(agent_id, {})
36
+ results = [
37
+ f"{k}: {v}" for k, v in agent_data.items()
38
+ if keyword.lower() in k.lower() or keyword.lower() in v.lower()
39
+ ]
40
+
41
+ return results if results else ["No matching context found."]