/// This function wrapper class adds save/load functionality to the ElizaDeducer object.
///
/// Usage:
/// let ed = ElizaDeducerInitializer(2)
/// ed.getEC2().addFromDB("test", "one_two_three") // Manual load for testing
/// let kokoro = Kokoro(AbsDictionaryDB()) // Use skill's kokoro attribute
/// let ew = ElizaDBWrapper()
/// print(ew.respond("test", ed.getEC2(), kokoro)) // Load and respond
/// print(ew.respond("test", ed.getEC2(), kokoro)) // Uses cached version
/// ed.learn("a is b") // Learning happens post-response
/// ElizaDBWrapper.sleepNSave(ed.getEC2(), kokoro) // Save when bot is idle
class ElizaDBWrapper {
private var modifiedKeys: Set<String> = []
/// Responds to input, loads from DB only once per input key
func respond(_ input: String, _ ec: EventChatV2, _ kokoro: Kokoro) -> String {
if modifiedKeys.contains(input) {
return ec.response(input)
}
modifiedKeys.insert(input)
ec.addFromDB(input, kokoro.grimoireMemento.load(input))
return ec.response(input)
}
/// Responds with the most recent reply, loads from DB only once
func respondLatest(_ input: String, _ ec: EventChatV2, _ kokoro: Kokoro) -> String {
if modifiedKeys.contains(input) {
return ec.responseLatest(input)
}
modifiedKeys.insert(input)
ec.addFromDB(input, kokoro.grimoireMemento.load(input))
return ec.responseLatest(input)
}
/// Use this to save once the bot is idle/asleep—not during every response
static func sleepNSave(_ ecv2: EventChatV2, _ kokoro: Kokoro) {
for key in ecv2.getModifiedKeys() {
let saveStr = ecv2.getSaveStr(key)
kokoro.grimoireMemento.save(key, saveStr)
}
}
}