Merge branch 'staging' of https://github.com/SillyTavern/SillyTavern into staging

This commit is contained in:
Cohee
2023-11-05 21:54:23 +02:00
15 changed files with 770 additions and 261 deletions

View File

@ -268,11 +268,11 @@ async function RA_autoloadchat() {
let active_character_id = Object.keys(characters).find(key => characters[key].avatar === active_character);
if (active_character_id !== null) {
selectCharacterById(String(active_character_id));
await selectCharacterById(String(active_character_id));
}
if (active_group != null) {
openGroupById(String(active_group));
await openGroupById(String(active_group));
}
// if the character list hadn't been loaded yet, try again.

View File

@ -33,7 +33,7 @@
<small data-i18n="Replace With">Replace With</small>
</label>
<div>
<textarea
<textarea
class="regex_replace_string text_pole wide100p textarea_compact"
placeholder="Use {{match}} to include the matched text from the Find Regex"
rows="2"
@ -45,7 +45,7 @@
<small data-i18n="Trim Out">Trim Out</small>
</label>
<div>
<textarea
<textarea
class="regex_trim_strings text_pole wide100p textarea_compact"
placeholder="Globally trims any unwanted parts from a regex match before replacement. Separate each element by an enter."
rows="3"
@ -86,6 +86,10 @@
<input type="checkbox" name="only_format_display" />
<span data-i18n="Only Format Display">Only Format Display</span>
</label>
<label class="checkbox flex-container" title="Chat history won't change, only the prompt as the request is sent (on generation)">
<input type="checkbox" name="only_format_prompt"/>
<span data-i18n="Only Format Prompt (?)">Only Format Prompt (?)</span>
</label>
<label class="checkbox flex-container">
<input type="checkbox" name="run_on_edit" />
<span data-i18n="Run On Edit">Run On Edit</span>

View File

@ -24,12 +24,12 @@ function regexFromString(input) {
try {
// Parse input
var m = input.match(/(\/?)(.+)\1([a-z]*)/i);
// Invalid flags
if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
return RegExp(input);
}
// Create the regular expression
return new RegExp(m[2], m[3]);
} catch {
@ -38,19 +38,24 @@ function regexFromString(input) {
}
// Parent function to fetch a regexed version of a raw string
function getRegexedString(rawString, placement, { characterOverride, isMarkdown } = {}) {
function getRegexedString(rawString, placement, { characterOverride, isMarkdown, isPrompt } = {}) {
let finalString = rawString;
if (extension_settings.disabledExtensions.includes("regex") || !rawString || placement === undefined) {
return finalString;
}
extension_settings.regex.forEach((script) => {
if ((script.markdownOnly && !isMarkdown) || (!script.markdownOnly && isMarkdown)) {
return;
}
if (script.placement.includes(placement)) {
finalString = runRegexScript(script, finalString, { characterOverride });
if (
// Script applies to Markdown and input is Markdown
(script.markdownOnly && isMarkdown) ||
// Script applies to Generate and input is Generate
(script.promptOnly && isPrompt) ||
// Script applies to all cases when neither "only"s are true, but there's no need to do it when `isMarkdown`, the as source (chat history) should already be changed beforehand
(!script.markdownOnly && !script.promptOnly && !isMarkdown)
) {
if (script.placement.includes(placement)) {
finalString = runRegexScript(script, finalString, { characterOverride });
}
}
});
@ -91,7 +96,7 @@ function runRegexScript(regexScript, rawString, { characterOverride } = {}) {
const subReplaceString = substituteRegexParams(
regexScript.replaceString,
trimCapturedMatch ?? trimFencedMatch,
{
{
characterOverride,
replaceStrategy: regexScript.replaceStrategy ?? regex_replace_strategy.REPLACE
}

View File

@ -113,6 +113,9 @@ async function onRegexEditorOpenClick(existingId) {
editorHtml
.find(`input[name="only_format_display"]`)
.prop("checked", existingScript.markdownOnly ?? false);
editorHtml
.find(`input[name="only_format_prompt"]`)
.prop("checked", existingScript.promptOnly ?? false);
editorHtml
.find(`input[name="run_on_edit"]`)
.prop("checked", existingScript.runOnEdit ?? false);
@ -165,6 +168,10 @@ async function onRegexEditorOpenClick(existingId) {
editorHtml
.find(`input[name="only_format_display"]`)
.prop("checked"),
promptOnly:
editorHtml
.find(`input[name="only_format_prompt"]`)
.prop("checked"),
runOnEdit:
editorHtml
.find(`input[name="run_on_edit"]`)
@ -197,6 +204,7 @@ function migrateSettings() {
script.placement = script.placement.filter((e) => e !== regex_placement.MD_DISPLAY);
script.markdownOnly = true
script.promptOnly = true
performSave = true;
}

View File

@ -68,6 +68,7 @@ import {
setExternalAbortController,
baseChatReplace,
depth_prompt_depth_default,
loadItemizedPrompts,
} from "../script.js";
import { appendTagToList, createTagMapFromList, getTagsList, applyTagsOnCharacterSelect, tag_map, printTagFilters } from './tags.js';
import { FILTER_TYPES, FilterHelper } from './filters.js';
@ -168,6 +169,8 @@ export async function getGroupChat(groupId) {
const chat_id = group.chat_id;
const data = await loadGroupChat(chat_id);
await loadItemizedPrompts(getCurrentChatId());
if (Array.isArray(data) && data.length) {
data[0].is_group = true;
for (let key of data) {
@ -913,10 +916,10 @@ async function deleteGroup(id) {
}
if (response.ok) {
await clearChat();
selected_group = null;
delete tag_map[id];
resetChatState();
clearChat();
await printMessages();
await getCharacters();
@ -1385,12 +1388,12 @@ export async function openGroupById(groupId) {
if (!is_send_press && !is_group_generating) {
if (selected_group !== groupId) {
await clearChat();
cancelTtsPlay();
selected_group = groupId;
setCharacterId(undefined);
setCharacterName('');
setEditedMessageId(undefined);
clearChat();
updateChatMetadata({}, true);
chat.length = 0;
await getGroupChat(groupId);
@ -1484,7 +1487,7 @@ export async function createNewGroupChat(groupId) {
group.past_metadata = {};
}
clearChat();
await clearChat();
chat.length = 0;
if (oldChatName) {
group.past_metadata[oldChatName] = Object.assign({}, chat_metadata);
@ -1537,7 +1540,7 @@ export async function openGroupChat(groupId, chatId) {
return;
}
clearChat();
await clearChat();
chat.length = 0;
const previousChat = group.chat_id;
group.past_metadata[previousChat] = Object.assign({}, chat_metadata);

View File

@ -25,6 +25,9 @@ import {
event_types,
substituteParams,
MAX_INJECTION_DEPTH,
getStoppingStrings,
getNextMessageId,
replaceItemizedPromptText,
} from "../script.js";
import { groups, selected_group } from "./group-chats.js";
@ -367,14 +370,19 @@ function convertChatCompletionToInstruct(messages, type) {
}
const isImpersonate = type === 'impersonate';
const isContinue = type === 'continue';
const promptName = isImpersonate ? name1 : name2;
const promptLine = formatInstructModePrompt(promptName, isImpersonate, '', name1, name2).trimStart();
const promptLine = isContinue ? '' : formatInstructModePrompt(promptName, isImpersonate, '', name1, name2).trimStart();
const prompt = [systemPromptText, examplesText, chatMessagesText, promptLine]
let prompt = [systemPromptText, examplesText, chatMessagesText, promptLine]
.filter(x => x)
.map(x => x.endsWith('\n') ? x : `${x}\n`)
.join('');
if (isContinue) {
prompt = prompt.replace(/\n$/, '');
}
return prompt;
}
@ -578,6 +586,10 @@ function populationInjectionPrompts(prompts) {
openai_msgs = openai_msgs.reverse();
}
export function isOpenRouterWithInstruct() {
return oai_settings.chat_completion_source === chat_completion_sources.OPENROUTER && oai_settings.openrouter_force_instruct && power_user.instruct.enabled;
}
/**
* Populates the chat history of the conversation.
*
@ -604,7 +616,8 @@ function populateChatHistory(prompts, chatCompletion, type = null, cyclePrompt =
// Reserve budget for continue nudge
let continueMessage = null;
if (type === 'continue' && cyclePrompt) {
const instruct = isOpenRouterWithInstruct();
if (type === 'continue' && cyclePrompt && !instruct) {
const continuePrompt = new Prompt({
identifier: 'continueNudge',
role: 'system',
@ -1249,7 +1262,7 @@ function saveModelList(data) {
}
}
async function sendAltScaleRequest(openai_msgs_tosend, logit_bias, signal) {
async function sendAltScaleRequest(openai_msgs_tosend, logit_bias, signal, type) {
const generate_url = '/generate_altscale';
let firstSysMsgs = []
@ -1269,6 +1282,8 @@ async function sendAltScaleRequest(openai_msgs_tosend, logit_bias, signal) {
}, "");
openai_msgs_tosend = substituteParams(joinedSubsequentMsgs);
const messageId = getNextMessageId(type);
replaceItemizedPromptText(messageId, openai_msgs_tosend);
const generate_data = {
sysprompt: joinedSysMsgs,
@ -1304,6 +1319,7 @@ async function sendOpenAIRequest(type, openai_msgs_tosend, signal) {
openai_msgs_tosend = openai_msgs_tosend.filter(msg => msg && typeof msg === 'object');
let logit_bias = {};
const messageId = getNextMessageId(type);
const isClaude = oai_settings.chat_completion_source == chat_completion_sources.CLAUDE;
const isOpenRouter = oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER;
const isScale = oai_settings.chat_completion_source == chat_completion_sources.SCALE;
@ -1317,6 +1333,7 @@ async function sendOpenAIRequest(type, openai_msgs_tosend, signal) {
if (isTextCompletion && isOpenRouter) {
openai_msgs_tosend = convertChatCompletionToInstruct(openai_msgs_tosend, type);
replaceItemizedPromptText(messageId, openai_msgs_tosend);
}
if (isAI21 || isPalm) {
@ -1325,6 +1342,7 @@ async function sendOpenAIRequest(type, openai_msgs_tosend, signal) {
return acc + (prefix ? (selected_group ? "\n" : prefix + " ") : "") + obj.content + "\n";
}, "");
openai_msgs_tosend = substituteParams(joinedMsgs) + (isImpersonate ? `${name1}:` : `${name2}:`);
replaceItemizedPromptText(messageId, openai_msgs_tosend);
}
// If we're using the window.ai extension, use that instead
@ -1343,7 +1361,7 @@ async function sendOpenAIRequest(type, openai_msgs_tosend, signal) {
}
if (isScale && oai_settings.use_alt_scale) {
return sendAltScaleRequest(openai_msgs_tosend, logit_bias, signal)
return sendAltScaleRequest(openai_msgs_tosend, logit_bias, signal, type);
}
const model = getChatCompletionModel();
@ -1382,6 +1400,10 @@ async function sendOpenAIRequest(type, openai_msgs_tosend, signal) {
generate_data['use_openrouter'] = true;
generate_data['top_k'] = Number(oai_settings.top_k_openai);
generate_data['use_fallback'] = oai_settings.openrouter_use_fallback;
if (isTextCompletion) {
generate_data['stop'] = getStoppingStrings(isImpersonate);
}
}
if (isScale) {

View File

@ -162,6 +162,7 @@ let power_user = {
max_context_unlocked: false,
message_token_count_enabled: false,
expand_message_actions: false,
enableZenSliders: false,
prefer_character_prompt: true,
prefer_character_jailbreak: true,
quick_continue: false,
@ -251,6 +252,7 @@ const storage_keys = {
mesIDDisplay_enabled: 'mesIDDisplayEnabled',
message_token_count_enabled: 'MessageTokenCountEnabled',
expand_message_actions: 'ExpandMessageActions',
enableZenSliders: 'enableZenSliders',
};
const contextControls = [
@ -419,6 +421,148 @@ function switchMessageActions() {
$('.extraMesButtons, .extraMesButtonsHint').removeAttr('style');
}
async function switchZenSliders() {
const value = localStorage.getItem(storage_keys.enableZenSliders);
power_user.enableZenSliders = value === null ? false : value == "true";
$("body").toggleClass("enableZenSliders", power_user.enableZenSliders);
$("#enableZenSliders").prop("checked", power_user.enableZenSliders);
function revertOriginalSliders() {
$("#range_block_textgenerationwebui input[type='number']").show();
$("#textgenerationwebui_api-settings input[type='number']").show();
$("#pro-settings-block input[type='number']").show();
$(`#range_block_textgenerationwebui input[type='range'],
#textgenerationwebui_api-settings input[type='range'],
#pro-settings-block input[type='range']`).each(function () {
$(this).show();
});
$('div[id$="_zenslider"]').remove();
}
if (power_user.enableZenSliders) {
$("#range_block_textgenerationwebui input[type='number']").hide();
$("#textgenerationwebui_api-settings input[type='number']").hide();
$("#pro-settings-block input[type='number']").hide();
$("#seed_textgenerationwebui").show();
$(`#range_block_textgenerationwebui input[type='range'],
#textgenerationwebui_api-settings input[type='range'],
#pro-settings-block input[type='range']`).each(
function () {
CreateZenSliders($(this))
}
)
} else {
revertOriginalSliders();
}
async function CreateZenSliders(elmnt) {
await delay(100)
var originalSlider = elmnt;
var sliderID = originalSlider.attr('id')
var sliderMin = Number(originalSlider.attr('min'))
var sliderMax = Number(originalSlider.attr('max'))
var sliderValue = originalSlider.val();
var sliderRange = sliderMax - sliderMin
var midpoint = sliderRange / 2
var numSteps = 10
var decimals = 2
if (sliderID == 'rep_pen_range_textgenerationwebui') {
numSteps = 16
decimals = 0
}
if (sliderID == 'amount_gen') {
decimals = 0
}
if (sliderID == 'max_context') {
numSteps = 15
decimals = 0
}
if (sliderID == 'encoder_rep_pen_textgenerationwebui') {
numSteps = 14
}
if (sliderID == 'mirostat_mode_textgenerationwebui') {
numSteps = 2
decimals = 0
}
if (sliderID == 'mirostat_tau_textgenerationwebui' ||
sliderID == 'top_k_textgenerationwebui' ||
sliderID == 'num_beams_textgenerationwebui' ||
sliderID == 'no_repeat_ngram_size_textgenerationwebui') {
numSteps = 20
decimals = 0
}
if (sliderID == 'epsilon_cutoff_textgenerationwebui') {
numSteps = 20
decimals = 1
}
if (sliderID == 'tfs_textgenerationwebui' ||
sliderID == 'min_p_textgenerationwebui') {
numSteps = 20
decimals = 2
}
if (sliderID == 'mirostat_eta_textgenerationwebui' ||
sliderID == 'penalty_alpha_textgenerationwebui' ||
sliderID == 'length_penalty_textgenerationwebui') {
numSteps = 50
}
if (sliderID == 'eta_cutoff_textgenerationwebui') {
numSteps = 50
decimals = 1
}
if (sliderID == 'guidance_scale_textgenerationwebui') {
numSteps = 78
}
if (sliderID == 'min_length_textgenerationwebui') {
decimals = 0
}
if (sliderID == 'temp_textgenerationwebui') {
numSteps = 20
}
var stepScale = sliderRange / numSteps
var newSlider = $("<div>")
.attr('id', `${sliderID}_zenslider`)
.css("width", "100%")
.insertBefore(originalSlider);
newSlider.slider({
value: sliderValue,
step: stepScale,
min: sliderMin,
max: sliderMax,
create: function () {
var handle = $(this).find(".ui-slider-handle");
var handleText = Number(sliderValue).toFixed(decimals)
handle.text(handleText);
//var width = handle.width()
var stepNumber = ((sliderValue - sliderMin) / stepScale)
var leftMargin = (stepNumber / numSteps) * 50 * -1
handle.css('margin-left', `${leftMargin}px`)
},
slide: function (event, ui) {
var handle = $(this).find(".ui-slider-handle");
//var width = handle.outerWidth()
handle.text(ui.value.toFixed(decimals));
var stepNumber = ((ui.value - sliderMin) / stepScale)
var leftMargin = (stepNumber / numSteps) * 50 * -1
handle.css('margin-left', `${leftMargin}px`)
let handleText = (ui.value)
originalSlider.val(handleText);
originalSlider.trigger('input')
originalSlider.trigger('change')
}
});
originalSlider.data("newSlider", newSlider);
originalSlider.hide();
};
}
function switchUiMode() {
const fastUi = localStorage.getItem(storage_keys.fast_ui_mode);
power_user.fast_ui_mode = fastUi === null ? true : fastUi == "true";
@ -780,6 +924,13 @@ async function applyTheme(name) {
switchMessageActions();
}
},
{
key: 'enableZenSliders',
action: async () => {
localStorage.setItem(storage_keys.enableZenSliders, Boolean(power_user.enableZenSliders));
switchMessageActions();
}
},
{
key: 'hotswap_enabled',
action: async () => {
@ -894,6 +1045,7 @@ function loadPowerUserSettings(settings, data) {
const timestamps = localStorage.getItem(storage_keys.timestamps_enabled);
const mesIDDisplay = localStorage.getItem(storage_keys.mesIDDisplay_enabled);
const expandMessageActions = localStorage.getItem(storage_keys.expand_message_actions);
const enableZenSliders = localStorage.getItem(storage_keys.enableZenSliders);
power_user.fast_ui_mode = fastUi === null ? true : fastUi == "true";
power_user.movingUI = movingUI === null ? false : movingUI == "true";
power_user.noShadows = noShadows === null ? false : noShadows == "true";
@ -902,6 +1054,7 @@ function loadPowerUserSettings(settings, data) {
power_user.timestamps_enabled = timestamps === null ? true : timestamps == "true";
power_user.mesIDDisplay_enabled = mesIDDisplay === null ? true : mesIDDisplay == "true";
power_user.expand_message_actions = expandMessageActions === null ? true : expandMessageActions == "true";
power_user.enableZenSliders = enableZenSliders === null ? false : enableZenSliders == "true";
power_user.avatar_style = Number(localStorage.getItem(storage_keys.avatar_style) ?? avatar_styles.ROUND);
//power_user.chat_display = Number(localStorage.getItem(storage_keys.chat_display) ?? chat_styles.DEFAULT);
power_user.chat_width = Number(localStorage.getItem(storage_keys.chat_width) ?? 50);
@ -983,6 +1136,7 @@ function loadPowerUserSettings(settings, data) {
$("#mesIDDisplayEnabled").prop("checked", power_user.mesIDDisplay_enabled);
$("#prefer_character_prompt").prop("checked", power_user.prefer_character_prompt);
$("#prefer_character_jailbreak").prop("checked", power_user.prefer_character_jailbreak);
$("#enableZenSliders").prop('checked', power_user.enableZenSliders).trigger('input');
$(`input[name="avatar_style"][value="${power_user.avatar_style}"]`).prop("checked", true);
$(`#chat_display option[value=${power_user.chat_display}]`).attr("selected", true).trigger('change');
$('#chat_width_slider').val(power_user.chat_width);
@ -1402,7 +1556,7 @@ async function saveTheme() {
mesIDDisplay_enabled: power_user.mesIDDisplay_enabled,
message_token_count_enabled: power_user.message_token_count_enabled,
expand_message_actions: power_user.expand_message_actions,
enableZenSliders: power_user.enableZenSliders,
hotswap_enabled: power_user.hotswap_enabled,
custom_css: power_user.custom_css,
@ -2346,6 +2500,13 @@ $(document).ready(() => {
switchMessageActions();
});
$("#enableZenSliders").on("input", function () {
const value = !!$(this).prop('checked');
power_user.enableZenSliders = value;
localStorage.setItem(storage_keys.enableZenSliders, Boolean(power_user.enableZenSliders));
switchZenSliders();
});
$("#mesIDDisplayEnabled").on("input", function () {
const value = !!$(this).prop('checked');
power_user.mesIDDisplay_enabled = value;

View File

@ -639,21 +639,34 @@ async function sendCommentMessage(_, text) {
await saveChatConditional();
}
/**
* Displays a help message from the slash command
* @param {any} _ Unused
* @param {string} type Type of help to display
*/
function helpCommandCallback(_, type) {
switch (type?.trim()) {
switch (type?.trim()?.toLowerCase()) {
case 'slash':
case 'commands':
case 'slashes':
case 'slash commands':
case '1':
sendSystemMessage(system_message_types.SLASH_COMMANDS);
break;
case 'format':
case 'formatting':
case 'formats':
case 'chat formatting':
case '2':
sendSystemMessage(system_message_types.FORMATTING);
break;
case 'hotkeys':
case 'hotkey':
case '3':
sendSystemMessage(system_message_types.HOTKEYS);
break;
case 'macros':
case 'macro':
case '4':
sendSystemMessage(system_message_types.MACROS);
break;

View File

@ -29,6 +29,7 @@ export const textgen_types = {
const textgenerationwebui_settings = {
temp: 0.7,
temperature_last: true,
top_p: 0.5,
top_k: 40,
top_a: 0,
@ -36,6 +37,7 @@ const textgenerationwebui_settings = {
epsilon_cutoff: 0,
eta_cutoff: 0,
typical_p: 1,
min_p: 0,
rep_pen: 1.2,
rep_pen_range: 0,
no_repeat_ngram_size: 0,
@ -81,6 +83,7 @@ export let textgenerationwebui_preset_names = [];
const setting_names = [
"temp",
"temperature_last",
"rep_pen",
"rep_pen_range",
"no_repeat_ngram_size",
@ -91,6 +94,7 @@ const setting_names = [
"epsilon_cutoff",
"eta_cutoff",
"typical_p",
"min_p",
"penalty_alpha",
"num_beams",
"length_penalty",
@ -122,7 +126,7 @@ const setting_names = [
//'prompt_log_probs_aphrodite'
];
function selectPreset(name) {
async function selectPreset(name) {
const preset = textgenerationwebui_presets[textgenerationwebui_preset_names.indexOf(name)];
if (!preset) {
@ -351,6 +355,14 @@ function setSettingByName(i, value, trigger) {
const val = parseFloat(value);
$(`#${i}_textgenerationwebui`).val(val);
$(`#${i}_counter_textgenerationwebui`).val(val);
if (power_user.enableZenSliders) {
let zenSlider = $(`#${i}_textgenerationwebui_zenslider`).slider()
zenSlider.slider('option', 'value', val)
zenSlider.slider('option', 'slide')
.call(zenSlider, null, {
handle: $('.ui-slider-handle', zenSlider), value: val
});
}
}
if (trigger) {
@ -446,8 +458,10 @@ export function getTextGenGenerationData(finalPrompt, this_amount_gen, isImperso
'max_new_tokens': this_amount_gen,
'do_sample': textgenerationwebui_settings.do_sample,
'temperature': textgenerationwebui_settings.temp,
'temperature_last': textgenerationwebui_settings.temperature_last,
'top_p': textgenerationwebui_settings.top_p,
'typical_p': textgenerationwebui_settings.typical_p,
'min_p': textgenerationwebui_settings.min_p,
'repetition_penalty': textgenerationwebui_settings.rep_pen,
'repetition_penalty_range': textgenerationwebui_settings.rep_pen_range,
'encoder_repetition_penalty': textgenerationwebui_settings.encoder_rep_pen,

View File

@ -12,6 +12,8 @@ export {
world_info,
world_info_budget,
world_info_depth,
world_info_min_activations,
world_info_min_activations_depth_max,
world_info_recursive,
world_info_overflow_alert,
world_info_case_sensitive,
@ -35,6 +37,9 @@ let world_info = {};
let selected_world_info = [];
let world_names;
let world_info_depth = 2;
let world_info_min_activations = 0; // if > 0, will continue seeking chat until minimum world infos are activated
let world_info_min_activations_depth_max = 0; // used when (world_info_min_activations > 0)
let world_info_budget = 25;
let world_info_recursive = false;
let world_info_overflow_alert = false;
@ -55,14 +60,14 @@ const worldInfoFilter = new FilterHelper(() => updateEditor());
const SORT_ORDER_KEY = 'world_info_sort_order';
const METADATA_KEY = 'world_info';
const InputWidthReference = $("#WIInputWidthReference");
const DEFAULT_DEPTH = 4;
export function getWorldInfoSettings() {
return {
world_info,
world_info_depth,
world_info_min_activations,
world_info_min_activations_depth_max,
world_info_budget,
world_info_recursive,
world_info_overflow_alert,
@ -102,6 +107,10 @@ async function getWorldInfoPrompt(chat2, maxContext) {
function setWorldInfoSettings(settings, data) {
if (settings.world_info_depth !== undefined)
world_info_depth = Number(settings.world_info_depth);
if (settings.world_info_min_activations !== undefined)
world_info_min_activations = Number(settings.world_info_min_activations);
if (settings.world_info_min_activations_depth_max !== undefined)
world_info_min_activations_depth_max = Number(settings.world_info_min_activations_depth_max);
if (settings.world_info_budget !== undefined)
world_info_budget = Number(settings.world_info_budget);
if (settings.world_info_recursive !== undefined)
@ -138,6 +147,12 @@ function setWorldInfoSettings(settings, data) {
$("#world_info_depth_counter").val(world_info_depth);
$("#world_info_depth").val(world_info_depth);
$("#world_info_min_activations_counter").val(world_info_min_activations);
$("#world_info_min_activations").val(world_info_min_activations);
$("#world_info_min_activations_depth_max_counter").val(world_info_min_activations_depth_max);
$("#world_info_min_activations_depth_max").val(world_info_min_activations_depth_max);
$("#world_info_budget_counter").val(world_info_budget);
$("#world_info_budget").val(world_info_budget);
@ -367,24 +382,23 @@ function displayWorldEntries(name, data, navigation = navigation_option.none) {
<small class="flex1">
Title/Memo
</small>
<small style="width:${InputWidthReference.width() + 5 + 'px'}">
<small style="width: calc(3.5em + 5px)">
Status
</small>
<small style="width:${InputWidthReference.width() + 20 + 'px'}">
<small style="width: calc(3.5em + 20px)">
Position
</small>
<small style="width:${InputWidthReference.width() + 15 + 'px'}">
<small style="width: calc(3.5em + 15px)">
Depth
</small>
<small style="width:${InputWidthReference.width() + 15 + 'px'}">
<small style="width: calc(3.5em + 15px)">
Order
</small>
<small style="width:${InputWidthReference.width() + 15 + 'px'}">
<small style="width: calc(3.5em + 15px)">
Trigger %
</small>
</div>`
const blocks = page.map(entry => getWorldEntry(name, data, entry));
const blocks = page.map(entry => getWorldEntry(name, data, entry)).filter(x => x);
$("#world_popup_entries_list").append(keywordHeaders);
$("#world_popup_entries_list").append(blocks);
},
@ -545,6 +559,10 @@ function deleteOriginalDataValue(data, uid) {
}
function getWorldEntry(name, data, entry) {
if (!data.entries[entry.uid]) {
return;
}
const template = $("#entry_edit_template .world_entry").clone();
template.data("uid", entry.uid);
template.attr("uid", entry.uid);
@ -819,7 +837,7 @@ function getWorldEntry(name, data, entry) {
saveWorldInfo(name, data);
});
orderInput.val(entry.order).trigger("input");
orderInput.width(InputWidthReference.width() + 15 + 'px')
orderInput.css('width', 'calc(3em + 15px)');
// probability
if (entry.probability === undefined) {
@ -840,7 +858,7 @@ function getWorldEntry(name, data, entry) {
saveWorldInfo(name, data);
});
depthInput.val(entry.depth ?? DEFAULT_DEPTH).trigger("input");
depthInput.width(InputWidthReference.width() + 15 + 'px');
depthInput.css('width', 'calc(3em + 15px)');
// Hide by default unless depth is specified
if (entry.position === world_info_position.atDepth) {
@ -868,7 +886,7 @@ function getWorldEntry(name, data, entry) {
saveWorldInfo(name, data);
});
probabilityInput.val(entry.probability).trigger("input");
probabilityInput.width(InputWidthReference.width() + 15 + 'px')
probabilityInput.css('width', 'calc(3em + 15px)');
// probability toggle
if (entry.useProbability === undefined) {
@ -1379,6 +1397,7 @@ async function checkWorldInfo(chat, maxContext) {
// Combine the chat
let textToScan = chat.slice(0, messagesToLookBack).join("");
let minActivationMsgIndex = messagesToLookBack; // tracks chat index to satisfy `world_info_min_activations`
// Add the depth or AN if enabled
// Put this code here since otherwise, the chat reference is modified
@ -1402,6 +1421,7 @@ async function checkWorldInfo(chat, maxContext) {
textToScan = transformString(textToScan);
let needsToScan = true;
let token_budget_overflowed = false;
let count = 0;
let allActivatedEntries = new Set();
let failedProbabilityChecks = new Set();
@ -1531,6 +1551,7 @@ async function checkWorldInfo(chat, maxContext) {
toastr.warning(`World info budget reached after ${allActivatedEntries.size} entries.`, 'World Info');
}
needsToScan = false;
token_budget_overflowed = true;
break;
}
@ -1553,6 +1574,24 @@ async function checkWorldInfo(chat, maxContext) {
textToScan = (currentlyActivatedText + '\n' + textToScan);
allActivatedText = (currentlyActivatedText + '\n' + allActivatedText);
}
// world_info_min_activations
if (!needsToScan && !token_budget_overflowed) {
if (world_info_min_activations > 0 && (allActivatedEntries.size < world_info_min_activations)) {
let over_max = false
over_max = (
world_info_min_activations_depth_max > 0 &&
minActivationMsgIndex > world_info_min_activations_depth_max
) || (
minActivationMsgIndex >= chat.length
)
if (!over_max) {
needsToScan = true
textToScan = transformString(chat.slice(minActivationMsgIndex, minActivationMsgIndex + 1).join(""));
minActivationMsgIndex += 1
}
}
}
}
// Forward-sorted list of entries for joining
@ -2027,7 +2066,7 @@ jQuery(() => {
$("#world_editor_select").on('change', async () => {
$("#world_info_search").val('');
worldInfoFilter.setFilterData(FILTER_TYPES.WORLD_INFO_SEARCH, '', true);
const selectedIndex = $("#world_editor_select").find(":selected").val();
const selectedIndex = String($("#world_editor_select").find(":selected").val());
if (selectedIndex === "") {
hideWorldEditor();
@ -2042,27 +2081,39 @@ jQuery(() => {
eventSource.emit(event_types.WORLDINFO_SETTINGS_UPDATED);
}
$(document).on("input", "#world_info_depth", function () {
$("#world_info_depth").on('input', function () {
world_info_depth = Number($(this).val());
$("#world_info_depth_counter").val($(this).val());
saveSettings();
});
$(document).on("input", "#world_info_budget", function () {
$("#world_info_min_activations").on('input', function () {
world_info_min_activations = Number($(this).val());
$("#world_info_min_activations_counter").val($(this).val());
saveSettings();
});
$("#world_info_min_activations_depth_max").on('input', function () {
world_info_min_activations_depth_max = Number($(this).val());
$("#world_info_min_activations_depth_max_counter").val($(this).val());
saveSettings();
});
$("#world_info_budget").on('input', function () {
world_info_budget = Number($(this).val());
$("#world_info_budget_counter").val($(this).val());
saveSettings();
});
$(document).on("input", "#world_info_recursive", function () {
$("#world_info_recursive").on('input', function () {
world_info_recursive = !!$(this).prop('checked');
saveSettings();
})
});
$('#world_info_case_sensitive').on('input', function () {
world_info_case_sensitive = !!$(this).prop('checked');
saveSettings();
})
});
$('#world_info_match_whole_words').on('input', function () {
world_info_match_whole_words = !!$(this).prop('checked');