Spaces:
Sleeping
Sleeping
File size: 1,479 Bytes
2f0addb |
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 43 44 |
import random
from dataclasses import dataclass, field
from typing import List, Dict, Any
@dataclass
class Slot:
key: str
content: str
salience: float
@dataclass
class Workspace:
max_slots: int = 7
slots: List[Slot] = field(default_factory=list)
history: List[Dict[str, Any]] = field(default_factory=list)
def commit(self, key: str, content: str, salience: float):
evicted = None
if len(self.slots) >= self.max_slots:
self.slots.sort(key=lambda s: s.salience)
evicted = self.slots.pop(0)
self.slots.append(Slot(key=key, content=content, salience=salience))
self.history.append({"event":"commit","key":key,"salience":salience,"evicted":evicted.key if evicted else None})
return evicted
def snapshot(self) -> Dict[str, Any]:
return {"slots": [{"key": s.key, "content": s.content, "salience": s.salience} for s in self.slots]}
def randomize(self):
random.shuffle(self.slots)
def clear(self):
self.slots.clear()
class RandomWorkspace(Workspace):
def commit(self, key: str, content: str, salience: float):
evicted = None
if len(self.slots) >= self.max_slots:
idx = random.randrange(len(self.slots))
evicted = self.slots.pop(idx)
idx = random.randrange(len(self.slots)+1) if self.slots else 0
self.slots.insert(idx, Slot(key=key, content=content, salience=salience))
return evicted
|