Merge pull request #3185 from SillyTavern/inject-filter Inject filter
Signed| @@ -2873,23 +2873,54 @@ function addPersonaDescriptionExtensionPrompt() { | ||
| 2873 | 2873 | } |
| 2874 | 2874 | } |
| 2875 | 2875 | |
| 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 | 2882 | |
| 2883 | - return value.length ? substituteParams(value) : ''; | |
| 2883 | + for (const prompt of Object.values(extension_prompts)) { | |
| 2884 | + const value = prompt?.value?.trim(); | |
| 2885 | + | |
| 2886 | + if (!value) { | |
| 2887 | + continue; | |
| 2884 | 2888 | } |
| 2885 | 2889 | |
| 2886 | -// Wrapper to fetch extension prompts by module name | |
| 2890 | + const hasFilter = typeof prompt.filter === 'function'; | |
| 2887 | -export function getExtensionPromptByName(moduleName) { | |
| 2891 | + if (hasFilter && !await prompt.filter()) { | |
| 2888 | - if (moduleName) { | |
| 2892 | + continue; | |
| 2889 | - return substituteParams(extension_prompts[moduleName]?.value); | |
| 2890 | - } else { | |
| 2891 | - return; | |
| 2892 | 2893 | } |
| 2894 | + | |
| 2895 | + values.push(value); | |
| 2896 | + } | |
| 2897 | + | |
| 2898 | + return substituteParams(values.join('\n')); | |
| 2899 | +} | |
| 2900 | + | |
| 2901 | +/** | |
| 2902 | + * Wrapper to fetch extension prompts by module name | |
| 2903 | + * @param {string} moduleName Module name | |
| 2904 | + * @returns {Promise<string>} Extension prompt | |
| 2905 | + */ | |
| 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 ''; | |
| 2915 | + } | |
| 2916 | + | |
| 2917 | + const hasFilter = typeof prompt.filter === 'function'; | |
| 2918 | + | |
| 2919 | + if (hasFilter && !await prompt.filter()) { | |
| 2920 | + return ''; | |
| 2921 | + } | |
| 2922 | + | |
| 2923 | + return substituteParams(prompt.value); | |
| 2893 | 2924 | } |
| 2894 | 2925 | |
| 2895 | 2926 | /** |
| @@ -2900,27 +2931,36 @@ export function getExtensionPromptByName(moduleName) { | ||
| 2900 | 2931 | * @param {string} [separator] Separator for joining multiple prompts |
| 2901 | 2932 | * @param {number} [role] Role of the prompt |
| 2902 | 2933 | * @param {boolean} [wrap] Wrap start and end with a separator |
| 2903 | 2934 | * @returns {Promise<string>} Extension prompt |
| 2904 | 2935 | */ |
| 2905 | 2936 | export 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) | |
| 2907 | 2945 | .sort() |
| 2908 | 2946 | .map((x) => extension_prompts[x]) |
| 2909 | 2947 | .filter(x => x.position == position && x.value) |
| 2910 | 2948 | .filter(x => depth === undefined || x.depth === undefined || x.depth === depth) |
| 2911 | 2949 | .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; | |
| 2916 | 2956 | } |
| 2917 | 2957 | if (wrap && extension_promptvalues.length && !extension_promptvalues.endsWith(separator)) { |
| 2918 | 2958 | extension_promptvalues = extension_promptvalues + separator; |
| 2919 | 2959 | } |
| 2920 | 2960 | if (extension_promptvalues.length) { |
| 2921 | 2961 | extension_promptvalues = substituteParams(extension_promptvalues); |
| 2922 | 2962 | } |
| 2923 | 2963 | return extension_promptvalues; |
| 2924 | 2964 | } |
| 2925 | 2965 | |
| 2926 | 2966 | export function baseChatReplace(value, name1, name2) { |
| @@ -3834,7 +3874,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro | ||
| 3834 | 3874 | // Inject all Depth prompts. Chat Completion does it separately |
| 3835 | 3875 | let injectedIndices = []; |
| 3836 | 3876 | if (main_api !== 'openai') { |
| 3837 | 3877 | injectedIndices = await doChatInject(coreChat, isContinue); |
| 3838 | 3878 | } |
| 3839 | 3879 | |
| 3840 | 3880 | // 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 | ||
| 3907 | 3947 | } |
| 3908 | 3948 | |
| 3909 | 3949 | // Call combined AN into Generate |
| 3910 | 3950 | const beforeScenarioAnchor = (await getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT)).trimStart(); |
| 3911 | 3951 | const afterScenarioAnchor = await getExtensionPrompt(extension_prompt_types.IN_PROMPT); |
| 3912 | 3952 | |
| 3913 | 3953 | const storyStringParams = { |
| 3914 | 3954 | description: description, |
| @@ -4471,7 +4511,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro | ||
| 4471 | 4511 | ...thisPromptBits[currentArrayEntry], |
| 4472 | 4512 | rawPrompt: generate_data.prompt || generate_data.input, |
| 4473 | 4513 | mesId: getNextMessageId(type), |
| 4474 | 4514 | allAnchors: await getAllExtensionPrompts(), |
| 4475 | 4515 | chatInjects: injectedIndices?.map(index => arrMes[arrMes.length - index - 1])?.join('') || '', |
| 4476 | 4516 | summarizeString: (extension_prompts['1_memory']?.value || ''), |
| 4477 | 4517 | authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''), |
| @@ -4740,9 +4780,9 @@ export function stopGeneration() { | ||
| 4740 | 4780 | * Injects extension prompts into chat messages. |
| 4741 | 4781 | * @param {object[]} messages Array of chat messages |
| 4742 | 4782 | * @param {boolean} isContinue Whether the generation is a continuation. If true, the extension prompts of depth 0 are injected at position 1. |
| 4743 | 4783 | * @returns {Promise<number[]>} Array of indices where the extension prompts were injected |
| 4744 | 4784 | */ |
| 4745 | 4785 | async function doChatInject(messages, isContinue) { |
| 4746 | 4786 | const injectedIndices = []; |
| 4747 | 4787 | let totalInsertedMessages = 0; |
| 4748 | 4788 | messages.reverse(); |
| @@ -4760,7 +4800,7 @@ function doChatInject(messages, isContinue) { | ||
| 4760 | 4800 | const wrap = false; |
| 4761 | 4801 | |
| 4762 | 4802 | for (const role of roles) { |
| 4763 | 4803 | const extensionPrompt = String(await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, role, wrap)).trimStart(); |
| 4764 | 4804 | const isNarrator = role === extension_prompt_roles.SYSTEM; |
| 4765 | 4805 | const isUser = role === extension_prompt_roles.USER; |
| 4766 | 4806 | const name = names[role]; |
| @@ -7453,14 +7493,16 @@ function select_rm_characters() { | ||
| 7453 | 7493 | * @param {number} depth Insertion depth. 0 represets the last message in context. Expected values up to MAX_INJECTION_DEPTH. |
| 7454 | 7494 | * @param {number} role Extension prompt role. Defaults to SYSTEM. |
| 7455 | 7495 | * @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. | |
| 7456 | 7497 | */ |
| 7457 | 7498 | export function setExtensionPrompt(key, value, position, depth, scan = false, role = extension_prompt_roles.SYSTEM, filter = null) { |
| 7458 | 7499 | extension_prompts[key] = { |
| 7459 | 7500 | value: String(value), |
| 7460 | 7501 | position: Number(position), |
| 7461 | 7502 | depth: Number(depth), |
| 7462 | 7503 | scan: !!scan, |
| 7463 | 7504 | role: Number(role ?? extension_prompt_roles.SYSTEM), |
| 7505 | + filter: filter, | |
| 7464 | 7506 | }; |
| 7465 | 7507 | } |
| 7466 | 7508 | |
| @@ -611,8 +611,9 @@ function formatWorldInfo(value) { | ||
| 611 | 611 | * |
| 612 | 612 | * @param {Prompt[]} prompts - Array containing injection prompts. |
| 613 | 613 | * @param {Object[]} messages - Array containing all messages. |
| 614 | + * @returns {Promise<Object[]>} - Array containing all messages with injections. | |
| 614 | 615 | */ |
| 615 | 616 | async function populationInjectionPrompts(prompts, messages) { |
| 616 | 617 | let totalInsertedMessages = 0; |
| 617 | 618 | |
| 618 | 619 | const roleTypes = { |
| @@ -635,7 +636,7 @@ function populationInjectionPrompts(prompts, messages) { | ||
| 635 | 636 | // Get prompts for current role |
| 636 | 637 | const rolePrompts = depthPrompts.filter(prompt => prompt.role === role).map(x => x.content).join(separator); |
| 637 | 638 | // Get extension prompt |
| 638 | 639 | const extensionPrompt = await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, roleTypes[role], wrap); |
| 639 | 640 | |
| 640 | 641 | const jointPrompt = [rolePrompts, extensionPrompt].filter(x => x).map(x => x.trim()).join(separator); |
| 641 | 642 | |
| @@ -1020,7 +1021,7 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm | ||
| 1020 | 1021 | } |
| 1021 | 1022 | |
| 1022 | 1023 | // Add in-chat injections |
| 1023 | 1024 | messages = await populationInjectionPrompts(absolutePrompts, messages); |
| 1024 | 1025 | |
| 1025 | 1026 | // Decide whether dialogue examples should always be added |
| 1026 | 1027 | if (power_user.pin_examples) { |
| @@ -1051,9 +1052,9 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm | ||
| 1051 | 1052 | * @param {string} options.systemPromptOverride |
| 1052 | 1053 | * @param {string} options.jailbreakPromptOverride |
| 1053 | 1054 | * @param {string} options.personaDescription |
| 1054 | 1055 | * @returns {Promise<Object>} prompts - The prepared and merged system and user-defined prompts. |
| 1055 | 1056 | */ |
| 1056 | 1057 | async function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, worldInfoBefore, worldInfoAfter, charDescription, quietPrompt, bias, extensionPrompts, systemPromptOverride, jailbreakPromptOverride, personaDescription }) { |
| 1057 | 1058 | const scenarioText = Scenario && oai_settings.scenario_format ? substituteParams(oai_settings.scenario_format) : ''; |
| 1058 | 1059 | const charPersonalityText = charPersonality && oai_settings.personality_format ? substituteParams(oai_settings.personality_format) : ''; |
| 1059 | 1060 | const groupNudge = substituteParams(oai_settings.group_nudge_prompt); |
| @@ -1142,6 +1143,9 @@ function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, wor | ||
| 1142 | 1143 | if (!extensionPrompts[key].value) continue; |
| 1143 | 1144 | if (![extension_prompt_types.BEFORE_PROMPT, extension_prompt_types.IN_PROMPT].includes(prompt.position)) continue; |
| 1144 | 1145 | |
| 1146 | + const hasFilter = typeof prompt.filter === 'function'; | |
| 1147 | + if (hasFilter && !await prompt.filter()) continue; | |
| 1148 | + | |
| 1145 | 1149 | systemPrompts.push({ |
| 1146 | 1150 | identifier: key.replace(/\W/g, '_'), |
| 1147 | 1151 | position: getPromptPosition(prompt.position), |
| @@ -1254,7 +1258,7 @@ export async function prepareOpenAIMessages({ | ||
| 1254 | 1258 | |
| 1255 | 1259 | try { |
| 1256 | 1260 | // Merge markers and ordered user prompts with system prompts |
| 1257 | 1261 | const prompts = await preparePromptsForChatCompletion({ |
| 1258 | 1262 | Scenario, |
| 1259 | 1263 | charPersonality, |
| 1260 | 1264 | name2, |
| @@ -84,6 +84,25 @@ export const parser = new SlashCommandParser(); | ||
| 84 | 84 | const registerSlashCommand = SlashCommandParser.addCommand.bind(SlashCommandParser); |
| 85 | 85 | const getSlashCommandsHelp = parser.getHelpString.bind(parser); |
| 86 | 86 | |
| 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 | + | |
| 87 | 106 | export function initDefaultSlashCommands() { |
| 88 | 107 | SlashCommandParser.addCommandObject(SlashCommand.fromProps({ |
| 89 | 108 | name: '?', |
| @@ -1611,6 +1630,13 @@ export function initDefaultSlashCommands() { | ||
| 1611 | 1630 | new SlashCommandNamedArgument( |
| 1612 | 1631 | 'ephemeral', 'remove injection after generation', [ARGUMENT_TYPE.BOOLEAN], false, false, 'false', |
| 1613 | 1632 | ), |
| 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 | + }), | |
| 1614 | 1640 | ], |
| 1615 | 1641 | unnamedArgumentList: [ |
| 1616 | 1642 | new SlashCommandArgument( |
| @@ -1901,6 +1927,11 @@ const NARRATOR_NAME_DEFAULT = 'System'; | ||
| 1901 | 1927 | export const COMMENT_NAME_DEFAULT = 'Note'; |
| 1902 | 1928 | const SCRIPT_PROMPT_KEY = 'script_inject_'; |
| 1903 | 1929 | |
| 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 | + */ | |
| 1904 | 1935 | function injectCallback(args, value) { |
| 1905 | 1936 | const positions = { |
| 1906 | 1937 | 'before': extension_prompt_types.BEFORE_PROMPT, |
| @@ -1914,8 +1945,8 @@ function injectCallback(args, value) { | ||
| 1914 | 1945 | 'assistant': extension_prompt_roles.ASSISTANT, |
| 1915 | 1946 | }; |
| 1916 | 1947 | |
| 1917 | 1948 | const id = String(args?.id); |
| 1918 | 1949 | const ephemeral = isTrueBoolean(String(args?.ephemeral)); |
| 1919 | 1950 | |
| 1920 | 1951 | if (!id) { |
| 1921 | 1952 | console.warn('WARN: No ID provided for /inject command'); |
| @@ -1931,9 +1962,15 @@ function injectCallback(args, value) { | ||
| 1931 | 1962 | const depth = isNaN(depthValue) ? defaultDepth : depthValue; |
| 1932 | 1963 | const roleValue = typeof args?.role === 'string' ? args.role.toLowerCase().trim() : Number(args?.role ?? extension_prompt_roles.SYSTEM); |
| 1933 | 1964 | const role = roles[roleValue] ?? roles[extension_prompt_roles.SYSTEM]; |
| 1934 | 1965 | 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; | |
| 1935 | 1968 | value = value || ''; |
| 1936 | 1969 | |
| 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 | + | |
| 1937 | 1974 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; |
| 1938 | 1975 | |
| 1939 | 1976 | if (!chat_metadata.script_injects) { |
| @@ -1941,13 +1978,13 @@ function injectCallback(args, value) { | ||
| 1941 | 1978 | } |
| 1942 | 1979 | |
| 1943 | 1980 | if (value) { |
| 1944 | 1981 | const inject = { value, position, depth, scan, role, filter }; |
| 1945 | 1982 | chat_metadata.script_injects[id] = inject; |
| 1946 | 1983 | } else { |
| 1947 | 1984 | delete chat_metadata.script_injects[id]; |
| 1948 | 1985 | } |
| 1949 | 1986 | |
| 1950 | 1987 | setExtensionPrompt(prefixedId, String(value), position, depth, scan, role, filterFunction); |
| 1951 | 1988 | saveMetadataDebounced(); |
| 1952 | 1989 | |
| 1953 | 1990 | if (ephemeral) { |
| @@ -1958,7 +1995,7 @@ function injectCallback(args, value) { | ||
| 1958 | 1995 | } |
| 1959 | 1996 | console.log('Removing ephemeral script injection', id); |
| 1960 | 1997 | delete chat_metadata.script_injects[id]; |
| 1961 | 1998 | setExtensionPrompt(prefixedId, '', position, depth, scan, role, filterFunction); |
| 1962 | 1999 | saveMetadataDebounced(); |
| 1963 | 2000 | deleted = true; |
| 1964 | 2001 | }; |
| @@ -2053,9 +2090,28 @@ export function processChatSlashCommands() { | ||
| 2053 | 2090 | } |
| 2054 | 2091 | |
| 2055 | 2092 | 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 | + | |
| 2056 | 2110 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; |
| 2111 | + const filterClosure = reviveFilterClosure(); | |
| 2112 | + const filter = filterClosure ? closureToFilter(filterClosure) : null; | |
| 2057 | 2113 | console.log('Adding script injection', id); |
| 2058 | 2114 | setExtensionPrompt(prefixedId, inject.value, inject.position, inject.depth, inject.scan, inject.role, filter); |
| 2059 | 2115 | } |
| 2060 | 2116 | } |
| 2061 | 2117 | |
| @@ -3760,7 +3760,7 @@ export async function checkWorldInfo(chat, maxContext, isDryRun) { | ||
| 3760 | 3760 | // Put this code here since otherwise, the chat reference is modified |
| 3761 | 3761 | for (const key of Object.keys(context.extensionPrompts)) { |
| 3762 | 3762 | if (context.extensionPrompts[key]?.scan) { |
| 3763 | 3763 | const prompt = await getExtensionPromptByName(key); |
| 3764 | 3764 | if (prompt) { |
| 3765 | 3765 | buffer.addInject(prompt); |
| 3766 | 3766 | } |