Merge pull request #3185 from SillyTavern/inject-filter Inject filter

f9eb720f2a823db170137f229b0fa031dd265a5e

Cohee <18619528+Cohee1207@users.noreply.github.com>

Signed
4 files changed, +149 -47Ignore whitespace
public/script.js+75 -33
@@ -2873,23 +2873,54 @@ function addPersonaDescriptionExtensionPrompt() {
28732873 }
28742874}
28752875
2876-function getAllExtensionPrompts() {
2876+/**
2877- const value = Object
2877+ * Returns all extension prompts combined.
2878- .values(extension_prompts)
2878+ * @returns {Promise<string>} Combined extension prompts
2879- .filter(x => x.value)
2879+ */
2880- .map(x => x.value.trim())
2880+async function getAllExtensionPrompts() {
2881- .join('\n');
2881+ const values = [];
2882+
2883+ for (const prompt of Object.values(extension_prompts)) {
2884+ const value = prompt?.value?.trim();
2885+
2886+ if (!value) {
2887+ continue;
2888+ }
28822889
2883- return value.length ? substituteParams(value) : '';
2890+ const hasFilter = typeof prompt.filter === 'function';
2891+ if (hasFilter && !await prompt.filter()) {
2892+ continue;
2893+ }
2894+
2895+ values.push(value);
2896+ }
2897+
2898+ return substituteParams(values.join('\n'));
28842899}
28852900
2886-// Wrapper to fetch extension prompts by module name
2901+/**
2887-export function getExtensionPromptByName(moduleName) {
2902+ * Wrapper to fetch extension prompts by module name
2888- if (moduleName) {
2903+ * @param {string} moduleName Module name
2889- return substituteParams(extension_prompts[moduleName]?.value);
2904+ * @returns {Promise<string>} Extension prompt
2890- } else {
2905+ */
2891- return;
2906+export async function getExtensionPromptByName(moduleName) {
2907+ if (!moduleName) {
2908+ return '';
2909+ }
2910+
2911+ const prompt = extension_prompts[moduleName];
2912+
2913+ if (!prompt) {
2914+ return '';
28922915 }
2916+
2917+ const hasFilter = typeof prompt.filter === 'function';
2918+
2919+ if (hasFilter && !await prompt.filter()) {
2920+ return '';
2921+ }
2922+
2923+ return substituteParams(prompt.value);
28932924}
28942925
28952926/**
@@ -2900,27 +2931,36 @@ export function getExtensionPromptByName(moduleName) {
29002931 * @param {string} [separator] Separator for joining multiple prompts
29012932 * @param {number} [role] Role of the prompt
29022933 * @param {boolean} [wrap] Wrap start and end with a separator
29032934 * @returns {Promise<string>} Extension prompt
29042935 */
29052936export async function getExtensionPrompt(position = extension_prompt_types.IN_PROMPT, depth = undefined, separator = '\n', role = undefined, wrap = true) {
2906- let extension_prompt = Object.keys(extension_prompts)
2937+ const filterByFunction = async (prompt) => {
2938+ const hasFilter = typeof prompt.filter === 'function';
2939+ if (hasFilter && !await prompt.filter()) {
2940+ return false;
2941+ }
2942+ return true;
2943+ };
2944+ const promptPromises = Object.keys(extension_prompts)
29072945 .sort()
29082946 .map((x) => extension_prompts[x])
29092947 .filter(x => x.position == position && x.value)
29102948 .filter(x => depth === undefined || x.depth === undefined || x.depth === depth)
29112949 .filter(x => role === undefined || x.role === undefined || x.role === role)
2912- .map(x => x.value.trim())
2950+ .filter(filterByFunction);
2913- .join(separator);
2951+ const prompts = await Promise.all(promptPromises);
2914- if (wrap && extension_prompt.length && !extension_prompt.startsWith(separator)) {
2952+
2915- extension_prompt = separator + extension_prompt;
2953+ let values = prompts.map(x => x.value.trim()).join(separator);
2954+ if (wrap && values.length && !values.startsWith(separator)) {
2955+ values = separator + values;
29162956 }
29172957 if (wrap && extension_promptvalues.length && !extension_promptvalues.endsWith(separator)) {
29182958 extension_promptvalues = extension_promptvalues + separator;
29192959 }
29202960 if (extension_promptvalues.length) {
29212961 extension_promptvalues = substituteParams(extension_promptvalues);
29222962 }
29232963 return extension_promptvalues;
29242964}
29252965
29262966export function baseChatReplace(value, name1, name2) {
@@ -3834,7 +3874,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
38343874 // Inject all Depth prompts. Chat Completion does it separately
38353875 let injectedIndices = [];
38363876 if (main_api !== 'openai') {
38373877 injectedIndices = await doChatInject(coreChat, isContinue);
38383878 }
38393879
38403880 // Insert character jailbreak as the last user message (if exists, allowed, preferred, and not using Chat Completion)
@@ -3907,8 +3947,8 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
39073947 }
39083948
39093949 // Call combined AN into Generate
39103950 const beforeScenarioAnchor = (await getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT)).trimStart();
39113951 const afterScenarioAnchor = await getExtensionPrompt(extension_prompt_types.IN_PROMPT);
39123952
39133953 const storyStringParams = {
39143954 description: description,
@@ -4471,7 +4511,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
44714511 ...thisPromptBits[currentArrayEntry],
44724512 rawPrompt: generate_data.prompt || generate_data.input,
44734513 mesId: getNextMessageId(type),
44744514 allAnchors: await getAllExtensionPrompts(),
44754515 chatInjects: injectedIndices?.map(index => arrMes[arrMes.length - index - 1])?.join('') || '',
44764516 summarizeString: (extension_prompts['1_memory']?.value || ''),
44774517 authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''),
@@ -4740,9 +4780,9 @@ export function stopGeneration() {
47404780 * Injects extension prompts into chat messages.
47414781 * @param {object[]} messages Array of chat messages
47424782 * @param {boolean} isContinue Whether the generation is a continuation. If true, the extension prompts of depth 0 are injected at position 1.
47434783 * @returns {Promise<number[]>} Array of indices where the extension prompts were injected
47444784 */
47454785async function doChatInject(messages, isContinue) {
47464786 const injectedIndices = [];
47474787 let totalInsertedMessages = 0;
47484788 messages.reverse();
@@ -4760,7 +4800,7 @@ function doChatInject(messages, isContinue) {
47604800 const wrap = false;
47614801
47624802 for (const role of roles) {
47634803 const extensionPrompt = String(await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, role, wrap)).trimStart();
47644804 const isNarrator = role === extension_prompt_roles.SYSTEM;
47654805 const isUser = role === extension_prompt_roles.USER;
47664806 const name = names[role];
@@ -7453,14 +7493,16 @@ function select_rm_characters() {
74537493 * @param {number} depth Insertion depth. 0 represets the last message in context. Expected values up to MAX_INJECTION_DEPTH.
74547494 * @param {number} role Extension prompt role. Defaults to SYSTEM.
74557495 * @param {boolean} scan Should the prompt be included in the world info scan.
7496+ * @param {(function(): Promise<boolean>|boolean)} filter Filter function to determine if the prompt should be injected.
74567497 */
74577498export function setExtensionPrompt(key, value, position, depth, scan = false, role = extension_prompt_roles.SYSTEM, filter = null) {
74587499 extension_prompts[key] = {
74597500 value: String(value),
74607501 position: Number(position),
74617502 depth: Number(depth),
74627503 scan: !!scan,
74637504 role: Number(role ?? extension_prompt_roles.SYSTEM),
7505+ filter: filter,
74647506 };
74657507}
74667508
public/scripts/openai.js+10 -6
@@ -611,8 +611,9 @@ function formatWorldInfo(value) {
611611 *
612612 * @param {Prompt[]} prompts - Array containing injection prompts.
613613 * @param {Object[]} messages - Array containing all messages.
614+ * @returns {Promise<Object[]>} - Array containing all messages with injections.
614615 */
615616async function populationInjectionPrompts(prompts, messages) {
616617 let totalInsertedMessages = 0;
617618
618619 const roleTypes = {
@@ -635,7 +636,7 @@ function populationInjectionPrompts(prompts, messages) {
635636 // Get prompts for current role
636637 const rolePrompts = depthPrompts.filter(prompt => prompt.role === role).map(x => x.content).join(separator);
637638 // Get extension prompt
638639 const extensionPrompt = await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, roleTypes[role], wrap);
639640
640641 const jointPrompt = [rolePrompts, extensionPrompt].filter(x => x).map(x => x.trim()).join(separator);
641642
@@ -1020,7 +1021,7 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
10201021 }
10211022
10221023 // Add in-chat injections
10231024 messages = await populationInjectionPrompts(absolutePrompts, messages);
10241025
10251026 // Decide whether dialogue examples should always be added
10261027 if (power_user.pin_examples) {
@@ -1051,9 +1052,9 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
10511052 * @param {string} options.systemPromptOverride
10521053 * @param {string} options.jailbreakPromptOverride
10531054 * @param {string} options.personaDescription
10541055 * @returns {Promise<Object>} prompts - The prepared and merged system and user-defined prompts.
10551056 */
10561057async function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, worldInfoBefore, worldInfoAfter, charDescription, quietPrompt, bias, extensionPrompts, systemPromptOverride, jailbreakPromptOverride, personaDescription }) {
10571058 const scenarioText = Scenario && oai_settings.scenario_format ? substituteParams(oai_settings.scenario_format) : '';
10581059 const charPersonalityText = charPersonality && oai_settings.personality_format ? substituteParams(oai_settings.personality_format) : '';
10591060 const groupNudge = substituteParams(oai_settings.group_nudge_prompt);
@@ -1142,6 +1143,9 @@ function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, wor
11421143 if (!extensionPrompts[key].value) continue;
11431144 if (![extension_prompt_types.BEFORE_PROMPT, extension_prompt_types.IN_PROMPT].includes(prompt.position)) continue;
11441145
1146+ const hasFilter = typeof prompt.filter === 'function';
1147+ if (hasFilter && !await prompt.filter()) continue;
1148+
11451149 systemPrompts.push({
11461150 identifier: key.replace(/\W/g, '_'),
11471151 position: getPromptPosition(prompt.position),
@@ -1254,7 +1258,7 @@ export async function prepareOpenAIMessages({
12541258
12551259 try {
12561260 // Merge markers and ordered user prompts with system prompts
12571261 const prompts = await preparePromptsForChatCompletion({
12581262 Scenario,
12591263 charPersonality,
12601264 name2,
public/scripts/slash-commands.js+63 -7
@@ -84,6 +84,25 @@ export const parser = new SlashCommandParser();
8484const registerSlashCommand = SlashCommandParser.addCommand.bind(SlashCommandParser);
8585const getSlashCommandsHelp = parser.getHelpString.bind(parser);
8686
87+/**
88+ * Converts a SlashCommandClosure to a filter function that returns a boolean.
89+ * @param {SlashCommandClosure} closure
90+ * @returns {() => Promise<boolean>}
91+ */
92+function closureToFilter(closure) {
93+ return async () => {
94+ try {
95+ const localClosure = closure.getCopy();
96+ localClosure.onProgress = () => { };
97+ const result = await localClosure.execute();
98+ return isTrueBoolean(result.pipe);
99+ } catch (e) {
100+ console.error('Error executing filter closure', e);
101+ return false;
102+ }
103+ };
104+}
105+
87106export function initDefaultSlashCommands() {
88107 SlashCommandParser.addCommandObject(SlashCommand.fromProps({
89108 name: '?',
@@ -1611,6 +1630,13 @@ export function initDefaultSlashCommands() {
16111630 new SlashCommandNamedArgument(
16121631 'ephemeral', 'remove injection after generation', [ARGUMENT_TYPE.BOOLEAN], false, false, 'false',
16131632 ),
1633+ SlashCommandNamedArgument.fromProps({
1634+ name: 'filter',
1635+ description: 'if a filter is defined, an injection will only be performed if the closure returns true',
1636+ typeList: [ARGUMENT_TYPE.CLOSURE],
1637+ isRequired: false,
1638+ acceptsMultiple: false,
1639+ }),
16141640 ],
16151641 unnamedArgumentList: [
16161642 new SlashCommandArgument(
@@ -1901,6 +1927,11 @@ const NARRATOR_NAME_DEFAULT = 'System';
19011927export const COMMENT_NAME_DEFAULT = 'Note';
19021928const SCRIPT_PROMPT_KEY = 'script_inject_';
19031929
1930+/**
1931+ * Adds a new script injection to the chat.
1932+ * @param {import('./slash-commands/SlashCommand.js').NamedArguments} args Named arguments
1933+ * @param {import('./slash-commands/SlashCommand.js').UnnamedArguments} value Unnamed argument
1934+ */
19041935function injectCallback(args, value) {
19051936 const positions = {
19061937 'before': extension_prompt_types.BEFORE_PROMPT,
@@ -1914,8 +1945,8 @@ function injectCallback(args, value) {
19141945 'assistant': extension_prompt_roles.ASSISTANT,
19151946 };
19161947
19171948 const id = String(args?.id);
19181949 const ephemeral = isTrueBoolean(String(args?.ephemeral));
19191950
19201951 if (!id) {
19211952 console.warn('WARN: No ID provided for /inject command');
@@ -1931,9 +1962,15 @@ function injectCallback(args, value) {
19311962 const depth = isNaN(depthValue) ? defaultDepth : depthValue;
19321963 const roleValue = typeof args?.role === 'string' ? args.role.toLowerCase().trim() : Number(args?.role ?? extension_prompt_roles.SYSTEM);
19331964 const role = roles[roleValue] ?? roles[extension_prompt_roles.SYSTEM];
19341965 const scan = isTrueBoolean(String(args?.scan));
1966+ const filter = args?.filter instanceof SlashCommandClosure ? args.filter.rawText : null;
1967+ const filterFunction = args?.filter instanceof SlashCommandClosure ? closureToFilter(args.filter) : null;
19351968 value = value || '';
19361969
1970+ if (args?.filter && !String(filter ?? '').trim()) {
1971+ throw new Error('Failed to parse the filter argument. Make sure it is a valid non-empty closure.');
1972+ }
1973+
19371974 const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`;
19381975
19391976 if (!chat_metadata.script_injects) {
@@ -1941,13 +1978,13 @@ function injectCallback(args, value) {
19411978 }
19421979
19431980 if (value) {
19441981 const inject = { value, position, depth, scan, role, filter };
19451982 chat_metadata.script_injects[id] = inject;
19461983 } else {
19471984 delete chat_metadata.script_injects[id];
19481985 }
19491986
19501987 setExtensionPrompt(prefixedId, String(value), position, depth, scan, role, filterFunction);
19511988 saveMetadataDebounced();
19521989
19531990 if (ephemeral) {
@@ -1958,7 +1995,7 @@ function injectCallback(args, value) {
19581995 }
19591996 console.log('Removing ephemeral script injection', id);
19601997 delete chat_metadata.script_injects[id];
19611998 setExtensionPrompt(prefixedId, '', position, depth, scan, role, filterFunction);
19621999 saveMetadataDebounced();
19632000 deleted = true;
19642001 };
@@ -2053,9 +2090,28 @@ export function processChatSlashCommands() {
20532090 }
20542091
20552092 for (const [id, inject] of Object.entries(context.chatMetadata.script_injects)) {
2093+ /**
2094+ * Rehydrates a filter closure from a string.
2095+ * @returns {SlashCommandClosure | null}
2096+ */
2097+ function reviveFilterClosure() {
2098+ if (!inject.filter) {
2099+ return null;
2100+ }
2101+
2102+ try {
2103+ return new SlashCommandParser().parse(inject.filter, true);
2104+ } catch (error) {
2105+ console.warn('Failed to revive filter closure for script injection', id, error);
2106+ return null;
2107+ }
2108+ }
2109+
20562110 const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`;
2111+ const filterClosure = reviveFilterClosure();
2112+ const filter = filterClosure ? closureToFilter(filterClosure) : null;
20572113 console.log('Adding script injection', id);
20582114 setExtensionPrompt(prefixedId, inject.value, inject.position, inject.depth, inject.scan, inject.role, filter);
20592115 }
20602116}
20612117
public/scripts/world-info.js+1 -1
@@ -3760,7 +3760,7 @@ export async function checkWorldInfo(chat, maxContext, isDryRun) {
37603760 // Put this code here since otherwise, the chat reference is modified
37613761 for (const key of Object.keys(context.extensionPrompts)) {
37623762 if (context.extensionPrompts[key]?.scan) {
37633763 const prompt = await getExtensionPromptByName(key);
37643764 if (prompt) {
37653765 buffer.addInject(prompt);
37663766 }