Ruby/ego/context.py

39 lines
896 B
Python

import json
import os
import time
from typing import List
CONTEXT_PATH = "memory/context.json"
MAX_MEMORY = 100
def load_context():
if not os.path.exists(CONTEXT_PATH):
return []
try:
with open(CONTEXT_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except json.JSONDecodeError:
print("[Context] Corrupted context.json. Returning empty list.")
return []
def save_context(mem: List[dict]):
with open(CONTEXT_PATH, "w", encoding="utf-8") as f:
json.dump(mem[-MAX_MEMORY:], f, indent=2)
def add_to_context(text: str, source: str = "user"):
mem = load_context()
mem.append({
"timestamp": time.time(),
"source": source,
"text": text
})
save_context(mem)
def get_recent_context(n: int = 5) -> List[str]:
mem = load_context()
return [entry["text"] for entry in mem[-n:]]