QOSAI / qusai_core /memory_graph.py
QalamABD's picture
Upload 46 files
acb830b verified
Raw History Blame Contribute Delete
12.7 kB
"""
Memory Hypergraph β€” Shahid's recursive JSON-based memory.
Replaces the RDF-based MemoryGraph.
Uses a dynamic JSON structure to allow for recursion and transparency.
Everything stored here is QIYAS (approximation).
"""
import json
import logging
import os
from datetime import datetime, timezone
from typing import List, Dict, Optional, Any, Set
from pathlib import Path
logger = logging.getLogger(__name__)
class MemoryGraph:
"""
Shahid's episodic + semantic memory as a JSON hypergraph.
Stores:
- Perceptions: Bilal's output (what Shahid heard)
- Inferences: Discovered patterns or derivations
- Syntheses: High-level understandings across multiple memories
- Beliefs: Shahid's own authored assertions (formerly AuthoredTriples)
- Episodes: Physical or virtual events (body state changes)
Structure is based on the TMQ v10 hypergraph pattern:
- nodes: Individual data points or events
- edges: Relationships (hyperedges) connecting one or more nodes
"""
def __init__(self, persist_path: Optional[str] = None):
self.persist_path = persist_path
self.nodes: Dict[str, Dict] = {}
self.edges: Dict[str, Dict] = {}
self._counter = 0
if self.persist_path and os.path.exists(self.persist_path):
self.load()
def _mint_id(self, prefix: str) -> str:
"""Generate a unique ID for a new memory node or edge."""
self._counter += 1
ts = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
return f"{prefix}_{ts}_{self._counter}"
# ── Node Management ───────────────────────────────────────────
def _add_node(self, node_type: str, content: Any,
timestamp: Optional[str] = None,
modal_state: Optional[Dict] = None,
metadata: Optional[Dict] = None) -> str:
node_id = self._mint_id(node_type[:3].lower())
self.nodes[node_id] = {
"type": node_type,
"timestamp": timestamp or datetime.now(timezone.utc).isoformat(),
"content": content,
"modal_state": modal_state or {},
"meta": metadata or {}
}
return node_id
# ── Edge Management ───────────────────────────────────────────
def _add_edge(self, nodes: List[str], family: str,
relation: str, modal: Optional[Dict] = None,
meta: Optional[Dict] = None) -> str:
edge_id = self._mint_id("edge")
self.edges[edge_id] = {
"nodes": nodes,
"family": family,
"relation": relation,
"modal": modal or {},
"meta": meta or {}
}
# Update nodes to track their membership in this edge
for node_id in nodes:
if node_id in self.nodes:
if "edges" not in self.nodes[node_id]:
self.nodes[node_id]["edges"] = []
self.nodes[node_id]["edges"].append(edge_id)
return edge_id
# ── Middleware Compatibility Methods ─────────────────────────
def store_perception(self, perception) -> str:
"""
Store a Bilal Perception.
"""
content = {
"source_text": perception.source_text[:1000],
"roots": perception.roots,
"signals": [
{"root": s.root, "score": round(s.score, 3), "mode": s.mode}
for s in perception.signals
],
"cooccurrences": [
{"a": co.root_a, "b": co.root_b, "count": co.count}
for co in perception.cooccurrences
]
}
node_id = self._add_node("Perception", content, timestamp=perception.timestamp)
# Auto-create edges for roots
for root in perception.roots:
self._add_edge([node_id], "RESONANCE", "resonates_with", meta={"root": root})
self._auto_persist()
return node_id
def store_inference(self, perception_uri: str, pattern: str,
confidence: float, mode: str = "QIYAS",
narration: str = "") -> str:
"""
Store an inference derived from a perception (or another node).
'perception_uri' here is the node_id.
"""
content = {
"pattern": pattern,
"confidence": round(confidence, 3),
"mode": mode,
"narration": narration
}
node_id = self._add_node("Inference", content)
# Create a recursive edge back to the source
self._add_edge([node_id, perception_uri], "RECURSION", "derived_from")
self._auto_persist()
return node_id
def store_synthesis(self, perception_uris: List[str], pattern: str,
confidence: float) -> str:
content = {
"pattern": pattern,
"confidence": round(confidence, 3),
"mode": "QIYAS"
}
node_id = self._add_node("Synthesis", content)
# Hyperedge connecting all source perceptions to this synthesis
self._add_edge([node_id] + perception_uris, "SYNTHESIS", "synthesized_from")
self._auto_persist()
return node_id
def store_chat(self, query: str, response: str, mode: str = "QIYAS",
roots: list = None, metadata: dict = None, context_id: str = None) -> str:
content = {
"query": query[:1000],
"response": response[:2000],
"mode": mode,
"roots": roots or []
}
node_id = self._add_node("Chat", content, metadata=metadata)
if roots:
for root in roots:
self._add_edge([node_id], "RESONANCE", "resonates_with", meta={"root": root})
if context_id:
self._add_edge([node_id, context_id], "LOGIC", "response_to")
self._auto_persist()
return node_id
def store_trace(self, edges: List[Dict], context_node_id: str) -> str:
"""
Stores the logical path (trace) through the hypergraph for a given interaction.
"""
content = {
"edges": edges,
"timestamp": datetime.now(timezone.utc).isoformat()
}
node_id = self._add_node("Trace", content)
# Link trace back to its context node (e.g., Perception or Chat)
self._add_edge([node_id, context_node_id], "LOGIC", "trace_for")
self._auto_persist()
return node_id
def store_authored_belief(self, subject: str, predicate: str, obj: str,
confidence: float = 0.5, source_thought: str = None) -> str:
"""
Formerly store_authored_triple.
Stores Shahid's own assertions.
"""
content = {
"subject": subject,
"predicate": predicate,
"object": obj,
"confidence": round(confidence, 3),
"mode": "QIYAS"
}
node_id = self._add_node("Belief", content)
if source_thought:
self._add_edge([node_id, source_thought], "RECURSION", "derived_from")
self._auto_persist()
return node_id
# ── Compatibility Aliases ────────────────────────────────────
def store_authored_triple(self, *args, **kwargs):
return self.store_authored_belief(*args, **kwargs)
# ── Query & Stats ───────────────────────────────────────────
def stats(self) -> Dict:
counts = {}
for node in self.nodes.values():
t = node["type"].lower() + "s"
counts[t] = counts.get(t, 0) + 1
return {
"total_nodes": len(self.nodes),
"total_edges": len(self.edges),
**counts,
"authored": counts.get("beliefs", 0)
}
def query_recent(self, limit: int = 10) -> List[Dict]:
sorted_nodes = sorted(
self.nodes.items(),
key=lambda x: x[1].get("timestamp", ""),
reverse=True
)
results = []
for nid, node in sorted_nodes[:limit]:
results.append({"id": nid, **node})
return results
def store_thought(self, step_name: str, content: str,
parent_id: Optional[str] = None,
metadata: Optional[Dict] = None) -> str:
"""
Stores a discrete step in Shahid's reasoning process.
'parent_id' can be a Chat node, a Perception node, or another Thought node.
"""
data = {
"step": step_name,
"content": content,
"timestamp": datetime.now(timezone.utc).isoformat()
}
node_id = self._add_node("Thought", data, metadata=metadata)
if parent_id:
self._add_edge([node_id, parent_id], "LOGIC", "part_of")
self._auto_persist()
return node_id
def query_by_type(self, node_type: str, limit: int = 10) -> List[Dict]:
"""Query nodes of a specific type, sorted by timestamp."""
results = []
for nid, node in self.nodes.items():
if node["type"].lower() == node_type.lower():
results.append({"id": nid, **node})
return sorted(results, key=lambda x: x.get("timestamp", ""), reverse=True)[:limit]
def query_semantic(self, text: str, limit: int = 5) -> List[Dict]:
"""
Simple keyword-based semantic query.
In the future, this will use Bilal's embeddings.
"""
text = text.lower()
results = []
for nid, node in self.nodes.items():
content_str = str(node.get("content", "")).lower()
if text in content_str:
results.append({"id": nid, **node})
return sorted(results, key=lambda x: x.get("timestamp", ""), reverse=True)[:limit]
def add_custom_edge(self, nodes: List[str], relation: str, family: str = "CUSTOM", meta: Optional[Dict] = None) -> str:
"""Exposes edge creation to the agent."""
edge_id = self._add_edge(nodes, family, relation, meta=meta)
self._auto_persist()
return edge_id
# ── Persistence ──────────────────────────────────────────────
def _auto_persist(self):
if self.persist_path:
self.save()
def save(self, path: Optional[str] = None):
target = path or self.persist_path
if not target: return
data = {
"nodes": self.nodes,
"edges": self.edges,
"stats": self.stats(),
"last_updated": datetime.now(timezone.utc).isoformat()
}
try:
with open(target, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
logger.info(f"Memory Hypergraph saved to {target}")
except Exception as e:
logger.error(f"Failed to save memory: {e}")
def load(self, path: Optional[str] = None):
target = path or self.persist_path
if not target or not os.path.exists(target): return
try:
with open(target, "r", encoding="utf-8") as f:
data = json.load(f)
self.nodes = data.get("nodes", {})
self.edges = data.get("edges", {})
# Determine max counter from existing IDs
ids = list(self.nodes.keys()) + list(self.edges.keys())
for idx in ids:
try:
num = int(idx.split("_")[-1])
if num > self._counter:
self._counter = num
except: continue
logger.info(f"Memory Hypergraph loaded from {target}")
except Exception as e:
logger.error(f"Failed to load memory: {e}")