Phrase Repetition Penalty
@@ -1272,41 +1285,7 @@
+
+
+
+
+ Impersonation prompt
+
+
+
+ Prompt that is used for Impersonation function
+
+
+
+
+
+
+
+ World Info format template
+
+
+
+ Wraps activated World Info entries before inserting into the prompt. Use
+ {0} to mark a place where the content is inserted.
+
+
+
+
+
+
+
+
+ NSFW avoidance prompt
+
+
+
+ Prompt that is used when the NSFW toggle is OFF
+
+
+
+
+
+
+
+
+ New Chat
+
+
+
+
+ Set at the beginning of the chat history to indicate that a new chat is about to start.
+
+
+
+
+
+
+
+
+ New Group Chat
+
+
+
+
+ Set at the beginning of the chat history to indicate that a new group chat is about to start.
+
+
+
+
+
+
+
+
+ New Example Chat
+
+
+
+
+ Set at the beginning of Dialogue examples to indicate that a new example chat is about to start.
+
+
+
+
+
+
+
+
+ Continue nudge
+
+
+
+
+ Set at the end of the chat history when the continue button is pressed.
+
+
+
+
+
+
+
+
+ Replace empty message
+
+
Send this text instead of nothing when the text box is empty.
-
-
-
-
-
-
-
-
-
-
- Overridden by the Character Definitions.
-
-
- The main prompt used to set the model behavior
-
-
-
-
-
-
-
- NSFW prompt
-
-
-
- Prompt that is used when the NSFW toggle is on
-
-
-
-
-
-
-
- NSFW avoidance prompt
-
-
-
-
- Prompt that is used when the NSFW toggle is OFF
-
-
-
-
-
-
-
-
- Jailbreak prompt
-
-
-
- Overridden by the Character Definitions.
-
-
- Prompt that is used when the Jailbreak toggle is on
-
-
-
-
-
-
- Assistant Prefill
-
-
-
-
-
-
-
-
-
Impersonation prompt
-
+
+
-
- Prompt that is used for Impersonation function
-
-
-
-
-
-
-
- World Info format template
-
-
-
-
- Wraps activated World Info entries before inserting into the prompt. Use {0} to mark a place where the content is inserted.
-
-
-
-
-
-
-
+
diff --git a/public/instruct/Roleplay.json b/public/instruct/Roleplay.json
index bd5b9e882..86b59cbbd 100644
--- a/public/instruct/Roleplay.json
+++ b/public/instruct/Roleplay.json
@@ -2,7 +2,7 @@
"input_sequence": "### Instruction:",
"macro": true,
"name": "Roleplay",
- "names": false,
+ "names": true,
"output_sequence": "### Response (2 paragraphs, engaging, natural, authentic, descriptive, creative):",
"separator_sequence": "",
"stop_sequence": "",
diff --git a/public/script.js b/public/script.js
index df9f5c2ac..c6ba4fbcf 100644
--- a/public/script.js
+++ b/public/script.js
@@ -79,6 +79,7 @@ import {
import {
setOpenAIMessageExamples,
setOpenAIMessages,
+ setupChatCompletionPromptManager,
prepareOpenAIMessages,
sendOpenAIRequest,
loadOpenAISettings,
@@ -160,6 +161,7 @@ import { context_settings, loadContextTemplatesFromSettings } from "./scripts/co
import { markdownExclusionExt } from "./scripts/showdown-exclusion.js";
import { NOTE_MODULE_NAME, metadata_keys, setFloatingPrompt, shouldWIAddPrompt } from "./scripts/authors-note.js";
import { deviceInfo } from "./scripts/RossAscends-mods.js";
+import { registerPromptManagerMigration } from "./scripts/PromptManager.js";
import { getRegexedString, regex_placement } from "./scripts/extensions/regex/engine.js";
//exporting functions and vars for mods
@@ -253,6 +255,14 @@ export const event_types = {
SETTINGS_UPDATED: 'settings_updated',
GROUP_UPDATED: 'group_updated',
MOVABLE_PANELS_RESET: 'movable_panels_reset',
+ SETTINGS_LOADED_BEFORE: 'settings_loaded_before',
+ SETTINGS_LOADED_AFTER: 'settings_loaded_after',
+ CHATCOMPLETION_SOURCE_CHANGED: 'chatcompletion_source_changed',
+ CHATCOMPLETION_MODEL_CHANGED: 'chatcompletion_model_changed',
+ OAI_BEFORE_CHATCOMPLETION: 'oai_before_chatcompletion',
+ OAI_PRESET_CHANGED: 'oai_preset_changed',
+ WORLDINFO_SETTINGS_UPDATED: 'worldinfo_settings_updated',
+ CHARACTER_EDITED: 'character_edited',
}
export const eventSource = new EventEmitter();
@@ -531,6 +541,9 @@ this
},
};
+// Register configuration migrations
+registerPromptManagerMigration();
+
$(document).ajaxError(function myErrorHandler(_, xhr) {
if (xhr.status == 403) {
toastr.warning(
@@ -1631,9 +1644,11 @@ function scrollChatToBottom() {
}
}
-function substituteParams(content, _name1, _name2, _original) {
+function substituteParams(content, _name1, _name2, _original, _group) {
_name1 = _name1 ?? name1;
_name2 = _name2 ?? name2;
+ _original = _original || '';
+ _group = _group ?? name2;
if (!content) {
return '';
@@ -1648,8 +1663,14 @@ function substituteParams(content, _name1, _name2, _original) {
content = content.replace(/{{input}}/gi, $('#send_textarea').val());
content = content.replace(/{{user}}/gi, _name1);
content = content.replace(/{{char}}/gi, _name2);
+ content = content.replace(/{{charIfNotGroup}}/gi, _group);
+ content = content.replace(/{{group}}/gi, _group);
+
content = content.replace(/
/gi, _name1);
content = content.replace(//gi, _name2);
+ content = content.replace(//gi, _group);
+ content = content.replace(//gi, _group);
+
content = content.replace(/{{time}}/gi, moment().format('LT'));
content = content.replace(/{{date}}/gi, moment().format('LL'));
content = content.replace(/{{idle_duration}}/gi, () => getTimeSinceLastMessage());
@@ -2216,7 +2237,7 @@ class StreamingProcessor {
}
}
-async function Generate(type, { automatic_trigger, force_name2, resolve, reject, quiet_prompt, force_chid, signal } = {}) {
+async function Generate(type, { automatic_trigger, force_name2, resolve, reject, quiet_prompt, force_chid, signal } = {}, dryRun = false) {
//console.log('Generate entered');
setGenerationProgress(0);
tokens_already_generated = 0;
@@ -2288,14 +2309,34 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
reject = () => { };
}
- if (selected_group && !is_group_generating) {
+ if (selected_group && !is_group_generating && !dryRun) {
generateGroupWrapper(false, type, { resolve, reject, quiet_prompt, force_chid, signal: abortController.signal });
return;
+ } else if (selected_group && !is_group_generating && dryRun) {
+ const characterIndexMap = new Map(characters.map((char, index) => [char.avatar, index]));
+ const group = groups.find((x) => x.id === selected_group);
+
+ const enabledMembers = group.members.reduce((acc, member) => {
+ if (!group.disabled_members.includes(member) && !acc.includes(member)) {
+ acc.push(member);
+ }
+ return acc;
+ }, []);
+
+ const memberIds = enabledMembers
+ .map((member) => characterIndexMap.get(member))
+ .filter((index) => index !== undefined);
+
+ if (memberIds.length > 0) {
+ setCharacterId(memberIds[0]);
+ setCharacterName('');
+ }
}
- if (online_status != 'no_connection' && this_chid != undefined && this_chid !== 'invalid-safety-id') {
+ if (true === dryRun ||
+ (online_status != 'no_connection' && this_chid != undefined && this_chid !== 'invalid-safety-id')) {
let textareaText;
- if (type !== 'regenerate' && type !== "swipe" && type !== 'quiet' && !isImpersonate) {
+ if (type !== 'regenerate' && type !== "swipe" && type !== 'quiet' && !isImpersonate && !dryRun) {
is_send_press = true;
textareaText = $("#send_textarea").val();
$("#send_textarea").val('').trigger('input');
@@ -2304,7 +2345,7 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
if (chat.length && chat[chat.length - 1]['is_user']) {
//do nothing? why does this check exist?
}
- else if (type !== 'quiet' && type !== "swipe" && !isImpersonate) {
+ else if (type !== 'quiet' && type !== "swipe" && !isImpersonate && !dryRun) {
chat.length = chat.length - 1;
count_view_mes -= 1;
$('#chat').children().last().hide(500, function () {
@@ -2785,19 +2826,20 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
generate_data = getNovelGenerationData(finalPromt, this_settings, this_amount_gen, isImpersonate);
}
else if (main_api == 'openai') {
- let [prompt, counts] = await prepareOpenAIMessages({
- systemPrompt: systemPrompt,
+ let [prompt, counts] = prepareOpenAIMessages({
name2: name2,
- storyString: storyString,
+ charDescription: charDescription,
+ charPersonality: charPersonality,
+ Scenario: Scenario,
worldInfoBefore: worldInfoBefore,
worldInfoAfter: worldInfoAfter,
- extensionPrompt: afterScenarioAnchor,
+ extensionPrompts: extension_prompts,
bias: promptBias,
type: type,
quietPrompt: quiet_prompt,
jailbreakPrompt: jailbreakPrompt,
cyclePrompt: cyclePrompt,
- });
+ }, dryRun);
generate_data = { prompt: prompt };
// counts will return false if the user has not enabled the token breakdown feature
@@ -2808,6 +2850,8 @@ async function Generate(type, { automatic_trigger, force_name2, resolve, reject,
setInContextMessages(openai_messages_count, type);
}
+ if (true === dryRun) return onSuccess({error: 'dryRun'});
+
if (power_user.console_log_prompts) {
console.log(generate_data.prompt);
@@ -3207,14 +3251,14 @@ function parseTokenCounts(counts, thisPromptBits) {
const total = Object.values(counts).filter(x => !Number.isNaN(x)).reduce((acc, val) => acc + val, 0);
thisPromptBits.push({
- oaiStartTokens: Object.entries(counts)[0][1],
- oaiPromptTokens: Object.entries(counts)[1][1],
- oaiBiasTokens: Object.entries(counts)[2][1],
- oaiNudgeTokens: Object.entries(counts)[3][1],
- oaiJailbreakTokens: Object.entries(counts)[4][1],
- oaiImpersonateTokens: Object.entries(counts)[5][1],
- oaiExamplesTokens: Object.entries(counts)[6][1],
- oaiConversationTokens: Object.entries(counts)[7][1],
+ oaiStartTokens: Object.entries(counts)?.[0]?.[1] ?? 0,
+ oaiPromptTokens: Object.entries(counts)?.[1]?.[1] ?? 0,
+ oaiBiasTokens: Object.entries(counts)?.[2]?.[1] ?? 0,
+ oaiNudgeTokens: Object.entries(counts)?.[3]?.[1] ?? 0,
+ oaiJailbreakTokens: Object.entries(counts)?.[4]?.[1] ?? 0,
+ oaiImpersonateTokens: Object.entries(counts)?.[5]?.[1] ?? 0,
+ oaiExamplesTokens: Object.entries(counts)?.[6]?.[1] ?? 0,
+ oaiConversationTokens: Object.entries(counts)?.[7]?.[1] ?? 0,
oaiTotalTokens: total,
});
}
@@ -4356,6 +4400,7 @@ async function getChat() {
}
await getChatResult();
await saveChat();
+ eventSource.emit('chatLoaded', {detail: {id: this_chid, character: characters[this_chid]}});
setTimeout(function () {
@@ -4515,6 +4560,17 @@ function changeMainAPI() {
getStatus();
getHordeModels();
}
+
+ switch (oai_settings.chat_completion_source) {
+ case chat_completion_sources.SCALE:
+ case chat_completion_sources.OPENROUTER:
+ case chat_completion_sources.WINDOWAI:
+ case chat_completion_sources.CLAUDE:
+ case chat_completion_sources.OPENAI:
+ default:
+ setupChatCompletionPromptManager(oai_settings);
+ break;
+ }
}
////////////////////////////////////////////////////
@@ -5033,6 +5089,9 @@ async function getSettings(type) {
$("#your_name").val(name1);
}
+ // Allow subscribers to mutate settings
+ eventSource.emit(event_types.SETTINGS_LOADED_BEFORE, settings);
+
//Load KoboldAI settings
koboldai_setting_names = data.koboldai_setting_names;
koboldai_settings = data.koboldai_settings;
@@ -5120,6 +5179,9 @@ async function getSettings(type) {
// Load context templates
loadContextTemplatesFromSettings(data, settings);
+ // Allow subscribers to mutate settings
+ eventSource.emit(event_types.SETTINGS_LOADED_AFTER, settings);
+
// Set context size after loading power user (may override the max value)
$("#max_context").val(max_context);
$("#max_context_counter").text(`${max_context}`);
@@ -6477,6 +6539,7 @@ async function createOrEditCharacter(e) {
);
$("#create_button").attr("value", "Save");
crop_data = undefined;
+ eventSource.emit(event_types.CHARACTER_EDITED, {detail: {id: this_chid, character: characters[this_chid]}});
},
error: function (jqXHR, exception) {
$("#create_button").removeAttr("disabled");
@@ -7520,6 +7583,7 @@ $(document).ready(function () {
if (popup_type == "del_ch") {
const deleteChats = !!$("#del_char_checkbox").prop("checked");
await handleDeleteCharacter(popup_type, this_chid, deleteChats);
+ eventSource.emit('characterDeleted', {id: this_chid, character: characters[this_chid]});
}
if (popup_type == "alternate_greeting" && menu_type !== "create") {
createOrEditCharacter();
@@ -7989,7 +8053,7 @@ $(document).ready(function () {
is_delete_mode = false;
});
- //confirms message delation with the "ok" button
+ //confirms message deletion with the "ok" button
$("#dialogue_del_mes_ok").click(function () {
$("#dialogue_del_mes").css("display", "none");
$("#send_form").css("display", css_send_form_display);
@@ -8389,6 +8453,8 @@ $(document).ready(function () {
updateViewMessageIds();
saveChatConditional();
+ eventSource.emit(event_types.MESSAGE_DELETED, count_view_mes);
+
hideSwipeButtons();
showSwipeButtons();
});
diff --git a/public/scripts/PromptManager.js b/public/scripts/PromptManager.js
new file mode 100644
index 000000000..ddf889637
--- /dev/null
+++ b/public/scripts/PromptManager.js
@@ -0,0 +1,1693 @@
+import {callPopup, event_types, eventSource, main_api, substituteParams} from "../script.js";
+import {TokenHandler} from "./openai.js";
+import {power_user} from "./power-user.js";
+import { debounce } from "./utils.js";
+
+/**
+ * Register migrations for the prompt manager when settings are loaded or an Open AI preset is loaded.
+ */
+const registerPromptManagerMigration = () => {
+ const migrate = (settings, savePreset = null, presetName = null) => {
+ if (settings.main_prompt || settings.nsfw_prompt || settings.jailbreak_prompt) {
+ console.log('Running prompt manager configuration migration');
+ if (settings.prompts === undefined || settings.prompts.length === 0) settings.prompts = structuredClone(chatCompletionDefaultPrompts.prompts);
+
+ const findPrompt = (identifier) => settings.prompts.find(prompt => identifier === prompt.identifier);
+ if (settings.main_prompt) {
+ findPrompt('main').content = settings.main_prompt
+ delete settings.main_prompt;
+ }
+
+ if (settings.nsfw_prompt) {
+ findPrompt('nsfw').content = settings.nsfw_prompt
+ delete settings.nsfw_prompt;
+ }
+
+ if (settings.jailbreak_prompt) {
+ findPrompt('jailbreak').content = settings.jailbreak_prompt
+ delete settings.jailbreak_prompt;
+ }
+
+ if (savePreset && presetName) savePreset(presetName, settings, false);
+ }
+ };
+
+ eventSource.on(event_types.SETTINGS_LOADED_BEFORE, settings => migrate(settings));
+ eventSource.on(event_types.OAI_PRESET_CHANGED, event => migrate(event.preset, event.savePreset, event.presetName));
+}
+
+/**
+ * Represents a prompt.
+ */
+class Prompt {
+ identifier; role; content; name; system_prompt;
+
+ /**
+ * Create a new Prompt instance.
+ *
+ * @param {Object} param0 - Object containing the properties of the prompt.
+ * @param {string} param0.identifier - The unique identifier of the prompt.
+ * @param {string} param0.role - The role associated with the prompt.
+ * @param {string} param0.content - The content of the prompt.
+ * @param {string} param0.name - The name of the prompt.
+ * @param {boolean} param0.system_prompt - Indicates if the prompt is a system prompt.
+ */
+ constructor({identifier, role, content, name, system_prompt} = {}) {
+ this.identifier = identifier;
+ this.role = role;
+ this.content = content;
+ this.name = name;
+ this.system_prompt = system_prompt;
+ }
+}
+
+/**
+ * Representing a collection of prompts.
+ */
+class PromptCollection {
+ collection = [];
+
+ /**
+ * Create a new PromptCollection instance.
+ *
+ * @param {...Prompt} prompts - An array of Prompt instances.
+ */
+ constructor(...prompts) {
+ this.add(...prompts);
+ }
+
+ /**
+ * Checks if the provided instances are of the Prompt class.
+ *
+ * @param {...any} prompts - Instances to check.
+ * @throws Will throw an error if one or more instances are not of the Prompt class.
+ */
+ checkPromptInstance(...prompts) {
+ for(let prompt of prompts) {
+ if(!(prompt instanceof Prompt)) {
+ throw new Error('Only Prompt instances can be added to PromptCollection');
+ }
+ }
+ }
+
+ /**
+ * Adds new Prompt instances to the collection.
+ *
+ * @param {...Prompt} prompts - An array of Prompt instances.
+ */
+ add(...prompts) {
+ this.checkPromptInstance(...prompts);
+ this.collection.push(...prompts);
+ }
+
+ /**
+ * Sets a Prompt instance at a specific position in the collection.
+ *
+ * @param {Prompt} prompt - The Prompt instance to set.
+ * @param {number} position - The position in the collection to set the Prompt instance.
+ */
+ set(prompt, position) {
+ this.checkPromptInstance(prompt);
+ this.collection[position] = prompt;
+ }
+
+ /**
+ * Retrieves a Prompt instance from the collection by its identifier.
+ *
+ * @param {string} identifier - The identifier of the Prompt instance to retrieve.
+ * @returns {Prompt} The Prompt instance with the provided identifier, or undefined if not found.
+ */
+ get(identifier) {
+ return this.collection.find(prompt => prompt.identifier === identifier);
+ }
+
+ /**
+ * Retrieves the index of a Prompt instance in the collection by its identifier.
+ *
+ * @param {null} identifier - The identifier of the Prompt instance to find.
+ * @returns {number} The index of the Prompt instance in the collection, or -1 if not found.
+ */
+ index(identifier) {
+ return this.collection.findIndex(prompt => prompt.identifier === identifier);
+ }
+
+ /**
+ * Checks if a Prompt instance exists in the collection by its identifier.
+ *
+ * @param {string} identifier - The identifier of the Prompt instance to check.
+ * @returns {boolean} true if the Prompt instance exists in the collection, false otherwise.
+ */
+ has(identifier) {
+ return this.index(identifier) !== -1;
+ }
+}
+
+function PromptManagerModule() {
+ this.configuration = {
+ version: 1,
+ prefix: '',
+ containerIdentifier: '',
+ listIdentifier: '',
+ listItemTemplateIdentifier: '',
+ toggleDisabled: [],
+ draggable: true,
+ warningTokenThreshold: 1500,
+ dangerTokenThreshold: 500,
+ defaultPrompts: {
+ main: '',
+ nsfw: '',
+ jailbreak: '',
+ enhanceDefinitions: ''
+ },
+ };
+
+ // Chatcompletion configuration object
+ this.serviceSettings = null;
+
+ // DOM element containing the prompt manager
+ this.containerElement = null;
+
+ // DOM element containing the prompt list
+ this.listElement = null;
+
+ // Currently selected character
+ this.activeCharacter = null;
+
+ // Message collection of the most recent chatcompletion
+ this.messages = null;
+
+ // The current token handler instance
+ this.tokenHandler = null;
+
+ // Token usage of last dry run
+ this.tokenUsage = 0;
+
+ // Error state, contains error message.
+ this.error = null;
+
+ /** Dry-run for generate, must return a promise */
+ this.tryGenerate = () => { };
+
+ /** Called to persist the configuration, must return a promise */
+ this.saveServiceSettings = () => { };
+
+ /** Toggle prompt button click */
+ this.handleToggle = () => { };
+
+ /** Prompt name click */
+ this.handleInspect = () => { };
+
+ /** Edit prompt button click */
+ this.handleEdit = () => { };
+
+ /** Detach prompt button click */
+ this.handleDetach = () => { };
+
+ /** Save prompt button click */
+ this.handleSavePrompt = () => { };
+
+ /** Reset prompt button click */
+ this.handleResetPrompt = () => { };
+
+ /** New prompt button click */
+ this.handleNewPrompt = () => { };
+
+ /** Delete prompt button click */
+ this.handleDeletePrompt = () => { };
+
+ /** Append prompt button click */
+ this.handleAppendPrompt = () => { };
+
+ /** Import button click */
+ this.handleImport = () => { };
+
+ /** Full export click */
+ this.handleFullExport = () => { };
+
+ /** Character export click */
+ this.handleCharacterExport = () => { };
+
+ /** Character reset button click*/
+ this.handleCharacterReset = () => {};
+
+ /** Debounced version of render */
+ this.renderDebounced = debounce(this.render.bind(this), 1000);
+}
+
+/**
+ * Initializes the PromptManagerModule with provided configuration and service settings.
+ *
+ * Sets up various handlers for user interactions, event listeners and initial rendering of prompts.
+ * It is also responsible for preparing prompt edit form buttons, managing popup form close and clear actions.
+ *
+ * @param {Object} moduleConfiguration - Configuration object for the PromptManagerModule.
+ * @param {Object} serviceSettings - Service settings object for the PromptManagerModule.
+ */
+PromptManagerModule.prototype.init = function (moduleConfiguration, serviceSettings) {
+ this.configuration = Object.assign(this.configuration, moduleConfiguration);
+ this.tokenHandler = this.tokenHandler || new TokenHandler();
+ this.serviceSettings = serviceSettings;
+ this.containerElement = document.getElementById(this.configuration.containerIdentifier);
+
+ this.sanitizeServiceSettings();
+
+ // Enable and disable prompts
+ this.handleToggle = (event) => {
+ const promptID = event.target.closest('.' + this.configuration.prefix + 'prompt_manager_prompt').dataset.pmIdentifier;
+ const promptOrderEntry = this.getPromptOrderEntry(this.activeCharacter, promptID);
+ const counts = this.tokenHandler.getCounts();
+
+ counts[promptID] = null;
+ promptOrderEntry.enabled = !promptOrderEntry.enabled;
+ this.saveServiceSettings().then(() => this.render());
+ };
+
+ // Open edit form and load selected prompt
+ this.handleEdit = (event) => {
+ this.clearEditForm();
+ this.clearInspectForm();
+
+ const promptID = event.target.closest('.' + this.configuration.prefix + 'prompt_manager_prompt').dataset.pmIdentifier;
+ const prompt = this.getPromptById(promptID);
+
+ this.loadPromptIntoEditForm(prompt);
+
+ this.showPopup();
+ }
+
+ // Open edit form and load selected prompt
+ this.handleInspect = (event) => {
+ this.clearEditForm();
+ this.clearInspectForm();
+
+ const promptID = event.target.closest('.' + this.configuration.prefix + 'prompt_manager_prompt').dataset.pmIdentifier;
+ if (true === this.messages.hasItemWithIdentifier(promptID)) {
+ const messages = this.messages.getItemByIdentifier(promptID);
+
+ this.loadMessagesIntoInspectForm(messages);
+
+ this.showPopup('inspect');
+ }
+ }
+
+ // Detach selected prompt from list form and close edit form
+ this.handleDetach = (event) => {
+ if (null === this.activeCharacter) return;
+ const promptID = event.target.closest('.' + this.configuration.prefix + 'prompt_manager_prompt').dataset.pmIdentifier;
+ const prompt = this.getPromptById(promptID);
+
+ this.detachPrompt(prompt, this.activeCharacter);
+ this.hidePopup();
+ this.clearEditForm();
+ this.saveServiceSettings().then(() => this.render());
+ };
+
+ // Factory function for creating quick edit elements
+ const saveSettings = this.saveServiceSettings;
+ const createQuickEdit = function() {
+ return {
+ element: null,
+ prompt: null,
+
+ from(element, prompt) {
+ this.element = element;
+ element.value = prompt.content ?? '';
+ element.addEventListener('input', () => {
+ prompt.content = element.value;
+ saveSettings();
+ });
+
+ return this;
+ },
+
+ update(value) {
+ this.element.value = value;
+ }
+ }
+ }
+
+ const mainPrompt = this.getPromptById('main');
+ const mainPromptTextarea = document.getElementById('main_prompt_quick_edit_textarea');
+ const mainQuickEdit = createQuickEdit().from(mainPromptTextarea, mainPrompt);
+
+ const jailbreakPrompt = this.getPromptById('jailbreak');
+ const jailbreakPromptTextarea = document.getElementById('jailbreak_prompt_quick_edit_textarea');
+ const jailbreakQuickEdit = createQuickEdit().from(jailbreakPromptTextarea, jailbreakPrompt);
+
+ // Save prompt edit form to settings and close form.
+ this.handleSavePrompt = (event) => {
+ const promptId = event.target.dataset.pmPrompt;
+ const prompt = this.getPromptById(promptId);
+
+ if (null === prompt) {
+ const newPrompt = {};
+ this.updatePromptWithPromptEditForm(newPrompt);
+ this.addPrompt(newPrompt, promptId);
+ } else {
+ this.updatePromptWithPromptEditForm(prompt);
+ }
+
+ if ('main' === promptId) mainQuickEdit.update(prompt.content)
+ if ('jailbreak' === promptId) jailbreakQuickEdit.update(prompt.content)
+
+ this.log('Saved prompt: ' + promptId);
+
+ this.hidePopup();
+ this.clearEditForm();
+ this.saveServiceSettings().then(() => this.render());
+ }
+
+ // Reset prompt should it be a system prompt
+ this.handleResetPrompt = (event) => {
+ const promptId = event.target.dataset.pmPrompt;
+ const prompt = this.getPromptById(promptId);
+
+ switch (promptId) {
+ case 'main':
+ prompt.name = 'Main Prompt';
+ prompt.content = this.configuration.defaultPrompts.main;
+ break;
+ case 'nsfw':
+ prompt.name = 'Nsfw Prompt';
+ prompt.content = this.configuration.defaultPrompts.nsfw;
+ break;
+ case 'jailbreak':
+ prompt.name = 'Jailbreak Prompt';
+ prompt.content = this.configuration.defaultPrompts.jailbreak;
+ break;
+ case 'enhanceDefinitions':
+ prompt.name = 'Enhance Definitions';
+ prompt.content = this.configuration.defaultPrompts.enhanceDefinitions;
+ break;
+ }
+
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name').value = prompt.name;
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role').value = 'system';
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt').value = prompt.content;
+ }
+
+ // Append prompt to selected character
+ this.handleAppendPrompt = (event) => {
+ const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
+ const prompt = this.getPromptById(promptID);
+
+ if (prompt){
+ this.appendPrompt(prompt, this.activeCharacter);
+ this.saveServiceSettings().then(() => this.render());
+ }
+ }
+
+ // Delete selected prompt from list form and close edit form
+ this.handleDeletePrompt = (event) => {
+ const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
+ const prompt = this.getPromptById(promptID);
+
+ if (prompt && true === this.isPromptDeletionAllowed(prompt)) {
+ const promptIndex = this.getPromptIndexById(promptID);
+ this.serviceSettings.prompts.splice(Number(promptIndex), 1);
+
+ this.log('Deleted prompt: ' + prompt.identifier);
+
+ this.hidePopup();
+ this.clearEditForm();
+ this.saveServiceSettings().then(() => this.render());
+ }
+ };
+
+ // Create new prompt, then save it to settings and close form.
+ this.handleNewPrompt = (event) => {
+ const prompt = {
+ identifier: this.getUuidv4(),
+ name: '',
+ role: 'system',
+ content: ''
+ }
+
+ this.loadPromptIntoEditForm(prompt);
+ this.showPopup();
+ }
+
+ // Export all user prompts
+ this.handleFullExport = () => {
+ const exportPrompts = this.serviceSettings.prompts.reduce((userPrompts, prompt) => {
+ if (false === prompt.system_prompt && false === prompt.marker) userPrompts.push(prompt);
+ return userPrompts;
+ }, []);
+
+ this.export({prompts: exportPrompts}, 'full', 'st-prompts');
+ }
+
+ // Export user prompts and order for this character
+ this.handleCharacterExport = () => {
+ const characterPrompts = this.getPromptsForCharacter(this.activeCharacter).reduce((userPrompts, prompt) => {
+ if (false === prompt.system_prompt && !prompt.marker) userPrompts.push(prompt);
+ return userPrompts;
+ }, []);
+
+ const characterList = this.getPromptOrderForCharacter(this.activeCharacter);
+
+ const exportPrompts = {
+ prompts: characterPrompts,
+ prompt_order: characterList
+ }
+
+ const name = this.activeCharacter.name + '-prompts';
+ this.export(exportPrompts, 'character', name);
+ }
+
+ // Import prompts for the selected character
+ this.handleImport = () => {
+ callPopup('Existing prompts with the same ID will be overridden. Do you want to proceed?', 'confirm',)
+ .then(userChoice => {
+ if (false === userChoice) return;
+
+ const fileOpener = document.createElement('input');
+ fileOpener.type = 'file';
+ fileOpener.accept = '.json';
+
+ fileOpener.addEventListener('change', (event) => {
+ const file = event.target.files[0];
+ if (!file) return;
+
+ const reader = new FileReader();
+
+ reader.onload = (event) => {
+ const fileContent = event.target.result;
+
+ try {
+ const data = JSON.parse(fileContent);
+ this.import(data);
+ } catch (err) {
+ toastr.error('An error occurred while importing prompts. More info available in console.')
+ console.log('An error occurred while importing prompts');
+ console.log(err.toString());
+ }
+ };
+
+ reader.readAsText(file);
+ });
+
+ fileOpener.click();
+ });
+ }
+
+ // Restore default state of a characters prompt order
+ this.handleCharacterReset = () => {
+ callPopup('This will reset the prompt order for this character. You will not lose any prompts.', 'confirm',)
+ .then(userChoice => {
+ if (false === userChoice) return;
+
+ this.removePromptOrderForCharacter(this.activeCharacter);
+ this.addPromptOrderForCharacter(this.activeCharacter, promptManagerDefaultPromptOrder);
+
+ this.saveServiceSettings().then(() => this.render());
+ });
+ }
+
+ // Re-render when chat history changes.
+ eventSource.on(event_types.MESSAGE_DELETED, () => this.renderDebounced());
+ eventSource.on(event_types.MESSAGE_EDITED, () => this.renderDebounced());
+ eventSource.on(event_types.MESSAGE_RECEIVED, () => this.renderDebounced());
+
+ // Re-render when chatcompletion settings change
+ eventSource.on(event_types.CHATCOMPLETION_SOURCE_CHANGED, () => this.renderDebounced());
+ eventSource.on(event_types.CHATCOMPLETION_MODEL_CHANGED, () => this.renderDebounced());
+
+ // Re-render when the character changes.
+ eventSource.on('chatLoaded', (event) => {
+ this.handleCharacterSelected(event)
+ this.saveServiceSettings().then(() => this.renderDebounced());
+ });
+
+ // Re-render when the character gets edited.
+ eventSource.on(event_types.CHARACTER_EDITED, (event) => {
+ this.handleCharacterUpdated(event);
+ this.saveServiceSettings().then(() => this.renderDebounced());
+ })
+
+ // Re-render when the group changes.
+ eventSource.on('groupSelected', (event) => {
+ this.handleGroupSelected(event)
+ this.saveServiceSettings().then(() => this.renderDebounced());
+ });
+
+ // Sanitize settings after character has been deleted.
+ eventSource.on('characterDeleted', (event) => {
+ this.handleCharacterDeleted(event)
+ this.saveServiceSettings().then(() => this.renderDebounced());
+ });
+
+ // Trigger re-render when token settings are changed
+ document.getElementById('openai_max_context').addEventListener('change', (event) => {
+ this.serviceSettings.openai_max_context = event.target.value;
+ if (this.activeCharacter) this.renderDebounced();
+ });
+
+ document.getElementById('openai_max_tokens').addEventListener('change', (event) => {
+ if (this.activeCharacter) this.renderDebounced();
+ });
+
+ // Prepare prompt edit form buttons
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_save').addEventListener('click', this.handleSavePrompt);
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_reset').addEventListener('click', this.handleResetPrompt);
+
+ const closeAndClearPopup = () => {
+ this.hidePopup();
+ this.clearEditForm();
+ this.clearInspectForm();
+ };
+
+ // Clear forms on closing the popup
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_close').addEventListener('click', closeAndClearPopup);
+ document.getElementById(this.configuration.prefix + 'prompt_manager_popup_close_button').addEventListener('click', closeAndClearPopup);
+
+ // Re-render prompt manager on openai preset change
+ eventSource.on(event_types.OAI_PRESET_CHANGED, settings => this.renderDebounced());
+
+ // Close popup on preset change
+ eventSource.on(event_types.OAI_PRESET_CHANGED, () => {
+ this.hidePopup();
+ this.clearEditForm();
+ });
+
+ // Re-render prompt manager on world settings update
+ eventSource.on(event_types.WORLDINFO_SETTINGS_UPDATED, () => this.renderDebounced());
+
+ this.log('Initialized')
+};
+
+/**
+ * Main rendering function
+ *
+ * @param afterTryGenerate - Whether a dry run should be attempted before rendering
+ */
+PromptManagerModule.prototype.render = function (afterTryGenerate = true) {
+ if (main_api !== 'openai') return;
+
+ if (null === this.activeCharacter) return;
+ this.error = null;
+
+ if (true === afterTryGenerate) {
+ // Executed during dry-run for determining context composition
+ this.profileStart('filling context');
+ this.tryGenerate().then(() => {
+ this.profileEnd('filling context');
+ this.profileStart('render');
+ this.renderPromptManager();
+ this.renderPromptManagerListItems()
+ this.makeDraggable();
+ this.profileEnd('render');
+ });
+ } else {
+ // Executed during live communication
+ this.profileStart('render');
+ this.renderPromptManager();
+ this.renderPromptManagerListItems()
+ this.makeDraggable();
+ this.profileEnd('render');
+ }
+}
+
+/**
+ * Update a prompt with the values from the HTML form.
+ * @param {object} prompt - The prompt to be updated.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.updatePromptWithPromptEditForm = function (prompt) {
+ prompt.name = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name').value;
+ prompt.role = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role').value;
+ prompt.content = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt').value;
+}
+
+/**
+ * Find a prompt by its identifier and update it with the provided object.
+ * @param {string} identifier - The identifier of the prompt.
+ * @param {object} updatePrompt - An object with properties to be updated in the prompt.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.updatePromptByIdentifier = function (identifier, updatePrompt) {
+ let prompt = this.serviceSettings.prompts.find((item) => identifier === item.identifier);
+ if (prompt) prompt = Object.assign(prompt, updatePrompt);
+}
+
+/**
+ * Iterate over an array of prompts, find each one by its identifier, and update them with the provided data.
+ * @param {object[]} prompts - An array of prompt updates.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.updatePrompts = function (prompts) {
+ prompts.forEach((update) => {
+ let prompt = this.getPromptById(update.identifier);
+ if (prompt) Object.assign(prompt, update);
+ })
+}
+
+PromptManagerModule.prototype.getTokenHandler = function() {
+ return this.tokenHandler;
+}
+
+/**
+ * Add a prompt to the current character's prompt list.
+ * @param {object} prompt - The prompt to be added.
+ * @param {object} character - The character whose prompt list will be updated.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.appendPrompt = function (prompt, character) {
+ const promptOrder = this.getPromptOrderForCharacter(character);
+ const index = promptOrder.findIndex(entry => entry.identifier === prompt.identifier);
+
+ if (-1 === index) promptOrder.push({identifier: prompt.identifier, enabled: false});
+}
+
+/**
+ * Remove a prompt from the current character's prompt list.
+ * @param {object} prompt - The prompt to be removed.
+ * @param {object} character - The character whose prompt list will be updated.
+ * @returns {void}
+ */
+// Remove a prompt from the current characters prompt list
+PromptManagerModule.prototype.detachPrompt = function (prompt, character) {
+ const promptOrder = this.getPromptOrderForCharacter(character);
+ const index = promptOrder.findIndex(entry => entry.identifier === prompt.identifier);
+ if (-1 === index) return;
+ promptOrder.splice(index, 1)
+}
+
+/**
+ * Create a new prompt and add it to the list of prompts.
+ * @param {object} prompt - The prompt to be added.
+ * @param {string} identifier - The identifier for the new prompt.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.addPrompt = function (prompt, identifier) {
+
+ if (typeof prompt !== 'object' || prompt === null) throw new Error('Object is not a prompt');
+
+ const newPrompt = {
+ identifier: identifier,
+ system_prompt: false,
+ enabled: false,
+ marker: false,
+ ...prompt
+ }
+
+ this.serviceSettings.prompts.push(newPrompt);
+}
+
+/**
+ * Sanitize the service settings, ensuring each prompt has a unique identifier.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.sanitizeServiceSettings = function () {
+ this.serviceSettings.prompts = this.serviceSettings.prompts ?? [];
+ this.serviceSettings.prompt_order = this.serviceSettings.prompt_order ?? [];
+
+ // Check whether the referenced prompts are present.
+ this.serviceSettings.prompts.length === 0
+ ? this.setPrompts(chatCompletionDefaultPrompts.prompts)
+ : this.checkForMissingPrompts(this.serviceSettings.prompts);
+
+ // Add identifiers if there are none assigned to a prompt
+ this.serviceSettings.prompts.forEach(prompt => prompt && (prompt.identifier = prompt.identifier ?? this.getUuidv4()));
+
+ if (this.activeCharacter) {
+ const promptReferences = this.getPromptOrderForCharacter(this.activeCharacter);
+ for(let i = promptReferences.length - 1; i >= 0; i--) {
+ const reference = promptReferences[i];
+ if(-1 === this.serviceSettings.prompts.findIndex(prompt => prompt.identifier === reference.identifier)) {
+ promptReferences.splice(i, 1);
+ this.log('Removed unused reference: ' + reference.identifier);
+ }
+ }
+ }
+};
+
+/**
+ * Checks whether entries of a characters prompt order are orphaned
+ * and if all mandatory system prompts for a character are present.
+ *
+ * @param prompts
+ */
+PromptManagerModule.prototype.checkForMissingPrompts = function(prompts) {
+ const defaultPromptIdentifiers = chatCompletionDefaultPrompts.prompts.reduce((list, prompt) => { list.push(prompt.identifier); return list;}, []);
+
+ const missingIdentifiers = defaultPromptIdentifiers.filter(identifier =>
+ !prompts.some(prompt =>prompt.identifier === identifier)
+ );
+
+ missingIdentifiers.forEach(identifier => {
+ const defaultPrompt = chatCompletionDefaultPrompts.prompts.find(prompt => prompt?.identifier === identifier);
+ if (defaultPrompt) {
+ prompts.push(defaultPrompt);
+ this.log(`Missing system prompt: ${defaultPrompt.identifier}. Added default.`);
+ }
+ });
+};
+
+/**
+ * Check whether a prompt can be inspected.
+ * @param {object} prompt - The prompt to check.
+ * @returns {boolean} True if the prompt is a marker, false otherwise.
+ */
+PromptManagerModule.prototype.isPromptInspectionAllowed = function (prompt) {
+ return true;
+}
+
+/**
+ * Check whether a prompt can be deleted. System prompts cannot be deleted.
+ * @param {object} prompt - The prompt to check.
+ * @returns {boolean} True if the prompt can be deleted, false otherwise.
+ */
+PromptManagerModule.prototype.isPromptDeletionAllowed = function (prompt) {
+ return false === prompt.system_prompt;
+}
+
+/**
+ * Check whether a prompt can be edited.
+ * @param {object} prompt - The prompt to check.
+ * @returns {boolean} True if the prompt can be edited, false otherwise.
+ */
+PromptManagerModule.prototype.isPromptEditAllowed = function (prompt) {
+ return !prompt.marker;
+}
+
+/**
+ * Check whether a prompt can be toggled on or off.
+ * @param {object} prompt - The prompt to check.
+ * @returns {boolean} True if the prompt can be deleted, false otherwise.
+ */
+PromptManagerModule.prototype.isPromptToggleAllowed = function (prompt) {
+ return prompt.marker ? false : !this.configuration.toggleDisabled.includes(prompt.identifier);
+}
+
+/**
+ * Handle the deletion of a character by removing their prompt list and nullifying the active character if it was the one deleted.
+ * @param {object} event - The event object containing the character's ID.
+ * @returns boolean
+ */
+PromptManagerModule.prototype.handleCharacterDeleted = function (event) {
+ this.removePromptOrderForCharacter(this.activeCharacter);
+ if (this.activeCharacter.id === event.detail.id) this.activeCharacter = null;
+}
+
+/**
+ * Handle the selection of a character by setting them as the active character and setting up their prompt list if necessary.
+ * @param {object} event - The event object containing the character's ID and character data.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.handleCharacterSelected = function (event) {
+ this.activeCharacter = {id: event.detail.id, ...event.detail.character};
+ const promptOrder = this.getPromptOrderForCharacter(this.activeCharacter);
+
+ // ToDo: These should be passed as parameter or attached to the manager as a set of default options.
+ // Set default prompts and order for character.
+ if (0 === promptOrder.length) this.addPromptOrderForCharacter(this.activeCharacter, promptManagerDefaultPromptOrder);
+}
+
+/**
+ * Set the most recently selected character
+ *
+ * @param event
+ */
+PromptManagerModule.prototype.handleCharacterUpdated = function (event) {
+ this.activeCharacter = {id: event.detail.id, ...event.detail.character};
+}
+
+/**
+ * Set the most recently selected character group
+ *
+ * @param event
+ */
+PromptManagerModule.prototype.handleGroupSelected = function (event) {
+ const characterDummy = {id: event.detail.id, group: event.detail.group};
+ this.activeCharacter = characterDummy;
+ const promptOrder = this.getPromptOrderForCharacter(characterDummy);
+
+ if (0 === promptOrder.length) this.addPromptOrderForCharacter(characterDummy, promptManagerDefaultPromptOrder)
+}
+
+/**
+ * Get a list of group characters, regardless of whether they are active or not.
+ *
+ * @returns {string[]}
+ */
+PromptManagerModule.prototype.getActiveGroupCharacters = function() {
+ // ToDo: Ideally, this should return the actual characters.
+ return (this.activeCharacter?.group?.members || []).map(member => member.substring(0, member.lastIndexOf('.')));
+}
+
+/**
+ * Get the prompts for a specific character. Can be filtered to only include enabled prompts.
+ * @returns {object[]} The prompts for the character.
+ * @param character
+ * @param onlyEnabled
+ */
+PromptManagerModule.prototype.getPromptsForCharacter = function (character, onlyEnabled = false) {
+ return this.getPromptOrderForCharacter(character)
+ .map(item => true === onlyEnabled ? (true === item.enabled ? this.getPromptById(item.identifier) : null) : this.getPromptById(item.identifier))
+ .filter(prompt => null !== prompt);
+}
+
+/**
+ * Get the order of prompts for a specific character. If no character is specified or the character doesn't have a prompt list, an empty array is returned.
+ * @param {object|null} character - The character to get the prompt list for.
+ * @returns {object[]} The prompt list for the character, or an empty array.
+ */
+PromptManagerModule.prototype.getPromptOrderForCharacter = function (character) {
+ return !character ? [] : (this.serviceSettings.prompt_order.find(list => String(list.character_id) === String(character.id))?.order ?? []);
+}
+
+/**
+ * Set the prompts for the manager.
+ * @param {object[]} prompts - The prompts to be set.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.setPrompts = function (prompts) {
+ this.serviceSettings.prompts = prompts;
+}
+
+/**
+ * Remove the prompt list for a specific character.
+ * @param {object} character - The character whose prompt list will be removed.
+ * @returns {void}
+ */
+PromptManagerModule.prototype.removePromptOrderForCharacter = function (character) {
+ const index = this.serviceSettings.prompt_order.findIndex(list => String(list.character_id) === String(character.id));
+ if (-1 !== index) this.serviceSettings.prompt_order.splice(index, 1);
+}
+
+/**
+ * Adds a new prompt list for a specific character.
+ * @param {Object} character - Object with at least an `id` property
+ * @param {Array