Last active
May 4, 2026 13:00
-
-
Save akarnokd/6fb12168bb8c755d6b8c4616483147b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import networkx as nx | |
| from datetime import datetime | |
| import json | |
| class WorldModel: | |
| def __init__(self): | |
| self.G = nx.DiGraph() # directed graph: perfect for "A told B", "B inferred X", etc. | |
| def record_fact(self, from_entity, to_entity, relation, content="", confidence=1.0, notes=""): | |
| self.G.add_edge(from_entity, to_entity, | |
| relation=relation, | |
| content=content, | |
| timestamp=str(datetime.now()), | |
| confidence=confidence, | |
| notes=notes) | |
| print(f"✅ Recorded: {from_entity} --[{relation}]--> {to_entity} ({content})") | |
| def query_how_did_know(self, entity, info): | |
| for pred in list(self.G.predecessors(entity)): | |
| data = self.G.get_edge_data(pred, entity) | |
| if data and (info in data.get('content', '') or data.get('relation') in ['told', 'shared', 'revealed']): | |
| return f"Probably {pred} {data['relation']} {entity} directly (confidence: {data['confidence']})" | |
| return f"No explicit record found for how {entity} knows about '{info}'. Possible inference paths: {list(self.G.predecessors(entity)) or 'none'}" | |
| def save(self, filename="world_model.json"): | |
| data = nx.node_link_data(self.G) | |
| with open(filename, 'w') as f: | |
| json.dump(data, f) | |
| print(f"💾 Saved to {filename}") | |
| def load(self, filename="world_model.json"): | |
| with open(filename, 'r') as f: | |
| data = json.load(f) | |
| self.G = nx.node_link_graph(data) | |
| print(f"📂 Loaded {filename}") | |
| # Quick usage example | |
| wm = WorldModel() | |
| wm.record_fact("A", "B", "told", "the secret plan", confidence=1.0) | |
| wm.record_fact("B", "C", "knows", "the secret plan", confidence=0.8, notes="inferred_from=A_told_B") | |
| print(wm.query_how_did_know("B", "the secret plan")) | |
| # Output: Probably A told B directly (confidence: 1.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment