mindcraft/src/agent/history.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

2024-03-05 12:05:46 -08:00
import { writeFileSync, readFileSync } from 'fs';
import { NPCData } from './npc/data.js';
2023-11-12 14:53:23 -08:00
export class History {
2023-12-21 20:42:01 -07:00
constructor(agent) {
this.agent = agent;
2023-11-12 14:53:23 -08:00
this.name = agent.name;
this.memory_fp = `./bots/${this.name}/memory.json`;
2023-11-15 13:18:38 -08:00
this.turns = [];
2023-11-12 14:53:23 -08:00
// These define an agent's long term memory
this.memory = '';
2023-11-15 13:18:38 -08:00
// Variables for controlling the agent's memory and knowledge
2023-11-12 14:53:23 -08:00
this.max_messages = 20;
}
2023-08-15 23:39:02 -07:00
getHistory() { // expects an Examples object
return JSON.parse(JSON.stringify(this.turns));
2023-11-13 20:33:34 -08:00
}
2023-11-12 14:53:23 -08:00
2023-11-13 20:33:34 -08:00
async storeMemories(turns) {
console.log("Storing memories...");
this.memory = await this.agent.prompter.promptMemSaving(this.memory, turns);
console.log("Memory updated to: ", this.memory);
2023-11-15 13:18:38 -08:00
}
2023-11-12 14:53:23 -08:00
async add(name, content) {
let role = 'assistant';
if (name === 'system') {
role = 'system';
}
2023-11-13 20:33:34 -08:00
else if (name !== this.name) {
role = 'user';
content = `${name}: ${content}`;
2023-08-17 00:00:57 -07:00
}
this.turns.push({role, content});
2023-11-12 14:53:23 -08:00
// Summarize older turns into memory
if (this.turns.length >= this.max_messages) {
2023-11-15 11:38:17 -08:00
let to_summarize = [this.turns.shift()];
2023-12-04 23:26:21 -08:00
while (this.turns[0].role != 'user' && this.turns.length > 1)
2023-11-15 11:38:17 -08:00
to_summarize.push(this.turns.shift());
await this.storeMemories(to_summarize);
2023-11-12 14:53:23 -08:00
}
}
2023-12-21 20:42:01 -07:00
save() {
2023-11-12 14:53:23 -08:00
// save history object to json file
2023-11-15 13:18:38 -08:00
let data = {
'name': this.name,
'memory': this.memory,
'turns': this.turns
};
2024-03-05 12:05:46 -08:00
if (this.agent.npc.data !== null)
data.npc = this.agent.npc.data.toObject();
2023-11-15 13:18:38 -08:00
const json_data = JSON.stringify(data, null, 4);
writeFileSync(this.memory_fp, json_data, (err) => {
2023-11-12 14:53:23 -08:00
if (err) {
throw err;
}
console.log("JSON data is saved.");
});
}
load() {
2023-11-12 14:53:23 -08:00
try {
// load history object from json file
const data = readFileSync(this.memory_fp, 'utf8');
2023-11-12 14:53:23 -08:00
const obj = JSON.parse(data);
this.memory = obj.memory;
2024-03-05 12:05:46 -08:00
this.agent.npc.data = NPCData.fromObject(obj.npc);
2023-12-04 23:26:21 -08:00
this.turns = obj.turns;
2023-11-12 14:53:23 -08:00
} catch (err) {
console.error(`No memory file '${this.memory_fp}' for agent ${this.name}.`);
2023-11-12 14:53:23 -08:00
}
2023-08-17 00:00:57 -07:00
}
clear() {
this.turns = [];
this.memory = '';
}
}