Spaces:
Runtime error
Runtime error
Upload knowledge_base.py
Browse files- knowledge_base.py +32 -0
knowledge_base.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
class KnowledgeBase:
|
| 6 |
+
def __init__(self, storage_path="kb.json"):
|
| 7 |
+
self.storage_path = Path(storage_path)
|
| 8 |
+
if not self.storage_path.exists():
|
| 9 |
+
self._save({})
|
| 10 |
+
self.data = self._load()
|
| 11 |
+
|
| 12 |
+
def _load(self):
|
| 13 |
+
with self.storage_path.open("r") as f:
|
| 14 |
+
return json.load(f)
|
| 15 |
+
|
| 16 |
+
def _save(self, data):
|
| 17 |
+
with self.storage_path.open("w") as f:
|
| 18 |
+
json.dump(data, f, indent=2)
|
| 19 |
+
|
| 20 |
+
def get(self, topic):
|
| 21 |
+
return self.data.get(topic.lower(), "❓ No entry found.")
|
| 22 |
+
|
| 23 |
+
def set(self, topic, content):
|
| 24 |
+
self.data[topic.lower()] = content
|
| 25 |
+
self._save(self.data)
|
| 26 |
+
return f"✅ Knowledge added for topic: '{topic}'"
|
| 27 |
+
|
| 28 |
+
def search(self, query):
|
| 29 |
+
return {k: v for k, v in self.data.items() if query.lower() in k or query.lower() in v}
|
| 30 |
+
|
| 31 |
+
def list_topics(self):
|
| 32 |
+
return list(self.data.keys())
|