-
Notifications
You must be signed in to change notification settings - Fork 3
/
helpers-prompt.js
371 lines (340 loc) · 10.9 KB
/
helpers-prompt.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
const { getConfigFromSupabase } = require("./helpers-utility.js");
const logger = require("./src/logger.js")("helpers-prompt");
// const { } = require("./src/remember.js");
const {
addUserMemories,
addRelevantMemories,
addGeneralMemories,
addUserMessages,
} = require("./helpers-memory.js");
const { supabase } = require("./src/supabaseclient");
// const { listTodos } = require("./capabilities/supabasetodo.js");
const { Chance } = require("chance");
const chance = new Chance();
const fs = require("fs");
/**
* Loads the capability manifest from the specified file path.
* @returns {Object|null} The capability manifest object, or null if an error occurred.
*/
function loadCapabilityManifest() {
const manifestPath = "./capabilities/_manifest.json";
try {
const manifestData = fs.readFileSync(manifestPath, "utf8");
const manifest = JSON.parse(manifestData);
// log the number of capabilities and methods
console.log(`Loaded ${Object.keys(manifest).length} capabilities`);
return manifest;
} catch (error) {
logger.error(`Error loading capability manifest: ${JSON.stringify(error)}`);
return null;
}
}
/**
* Assembles the message preamble for a given username.
* @param {string} username - The username for which the message preamble is being assembled.
* @param {Object} options - The options for assembling the message preamble.
* @param {boolean} options.shuffle - Whether to shuffle the messages or not.
* @returns {Promise<Array<string>>} - A promise that resolves to an array of messages representing the preamble.
*/
async function assembleMessagePreamble(
username,
prompt,
messages,
options = { shuffle: false }
) {
// logger.info(`🔧 Assembling message preamble for <${username}> message`);
// logger.info(`🔧 Options: ${JSON.stringify(options)}`);
// if there ain't no messages, console.error
if (!messages) {
logger.error("No messages array provided");
return [];
}
let addedMessages = [];
addCurrentDateTime(messages);
if (chance.bool({ likelihood: 90 })) {
await addHexagramPrompt(messages);
addedMessages.push("hexagram");
}
if (chance.bool({ likelihood: 90 })) {
await addTodosToMessages(messages);
addedMessages.push("todos");
}
if (chance.bool({ likelihood: 90 })) {
await addUserMemories(username, messages);
addedMessages.push("memories");
}
if (chance.bool({ likelihood: 90 })) {
await addRelevantMemories(username, messages);
addedMessages.push("relevant memories");
}
if (chance.bool({ likelihood: 90 })) {
await addCapabilityPromptIntro(messages);
addedMessages.push("capability prompt intro");
}
if (chance.bool({ likelihood: 90 })) {
await addCapabilityManifestMessage(messages);
addedMessages.push("capability manifest");
}
if (chance.bool({ likelihood: 90 })) {
await addGeneralMemories(messages);
addedMessages.push("general memories");
}
logger.info(`🔧 Added messages: ${addedMessages.join(", ")}`);
// BE WARNED
// Shuffling does some weird shit
// Some other functions depend on `messages` being the *correctly-ordered* array
// Because it assumes things like, the *last* message with the user role is the actual last user message, things like that break
// BUT, it's useful for testing, especially with very small context windows
if (options.shuffle) {
logger.info("🔧 Shuffling messages");
messages = chance.shuffle(messages);
}
await addUserMessages(username, messages);
await addSystemPrompt(messages);
// and finally, no matter what, end with a user message re-iterating the prompt
messages.push({
role: "user",
content: prompt,
});
return messages;
}
async function addTodosToMessages(messages) {
// TODO: Fix this
// const todos = await listTodos();
// logger.info(`🔧 Adding todos to messages: ${todos.length}`);
// const todoString = JSON.stringify(todos);
// messages.push({
// role: "system",
// content: `Here are your todos:
// ${todoString}`,
// });
}
/**
* Adds the current date and time to the messages array.
* @param {Array} messages - The array of messages.
* @returns {void}
*/
function addCurrentDateTime(messages) {
messages.push({
role: "system",
content: `Today is ${new Date().toLocaleDateString()} at ${new Date().toLocaleTimeString()}`,
});
}
/**
* Generates a hexagram.
* @returns {string} - The generated hexagram.
*/
function generateHexagram() {
const hexagramNumber = chance.integer({ min: 1, max: 64 });
return `${hexagramNumber}. ${getHexName(hexagramNumber)}`;
}
/**
* Gets the name of a hexagram.
* @param {number} hexagramNumber - The number of the hexagram.
* @returns {string} - The name of the hexagram.
*/
function getHexName(hexagramNumber) {
const hexNameMap = getHexNameMap();
return hexNameMap[hexagramNumber];
}
/**
* Gets a map of hexagram numbers to names.
* @returns {object} - The map of hexagram numbers to names.
*/
function getHexNameMap() {
return {
1: "The Creative",
2: "The Receptive",
3: "Difficulty at the Beginning",
4: "Youthful Folly",
5: "Waiting",
6: "Conflict",
7: "The Army",
8: "Holding Together",
9: "The Taming Power of the Small",
10: "Treading",
11: "Peace",
12: "Standstill",
13: "Fellowship with Men",
14: "Possession in Great Measure",
15: "Modesty",
16: "Enthusiasm",
17: "Following",
18: "Work on What Has Been Spoiled",
19: "Approach",
20: "Contemplation",
21: "Biting Through",
22: "Grace",
23: "Splitting Apart",
24: "Return",
25: "Innocence",
26: "The Taming Power of the Great",
27: "The Corners of the Mouth",
28: "Preponderance of the Great",
29: "The Abysmal",
30: "The Clinging",
31: "Influence",
32: "Duration",
33: "Retreat",
34: "The Power of the Great",
35: "Progress",
36: "Darkening of the Light",
37: "The Family",
38: "Opposition",
39: "Obstruction",
40: "Deliverance",
41: "Decrease",
42: "Increase",
43: "Breakthrough",
44: "Coming to Meet",
45: "Gathering Together",
46: "Pushing Upward",
47: "Oppression",
48: "The Well",
49: "Revolution",
50: "The Cauldron",
51: "The Arousing (Shock, Thunder)",
52: "Keeping Still (Mountain)",
53: "Development (Gradual Progress)",
54: "The Marrying Maiden",
55: "Abundance (Fullness)",
56: "The Wanderer",
57: "The Gentle (Wind)",
58: "The Joyous (Lake)",
59: "Dispersion (Dissolution)",
60: "Limitation",
61: "Inner Truth",
62: "Preponderance of the Small",
63: "After Completion",
64: "Before Completion",
};
}
/**
* Adds a hexagram prompt to the messages array.
* @param {Array} messages - The array of messages.
* @returns {Promise<void>} - A promise that resolves when the hexagram prompt is added.
*/
async function addHexagramPrompt(messages) {
if (chance.bool({ likelihood: 50 })) {
const hexagram = generateHexagram();
logger.info(`🔧 Adding hexagram prompt to message ${hexagram}`);
const hexagramPrompt = `Let this hexagram from the I Ching guide this interaction: ${hexagram}`;
messages.push({
role: "system",
content: hexagramPrompt,
});
}
}
/**
* Adds a system prompt to the given array of messages.
* @param {Array} messages - The array of messages to add the system prompt to.
*/
async function addSystemPrompt(messages) {
const { PROMPT_SYSTEM } = await getPromptsFromSupabase();
messages.push({
role: "user",
content: PROMPT_SYSTEM,
});
}
/**
* Adds a capability prompt introduction message to the given array of messages.
* @param {Array} messages - The array of messages to add the capability prompt introduction to.
*/
async function addCapabilityPromptIntro(messages) {
const { CAPABILITY_PROMPT_INTRO } = await getPromptsFromSupabase();
messages.push({
role: "user",
content: CAPABILITY_PROMPT_INTRO,
});
}
/**
* Formats the capability manifest into a structured and readable format.
* @param {Object} manifest - The capability manifest object.
* @returns {string} - The capability manifest in a structured and readable format.
*/
function formatCapabilityManifest(manifest) {
let formattedManifest = "";
for (const category in manifest) {
formattedManifest += `## ${category.toUpperCase()} CAPABILITIES\n\n`;
for (const capability of manifest[category]) {
formattedManifest += `### ${capability.name}\n`;
formattedManifest += `${capability.description}\n\n`;
if (capability.parameters) {
formattedManifest += "**Parameters:**\n\n";
for (const parameter of capability.parameters) {
formattedManifest += `- **${parameter.name}**: ${parameter.description}\n`;
}
formattedManifest += "\n";
}
if (capability.examples) {
formattedManifest += "**Examples:**\n\n";
for (const example of capability.examples) {
formattedManifest += `${example}\n\n`;
}
formattedManifest += "\n";
}
}
formattedManifest += "---\n\n"; // Separator between categories
}
return formattedManifest;
}
/**
* Adds a capability manifest message to the given array of messages.
* @param {Array} messages - The array of messages to add the capability manifest message to.
* @returns {Array} - The updated array of messages.
*/
async function addCapabilityManifestMessage(messages) {
const { CHAT_MODEL } = await getConfigFromSupabase();
const manifest = loadCapabilityManifest();
// if there is no manifest, big error time
if (!manifest) {
logger.error("No capability manifest found");
return messages;
}
if (CHAT_MODEL === "claude") {
const xmlManifest = convertCapabilityManifestToXML(manifest);
messages.push({
role: "user",
content: `## CAPABILITY MANIFEST\n\n${xmlManifest}`,
});
} else {
if (manifest) {
messages.push({
role: "user",
content: `## CAPABILITY MANIFEST\n\n${formatCapabilityManifest(
manifest
)}`,
});
}
}
return messages;
}
/**
* Retrieves prompts from Supabase.
* @returns {Promise<Object>} An object containing different prompts.
* @example {
* PROMPT_REMEMBER: "In order to remember, you must first forget.",
* PROMPT_CAPABILITY_REMEMBER: "I remember that I can",
*
*/
async function getPromptsFromSupabase() {
const { data, error } = await supabase.from("prompts").select("*");
const promptArray = data;
const promptKeys = promptArray.map((prompt) => prompt.prompt_name);
const promptValues = promptArray.map((prompt) => prompt.prompt_text);
// return an object with all the keys and values
const prompts = Object.fromEntries(
promptKeys.map((_, i) => [promptKeys[i], promptValues[i]])
);
// logger.info(`Prompts: ${JSON.stringify(prompts, null, 2)}`);
return prompts;
}
module.exports = {
assembleMessagePreamble,
addCurrentDateTime,
addHexagramPrompt,
addSystemPrompt,
addCapabilityPromptIntro,
addCapabilityManifestMessage,
getPromptsFromSupabase,
};