File size: 1,469 Bytes
b87b898
f5c5de9
7b52c17
f5c5de9
 
 
 
 
 
 
2911d99
f5c5de9
b87b898
f5c5de9
 
2911d99
 
 
b87b898
 
 
 
2911d99
f5c5de9
 
a155411
b87b898
f5c5de9
 
2911d99
 
b87b898
 
 
 
 
 
2911d99
b87b898
 
2911d99
b87b898
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import json, os

class ContextGraph:
    def __init__(self, file_path="context_graph.json"):
        self.file_path = file_path
        self._init_graph()

    def _init_graph(self):
        if not os.path.exists(self.file_path):
            with open(self.file_path, "w") as f:
                json.dump({"context_links": {}}, f)

    def link_context(self, agent_id, category, key, value):
        with open(self.file_path, "r") as f:
            graph = json.load(f)

        if agent_id not in graph["context_links"]:
            graph["context_links"][agent_id] = {}
        if category not in graph["context_links"][agent_id]:
            graph["context_links"][agent_id][category] = {}

        graph["context_links"][agent_id][category][key] = value

        with open(self.file_path, "w") as f:
            json.dump(graph, f, indent=2)

    def query_context(self, agent_id, category=None, keyword=None):
        with open(self.file_path, "r") as f:
            graph = json.load(f)

        agent_data = graph["context_links"].get(agent_id, {})
        if category:
            data = agent_data.get(category, {})
        else:
            # Merge all categories
            data = {k: v for c in agent_data.values() for k, v in c.items()}

        results = [
            f"{k}: {v}" for k, v in data.items()
            if not keyword or keyword.lower() in k.lower() or keyword.lower() in v.lower()
        ]
        return results or ["No context found."]