Merge branch 'staging' into sysprompt-divorce

0f2daede514247f64370ddc3c03d328099fc6702

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

21 files changed, +195 -50Ignore whitespace
default/config.yaml+2 -0
@@ -83,6 +83,8 @@ skipContentCheck: false
8383disableChatBackup: false
8484# Number of backups to keep for each chat and settings file
8585numberOfBackups: 50
86+# Interval in milliseconds to throttle chat backups per user
87+chatBackupThrottleInterval: 10000
8688# Allowed hosts for card downloads
8789whitelistImportDomains:
8890 - localhost
public/img/user-default.png+0 -0

Binary file

public/index.html+3 -0
@@ -2896,6 +2896,7 @@
28962896 <option value="mistral-large-latest">mistral-large-latest</option>
28972897 <option value="codestral-latest">codestral-latest</option>
28982898 <option value="codestral-mamba-latest">codestral-mamba-latest</option>
2899+ <option value="pixtral-latest">pixtral-latest</option>
28992900 </optgroup>
29002901 <optgroup label="Sub-versions">
29012902 <option value="open-mistral-nemo-2407">open-mistral-nemo-2407</option>
@@ -2903,11 +2904,13 @@
29032904 <option value="mistral-tiny-2312">mistral-tiny-2312</option>
29042905 <option value="mistral-small-2312">mistral-small-2312</option>
29052906 <option value="mistral-small-2402">mistral-small-2402</option>
2907+ <option value="mistral-small-2409">mistral-small-2409</option>
29062908 <option value="mistral-medium-2312">mistral-medium-2312</option>
29072909 <option value="mistral-large-2402">mistral-large-2402</option>
29082910 <option value="mistral-large-2407">mistral-large-2407</option>
29092911 <option value="codestral-2405">codestral-2405</option>
29102912 <option value="codestral-mamba-2407">codestral-mamba-2407</option>
2913+ <option value="pixtral-12b-2409">pixtral-12b-2409</option>
29112914 </optgroup>
29122915 </select>
29132916 </div>
public/script.js+3 -1
@@ -510,6 +510,7 @@ let saveCharactersPage = 0;
510510export const default_avatar = 'img/ai4.png';
511511export const system_avatar = 'img/five.png';
512512export const comment_avatar = 'img/quill.png';
513+export const default_user_avatar = 'img/user-default.png';
513514export let CLIENT_VERSION = 'SillyTavern:UNKNOWN:Cohee#1207'; // For Horde header
514515let optionsPopper = Popper.createPopper(document.getElementById('options_button'), document.getElementById('options'), {
515516 placement: 'top-start',
@@ -3335,7 +3336,6 @@ function removeLastMessage() {
33353336 */
33363337export async function Generate(type, { automatic_trigger, force_name2, quiet_prompt, quietToLoud, skipWIAN, force_chid, signal, quietImage, quietName } = {}, dryRun = false) {
33373338 console.log('Generate entered');
3338- await eventSource.emit(event_types.GENERATION_STARTED, type, { automatic_trigger, force_name2, quiet_prompt, quietToLoud, skipWIAN, force_chid, signal, quietImage }, dryRun);
33393339 setGenerationProgress(0);
33403340 generation_started = new Date();
33413341
@@ -3358,6 +3358,8 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro
33583358 }
33593359 }
33603360
3361+ await eventSource.emit(event_types.GENERATION_STARTED, type, { automatic_trigger, force_name2, quiet_prompt, quietToLoud, skipWIAN, force_chid, signal, quietImage }, dryRun);
3362+
33613363 if (main_api == 'kobold' && kai_settings.streaming_kobold && !kai_flags.can_use_streaming) {
33623364 toastr.error('Streaming is enabled, but the version of Kobold used does not support token streaming.', undefined, { timeOut: 10000, preventDuplicates: true });
33633365 unblockGeneration(type);
public/scripts/extensions.js+0 -1
@@ -29,7 +29,6 @@ export function saveMetadataDebounced() {
2929 const characterId = context.characterId;
3030
3131 if (saveMetadataTimeout) {
32- console.debug('Clearing save metadata timeout');
3332 clearTimeout(saveMetadataTimeout);
3433 }
3534
public/scripts/extensions/caption/index.js+1 -0
@@ -403,6 +403,7 @@ jQuery(async function () {
403403 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'openai' && (secret_state[SECRET_KEYS.OPENAI] || extension_settings.caption.allow_reverse_proxy)) ||
404404 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'openrouter' && secret_state[SECRET_KEYS.OPENROUTER]) ||
405405 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'zerooneai' && secret_state[SECRET_KEYS.ZEROONEAI]) ||
406+ (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'mistral' && (secret_state[SECRET_KEYS.MISTRALAI] || extension_settings.caption.allow_reverse_proxy)) ||
406407 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'google' && (secret_state[SECRET_KEYS.MAKERSUITE] || extension_settings.caption.allow_reverse_proxy)) ||
407408 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'anthropic' && (secret_state[SECRET_KEYS.CLAUDE] || extension_settings.caption.allow_reverse_proxy)) ||
408409 (extension_settings.caption.source === 'multimodal' && extension_settings.caption.multimodal_api === 'ollama' && textgenerationwebui_settings.server_urls[textgen_types.OLLAMA]) ||
public/scripts/extensions/caption/settings.html+4 -1
@@ -23,6 +23,7 @@
2323 <option value="google">Google AI Studio</option>
2424 <option value="koboldcpp">KoboldCpp</option>
2525 <option value="llamacpp">llama.cpp</option>
26+ <option value="mistral">MistralAI</option>
2627 <option value="ollama">Ollama</option>
2728 <option value="openai">OpenAI</option>
2829 <option value="openrouter">OpenRouter</option>
@@ -33,6 +34,8 @@
3334 <div class="flex1 flex-container flexFlowColumn flexNoGap">
3435 <label for="caption_multimodal_model" data-i18n="Model">Model</label>
3536 <select id="caption_multimodal_model" class="flex1 text_pole">
37+ <option data-type="mistral" value="pixtral-latest">pixtral-latest</option>
38+ <option data-type="mistral" value="pixtral-12b-2409">pixtral-12b-2409</option>
3639 <option data-type="zerooneai" value="yi-vision">yi-vision</option>
3740 <option data-type="openai" value="gpt-4-vision-preview">gpt-4-vision-preview</option>
3841 <option data-type="openai" value="gpt-4-turbo">gpt-4-turbo</option>
@@ -96,7 +99,7 @@
9699 <div data-type="ollama">
97100 The model must be downloaded first! Do it with the <code>ollama pull</code> command or <a href="#" id="caption_ollama_pull">click here</a>.
98101 </div>
99102 <label data-type="openai,anthropic,google,mistral" class="checkbox_label flexBasis100p" for="caption_allow_reverse_proxy" title="Allow using reverse proxy if defined and valid.">
100103 <input id="caption_allow_reverse_proxy" type="checkbox" class="checkbox">
101104 <span data-i18n="Allow reverse proxy">Allow reverse proxy</span>
102105 </label>
public/scripts/extensions/shared.js+6 -2
@@ -13,7 +13,7 @@ import { createThumbnail, isValidUrl } from '../utils.js';
1313 */
1414export async function getMultimodalCaption(base64Img, prompt) {
1515 const useReverseProxy =
1616 (['openai', 'anthropic', 'google', 'mistral'].includes(extension_settings.caption.multimodal_api))
1717 && extension_settings.caption.allow_reverse_proxy
1818 && oai_settings.reverse_proxy
1919 && isValidUrl(oai_settings.reverse_proxy);
@@ -36,7 +36,7 @@ export async function getMultimodalCaption(base64Img, prompt) {
3636 const isVllm = extension_settings.caption.multimodal_api === 'vllm';
3737 const base64Bytes = base64Img.length * 0.75;
3838 const compressionLimit = 2 * 1024 * 1024;
3939 if ((['google', 'openrouter', 'mistral'].includes(extension_settings.caption.multimodal_api) && base64Bytes > compressionLimit) || isOoba || isKoboldCpp) {
4040 const maxSide = 1024;
4141 base64Img = await createThumbnail(base64Img, maxSide, maxSide, 'image/jpeg');
4242 }
@@ -139,6 +139,10 @@ function throwIfInvalidModel(useReverseProxy) {
139139 throw new Error('Google AI Studio API key is not set.');
140140 }
141141
142+ if (extension_settings.caption.multi_modal_api === 'mistral' && !secret_state[SECRET_KEYS.MISTRALAI] && !useReverseProxy) {
143+ throw new Error('Mistral AI API key is not set.');
144+ }
145+
142146 if (extension_settings.caption.multimodal_api === 'ollama' && !textgenerationwebui_settings.server_urls[textgen_types.OLLAMA]) {
143147 throw new Error('Ollama server URL is not set.');
144148 }
public/scripts/horde.js+79 -19
@@ -1,10 +1,10 @@
11import {
22 saveSettingsDebouncedamount_gen,
33 callPopup,
4- setGenerationProgress,
54 getRequestHeaders,
65 max_context,
76 amount_gensaveSettingsDebounced,
7+ setGenerationProgress,
88} from '../script.js';
99import { SECRET_KEYS, writeSecret } from './secrets.js';
1010import { delay } from './utils.js';
@@ -45,8 +45,7 @@ async function getWorkers(force) {
4545 headers: getRequestHeaders(),
4646 body: JSON.stringify({ force }),
4747 });
4848 const data =return await response.json();
49- return data;
5049}
5150
5251/**
@@ -61,16 +60,18 @@ async function getModels(force) {
6160 body: JSON.stringify({ force }),
6261 });
6362 const data = await response.json();
63+ console.log('getModels', data);
6464 return data;
6565}
6666
67+
6768/**
6869 * Gets the status of a Horde task.
6970 * @param {string} taskId Task ID
7071 * @returns {Promise<Object>} Task status
7172 */
7273async function getTaskStatus(taskId) {
7374 const response = await fetch('/api/horde/task-status', {
7475 method: 'POST',
7576 headers: getRequestHeaders(),
7677 body: JSON.stringify({ taskId }),
@@ -80,8 +81,7 @@ async function getTaskStatus(taskId) {
8081 throw new Error(`Failed to get task status: ${response.statusText}`);
8182 }
8283
8384 const data =return await response.json();
84- return data;
8585}
8686
8787/**
@@ -148,7 +148,7 @@ async function adjustHordeGenerationParams(max_context_length, max_length) {
148148
149149 for (const model of selectedModels) {
150150 for (const worker of workers) {
151151 if (model.cluster === worker.cluster && worker.models.includes(model.name)) {
152152 // Skip workers that are not trusted if the option is enabled
153153 if (horde_settings.trusted_workers_only && !worker.trusted) {
154154 continue;
@@ -250,12 +250,10 @@ async function generateHorde(prompt, params, signal, reportProgress) {
250250 console.log(generatedText);
251251 console.log(`Generated by Horde Worker: ${WorkerName} [${WorkerModel}]`);
252252 return { text: generatedText, workerName: `Generated by Horde worker: ${WorkerName} [${WorkerModel}]` };
253- }
253+ } else if (!queue_position_first) {
254- else if (!queue_position_first) {
255254 queue_position_first = statusCheckJson.queue_position;
256255 reportProgress && setGenerationProgress(0);
257- }
256+ } else if (statusCheckJson.queue_position >= 0) {
258- else if (statusCheckJson.queue_position >= 0) {
259257 let queue_position = statusCheckJson.queue_position;
260258 const progress = Math.round(100 - (queue_position / queue_position_first * 100));
261259 reportProgress && setGenerationProgress(progress);
@@ -268,17 +266,24 @@ async function generateHorde(prompt, params, signal, reportProgress) {
268266 throw new Error('Horde timeout');
269267}
270268
269+
271270/**
272271 * Displays the available models in the Horde model selection dropdown.
273272 * @param {boolean} force Force refresh of the models
274273 */
275274async function getHordeModels(force) {
275+ const sortByPerformance = (a, b) => b.performance - a.performance;
276+ const sortByWhitelisted = (a, b) => b.is_whitelisted - a.is_whitelisted;
277+ const sortByPopular = (a, b) => b.tags?.includes('popular') - a.tags?.includes('popular');
278+
276279 $('#horde_model').empty();
277280 models = (await getModels(force)).sort((a, b) => b.performance - a.performance);{
281+ return sortByWhitelisted(a, b) || sortByPopular(a, b) || sortByPerformance(a, b);
282+ });
278283 for (const model of models) {
279284 const option = document.createElement('option');
280285 option.value = model.name;
281- option.innerText = `${model.name} (ETA: ${model.eta}s, Speed: ${model.performance}, Queue: ${model.queued}, Workers: ${model.count})`;
286+ option.innerText = hordeModelTextString(model);
282287 option.selected = horde_settings.models.includes(model.name);
283288 $('#horde_model').append(option);
284289 }
@@ -323,8 +328,66 @@ async function showKudos() {
323328 toastr.info(`Kudos: ${data.kudos}`, data.username);
324329}
325330
331+function hordeModelTextString(model) {
332+ const q = hordeModelQueueStateString(model);
333+ return `${model.name} (${q})`;
334+}
335+
336+function hordeModelQueueStateString(model) {
337+ return `ETA: ${model.eta}s, Speed: ${model.performance}, Queue: ${model.queued}, Workers: ${model.count}`;
338+}
339+
340+function getHordeModelTemplate(option) {
341+ const model = models.find(x => x.name === option?.element?.value);
342+
343+ if (!option.id || !model) {
344+ console.debug('No model found for option', option, option?.element?.value);
345+ console.debug('Models', models);
346+ return option.text;
347+ }
348+
349+ const strip = html => {
350+ const tmp = document.createElement('DIV');
351+ tmp.innerHTML = html || '';
352+ return tmp.textContent || tmp.innerText || '';
353+ };
354+
355+ // how much do we trust the metadata from the models repo? about this much
356+ const displayName = strip(model.display_name || model.name).replace(/.*\//g, '');
357+ const description = strip(model.description);
358+ const tags = model.tags ? model.tags.map(strip) : [];
359+ const url = strip(model.url);
360+ const style = strip(model.style);
361+
362+ const workerInfo = hordeModelQueueStateString(model);
363+ const isPopular = model.tags?.includes('popular');
364+ const descriptionDiv = description ? `<div class="horde-model-description">${description}</div>` : '';
365+ const tagSpans = tags.length > 0 &&
366+ `${tags.map(tag => `<span class="tag tag_name">${tag}</span>`).join('')}</span>` || '';
367+
368+ const modelDetailsLink = url && `<a href="${url}" target="_blank" rel="noopener noreferrer" class="model-details-link fa-solid fa-circle-question"> </a>`;
369+ const capitalize = s => s ? s[0].toUpperCase() + s.slice(1) : '';
370+ const innerContent = [
371+ `<strong>${displayName}</strong> ${modelDetailsLink}`,
372+ style ? `${capitalize(style)}` : '',
373+ tagSpans ? `<span class="tags tags_inline inline-flex margin-r2">${tagSpans}</span>` : '',
374+ ].filter(Boolean).join(' | ');
375+
376+ return $((`
377+ <div class="flex-container flexFlowColumn">
378+ <div>
379+ ${isPopular ? '<span class="fa-fw fa-solid fa-star" title="Popular"></span>' : ''}
380+ ${innerContent}
381+ </div>
382+ ${descriptionDiv}
383+ <div><small>${workerInfo}</small></div>
384+ </div>
385+ `));
386+}
387+
326388jQuery(function () {
327389 $('#horde_model').on('mousedown change', async function (e) {
390+ console.log('Horde model change', e);
328391 horde_settings.models = $('#horde_model').val();
329392 console.log('Updated Horde models', horde_settings.models);
330393
@@ -374,10 +437,7 @@ jQuery(function () {
374437 // Customize the pillbox text by shortening the full text
375438 return data.id;
376439 },
377- templateResult: function (data) {
440+ templateResult: getHordeModelTemplate,
378- // Return the full text for the dropdown
379- return data.text;
380- },
381441 });
382442 }
383443});
public/scripts/openai.js+7 -1
@@ -2490,7 +2490,7 @@ class Message {
24902490 * @returns {Promise<string>} Compressed image as a Data URL.
24912491 */
24922492 async compressImage(image) {
24932493 if ([chat_completion_sources.OPENROUTER, chat_completion_sources.MAKERSUITE, chat_completion_sources.MISTRALAI].includes(oai_settings.chat_completion_source)) {
24942494 const sizeThreshold = 2 * 1024 * 1024;
24952495 const dataSize = image.length * 0.75;
24962496 const maxSide = 1024;
@@ -4221,6 +4221,8 @@ async function onModelChange() {
42214221 $('#openai_max_context').attr('max', max_128k);
42224222 } else if (oai_settings.mistralai_model.includes('mixtral-8x22b')) {
42234223 $('#openai_max_context').attr('max', max_64k);
4224+ } else if (oai_settings.mistralai_model.includes('pixtral')) {
4225+ $('#openai_max_context').attr('max', max_128k);
42244226 } else {
42254227 $('#openai_max_context').attr('max', max_32k);
42264228 }
@@ -4770,6 +4772,8 @@ export function isImageInliningSupported() {
47704772 'gpt-4o-mini',
47714773 'chatgpt-4o-latest',
47724774 'yi-vision',
4775+ 'pixtral-latest',
4776+ 'pixtral-12b-2409',
47734777 ];
47744778
47754779 switch (oai_settings.chat_completion_source) {
@@ -4785,6 +4789,8 @@ export function isImageInliningSupported() {
47854789 return true;
47864790 case chat_completion_sources.ZEROONEAI:
47874791 return visionSupportedModels.some(model => oai_settings.zerooneai_model.includes(model));
4792+ case chat_completion_sources.MISTRALAI:
4793+ return visionSupportedModels.some(model => oai_settings.mistralai_model.includes(model));
47884794 default:
47894795 return false;
47904796 }
public/scripts/personas.js+3 -3
@@ -2,7 +2,7 @@ import {
22 characters,
33 chat,
44 chat_metadata,
55 default_avatardefault_user_avatar,
66 eventSource,
77 event_types,
88 getRequestHeaders,
@@ -357,7 +357,7 @@ async function createDummyPersona() {
357357 // Date + name (only ASCII) to make it unique
358358 const avatarId = `${Date.now()}-${personaName.replace(/[^a-zA-Z0-9]/g, '')}.png`;
359359 initPersona(avatarId, personaName, '');
360360 await uploadUserAvatar(default_avatardefault_user_avatar, avatarId);
361361}
362362
363363/**
@@ -944,7 +944,7 @@ async function onPersonasRestoreInput(e) {
944944 // If the avatar is missing, upload it
945945 if (!avatarsList.includes(key)) {
946946 warnings.push(`Persona image "${key}" (${value}) is missing, uploading default avatar`);
947947 await uploadUserAvatar(default_avatardefault_user_avatar, key);
948948 }
949949 }
950950
public/scripts/textgen-settings.js+2 -2
@@ -15,7 +15,7 @@ import { BIAS_CACHE, createNewLogitBiasEntry, displayLogitBias, getLogitBiasList
1515import { power_user, registerDebugFunction } from './power-user.js';
1616import { getEventSourceStream } from './sse-stream.js';
1717import { getCurrentDreamGenModelTokenizer, getCurrentOpenRouterModelTokenizer } from './textgen-models.js';
1818import { SENTENCEPIECE_TOKENIZERSENCODE_TOKENIZERS, TEXTGEN_TOKENIZERS, getTextTokens, tokenizers } from './tokenizers.js';
1919import { getSortableDelay, onlyUnique } from './utils.js';
2020
2121export {
@@ -353,7 +353,7 @@ function getTokenizerForTokenIds() {
353353 return tokenizers.API_CURRENT;
354354 }
355355
356356 if (SENTENCEPIECE_TOKENIZERSENCODE_TOKENIZERS.includes(power_user.tokenizer)) {
357357 return power_user.tokenizer;
358358 }
359359
public/scripts/tokenizers.js+5 -1
@@ -33,18 +33,22 @@ export const tokenizers = {
3333 BEST_MATCH: 99,
3434};
3535
36-export const SENTENCEPIECE_TOKENIZERS = [
36+// A list of local tokenizers that support encoding and decoding token ids.
37+export const ENCODE_TOKENIZERS = [
3738 tokenizers.LLAMA,
3839 tokenizers.MISTRAL,
3940 tokenizers.YI,
4041 tokenizers.LLAMA3,
4142 tokenizers.GEMMA,
4243 tokenizers.JAMBA,
44+ tokenizers.QWEN2,
45+ tokenizers.COMMAND_R,
4346 // uncomment when NovelAI releases Kayra and Clio weights, lol
4447 //tokenizers.NERD,
4548 //tokenizers.NERD2,
4649];
4750
51+// A list of Text Completion sources that support remote tokenization.
4852export const TEXTGEN_TOKENIZERS = [OOBA, TABBY, KOBOLDCPP, LLAMACPP, VLLM, APHRODITE];
4953
5054const TOKENIZER_URLS = {
public/scripts/utils.js+5 -5
@@ -1908,13 +1908,13 @@ export function select2ChoiceClickSubscribe(control, action, { buttonStyle = fal
19081908 * @returns {string} The html representation of the highlighted regex
19091909 */
19101910export function highlightRegex(regexStr) {
19111911 // Function to escape HTML special characters for safety or readability
19121912 const escapeHtmlescape = (str) => str.replace(/[&<>"'\x01]/g, match => ({
19131913 '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;', '\x01': '\\x01',
19141914 })[match]);
19151915
19161916 // Replace special characters with their HTML-escaped forms
19171917 regexStr = escapeHtmlescape(regexStr);
19181918
19191919 // Patterns that we want to highlight only if they are not escaped
19201920 function getPatterns() {
public/style.css+8 -0
@@ -3518,6 +3518,14 @@ grammarly-extension {
35183518 column-gap: 20px;
35193519}
35203520
3521+.horde-model-description {
3522+ -webkit-line-clamp: 3;
3523+ line-clamp: 3;
3524+ font-size: 0.9em;
3525+ overflow: hidden;
3526+ text-overflow: ellipsis;
3527+}
3528+
35213529.drag-handle {
35223530 cursor: grab;
35233531 /* Make the drag handle not selectable in most browsers */
src/constants.js+0 -2
@@ -5,7 +5,6 @@ const PUBLIC_DIRECTORIES = {
55 extensions: 'public/scripts/extensions',
66};
77
8-const DEFAULT_AVATAR = '/img/ai4.png';
98const SETTINGS_FILE = 'settings.json';
109
1110/**
@@ -423,7 +422,6 @@ const VLLM_KEYS = [
423422
424423module.exports = {
425424 DEFAULT_USER,
426- DEFAULT_AVATAR,
427425 SETTINGS_FILE,
428426 PUBLIC_DIRECTORIES,
429427 USER_DIRECTORY_TEMPLATE,
src/endpoints/characters.js+1 -2
@@ -726,13 +726,12 @@ router.post('/create', urlencodedParser, async function (request, response) {
726726 const char = JSON.stringify(charaFormatData(request.body, request.user.directories));
727727 const internalName = getPngName(request.body.ch_name, request.user.directories);
728728 const avatarName = `${internalName}.png`;
729- const defaultAvatar = './public/img/ai4.png';
730729 const chatsPath = path.join(request.user.directories.chats, internalName);
731730
732731 if (!fs.existsSync(chatsPath)) fs.mkdirSync(chatsPath);
733732
734733 if (!request.file) {
735734 await writeCharacterData(defaultAvatardefaultAvatarPath, char, internalName, request);
736735 return response.send(avatarName);
737736 } else {
738737 const crop = tryParse(request.query.crop);
src/endpoints/chats.js+24 -2
@@ -4,6 +4,7 @@ const readline = require('readline');
44const express = require('express');
55const sanitize = require('sanitize-filename');
66const writeFileAtomicSync = require('write-file-atomic').sync;
7+const _ = require('lodash');
78
89const { jsonParser, urlencodedParser } = require('../express-common');
910const { getConfigValue, humanizedISO8601DateTime, tryParse, generateTimestamp, removeOldBackups } = require('../util');
@@ -34,6 +35,27 @@ function backupChat(directory, name, chat) {
3435 }
3536}
3637
38+const backupFunctions = new Map();
39+
40+/**
41+ * Gets a backup function for a user.
42+ * @param {string} handle User handle
43+ * @returns {function(string, string, string): void} Backup function
44+ */
45+function getBackupFunction(handle) {
46+ const throttleInterval = getConfigValue('chatBackupThrottleInterval', 10_000);
47+ if (!backupFunctions.has(handle)) {
48+ backupFunctions.set(handle, _.throttle(backupChat, throttleInterval, { leading: true, trailing: true }));
49+ }
50+ return backupFunctions.get(handle);
51+}
52+
53+process.on('exit', () => {
54+ for (const func of backupFunctions.values()) {
55+ func.flush();
56+ }
57+});
58+
3759/**
3860 * Imports a chat from Ooba's format.
3961 * @param {string} userName User name
@@ -147,7 +169,7 @@ router.post('/save', jsonParser, function (request, response) {
147169 const fileName = `${String(request.body.file_name)}.jsonl`;
148170 const filePath = path.join(request.user.directories.chats, directoryName, sanitize(fileName));
149171 writeFileAtomicSync(filePath, jsonlData, 'utf8');
150172 backupChatgetBackupFunction(request.user.profile.handle)(request.user.directories.backups, directoryName, jsonlData);
151173 return response.send({ result: 'ok' });
152174 } catch (error) {
153175 response.send(error);
@@ -446,7 +468,7 @@ router.post('/group/save', jsonParser, (request, response) => {
446468 let chat_data = request.body.chat;
447469 let jsonlData = chat_data.map(JSON.stringify).join('\n');
448470 writeFileAtomicSync(pathToFile, jsonlData, 'utf8');
449471 backupChatgetBackupFunction(request.user.profile.handle)(request.user.directories.backups, String(id), jsonlData);
450472 return response.send({ ok: true });
451473});
452474
src/endpoints/horde.js+29 -4
@@ -6,6 +6,7 @@ const { readSecret, SECRET_KEYS } = require('./secrets');
66const { jsonParser } = require('../express-common');
77
88const ANONYMOUS_KEY = '0000000000';
9+const HORDE_TEXT_MODEL_METADATA_URL = 'https://raw.githubusercontent.com/db0/AI-Horde-text-model-reference/main/db.json';
910const cache = new Cache(60 * 1000);
1011const router = express.Router();
1112
@@ -23,10 +24,9 @@ async function getClientAgent() {
2324 * @returns {Promise<AIHorde>} AIHorde client
2425 */
2526async function getHordeClient() {
2627 const ai_horde =return new AIHorde({
2728 client_agent: await getClientAgent(),
2829 });
29- return ai_horde;
3030}
3131
3232/**
@@ -79,10 +79,24 @@ router.post('/text-workers', jsonParser, async (request, response) => {
7979 }
8080});
8181
82+async function getHordeTextModelMetadata() {
83+ const response = await fetch(HORDE_TEXT_MODEL_METADATA_URL);
84+ return await response.json();
85+}
86+
87+async function mergeModelsAndMetadata(models, metadata) {
88+ return models.map(model => {
89+ const metadataModel = metadata[model.name];
90+ if (!metadataModel) {
91+ return { ...model, is_whitelisted: false };
92+ }
93+ return { ...model, ...metadataModel, is_whitelisted: true };
94+ });
95+}
96+
8297router.post('/text-models', jsonParser, async (request, response) => {
8398 try {
8499 const cachedModels = cache.get('models');
85-
86100 if (cachedModels && !request.body.force) {
87101 return response.send(cachedModels);
88102 }
@@ -94,7 +108,17 @@ router.post('/text-models', jsonParser, async (request, response) => {
94108 },
95109 });
96110
97111 constlet data = await fetchResult.json();
112+
113+ // attempt to fetch and merge models metadata
114+ try {
115+ const metadata = await getHordeTextModelMetadata();
116+ data = await mergeModelsAndMetadata(data, metadata);
117+ }
118+ catch (error) {
119+ console.error('Failed to fetch metadata:', error);
120+ }
121+
98122 cache.set('models', data);
99123 return response.send(data);
100124 } catch (error) {
@@ -310,6 +334,7 @@ router.post('/generate-image', jsonParser, async (request, response) => {
310334 console.log('Stable Horde request:', request.body);
311335
312336 const ai_horde = await getHordeClient();
337+ // noinspection JSCheckFunctionSignatures -- see @ts-ignore - use_gfpgan
313338 const generation = await ai_horde.postAsyncImageGenerate(
314339 {
315340 prompt: `${request.body.prompt} ### ${request.body.negative_prompt}`,
src/endpoints/openai.js+8 -0
@@ -51,6 +51,10 @@ router.post('/caption-image', jsonParser, async (request, response) => {
5151 key = readSecret(request.user.directories, SECRET_KEYS.ZEROONEAI);
5252 }
5353
54+ if (request.body.api === 'mistral') {
55+ key = readSecret(request.user.directories, SECRET_KEYS.MISTRALAI);
56+ }
57+
5458 if (!key && !request.body.reverse_proxy && ['custom', 'ooba', 'koboldcpp', 'vllm'].includes(request.body.api) === false) {
5559 console.log('No key found for API', request.body.api);
5660 return response.sendStatus(400);
@@ -107,6 +111,10 @@ router.post('/caption-image', jsonParser, async (request, response) => {
107111 apiUrl = 'https://api.01.ai/v1/chat/completions';
108112 }
109113
114+ if (request.body.api === 'mistral') {
115+ apiUrl = 'https://api.mistral.ai/v1/chat/completions';
116+ }
117+
110118 if (request.body.api === 'ooba') {
111119 apiUrl = `${trimV1(request.body.server_url)}/v1/chat/completions`;
112120 const imgMessage = body.messages.pop();
src/users.js+5 -4
@@ -11,7 +11,7 @@ const mime = require('mime-types');
1111const archiver = require('archiver');
1212const writeFileAtomicSync = require('write-file-atomic').sync;
1313
1414const { USER_DIRECTORY_TEMPLATE, DEFAULT_USER, PUBLIC_DIRECTORIES, DEFAULT_AVATAR, SETTINGS_FILE } = require('./constants');
1515const { getConfigValue, color, delay, setConfigValue, generateTimestamp } = require('./util');
1616const { readSecret, writeSecret } = require('./endpoints/secrets');
1717
@@ -25,6 +25,7 @@ const ANON_CSRF_SECRET = crypto.randomBytes(64).toString('base64');
2525 * @type {Map<string, UserDirectoryList>}
2626 */
2727const DIRECTORIES_CACHE = new Map();
28+const PUBLIC_USER_AVATAR = '/img/default-user.png';
2829
2930const STORAGE_KEYS = {
3031 csrfSecret: 'csrfSecret',
@@ -510,11 +511,11 @@ async function getUserAvatar(handle) {
510511 const settings = fs.existsSync(pathToSettings) ? JSON.parse(fs.readFileSync(pathToSettings, 'utf8')) : {};
511512 const avatarFile = settings?.power_user?.default_persona || settings?.user_avatar;
512513 if (!avatarFile) {
513514 return DEFAULT_AVATARPUBLIC_USER_AVATAR;
514515 }
515516 const avatarPath = path.join(directory.avatars, avatarFile);
516517 if (!fs.existsSync(avatarPath)) {
517518 return DEFAULT_AVATARPUBLIC_USER_AVATAR;
518519 }
519520 const mimeType = mime.lookup(avatarPath);
520521 const base64Content = fs.readFileSync(avatarPath, 'base64');
@@ -522,7 +523,7 @@ async function getUserAvatar(handle) {
522523 }
523524 catch {
524525 // Ignore errors
525526 return DEFAULT_AVATARPUBLIC_USER_AVATAR;
526527 }
527528}
528529