Chat Completion: switch to async token handling

8e082e622b09dbe7d606d98966921363ab6f2dc6

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

2 files changed, +104 -62Ignore whitespace
public/scripts/PromptManager.js+1 -1
@@ -315,7 +315,7 @@ class PromptManager {
315315 */
316316 init(moduleConfiguration, serviceSettings) {
317317 this.configuration = Object.assign(this.configuration, moduleConfiguration);
318318 this.tokenHandler = this.tokenHandler || new TokenHandler(() => { throw new Error('Token handler not set'); });
319319 this.serviceSettings = serviceSettings;
320320 this.containerElement = document.getElementById(this.configuration.containerIdentifier);
321321
public/scripts/openai.js+103 -61
@@ -60,7 +60,7 @@ import {
6060 resetScrollHeight,
6161 stringFormat,
6262} from './utils.js';
6363import { countTokensOpenAIcountTokensOpenAIAsync, getTokenizerModel } from './tokenizers.js';
6464import { isMobile } from './RossAscends-mods.js';
6565import { saveLogprobsForActiveMessage } from './logprobs.js';
6666import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
@@ -671,14 +671,14 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
671671
672672 // Reserve budget for new chat message
673673 const newChat = selected_group ? oai_settings.new_group_chat_prompt : oai_settings.new_chat_prompt;
674674 const newChatMessage = newawait Message.createAsync('system', substituteParams(newChat), 'newMainChat');
675675 chatCompletion.reserveBudget(newChatMessage);
676676
677677 // Reserve budget for group nudge
678678 let groupNudgeMessage = null;
679679 const noGroupNudgeTypes = ['impersonate'];
680680 if (selected_group && prompts.has('groupNudge') && !noGroupNudgeTypes.includes(type)) {
681681 groupNudgeMessage = await Message.fromPromptfromPromptAsync(prompts.get('groupNudge'));
682682 chatCompletion.reserveBudget(groupNudgeMessage);
683683 }
684684
@@ -693,12 +693,12 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
693693 };
694694 const continuePrompt = new Prompt(promptObject);
695695 const preparedPrompt = promptManager.preparePrompt(continuePrompt);
696696 continueMessage = await Message.fromPromptfromPromptAsync(preparedPrompt);
697697 chatCompletion.reserveBudget(continueMessage);
698698 }
699699
700700 const lastChatPrompt = messages[messages.length - 1];
701701 const message = newawait Message.createAsync('user', oai_settings.send_if_empty, 'emptyUserMessageReplacement');
702702 if (lastChatPrompt && lastChatPrompt.role === 'assistant' && oai_settings.send_if_empty && chatCompletion.canAfford(message)) {
703703 chatCompletion.insert(message, 'chatHistory');
704704 }
@@ -715,11 +715,11 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
715715 // We do not want to mutate the prompt
716716 const prompt = new Prompt(chatPrompt);
717717 prompt.identifier = `chatHistory-${messages.length - index}`;
718718 const chatMessage = await Message.fromPromptfromPromptAsync(promptManager.preparePrompt(prompt));
719719
720720 if (promptManager.serviceSettings.names_behavior === character_names_behavior.COMPLETION && prompt.name) {
721721 const messageName = promptManager.isValidName(prompt.name) ? prompt.name : promptManager.sanitizeName(prompt.name);
722722 await chatMessage.setName(messageName);
723723 }
724724
725725 if (imageInlining && chatPrompt.image) {
@@ -729,9 +729,9 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
729729 if (canUseTools && Array.isArray(chatPrompt.invocations)) {
730730 /** @type {import('./tool-calling.js').ToolInvocation[]} */
731731 const invocations = chatPrompt.invocations;
732732 const toolCallMessage = newawait Message.createAsync(chatMessage.role, undefined, 'toolCall-' + chatMessage.identifier);
733733 const toolResultMessages = await Promise.all(invocations.slice().reverse().map((invocation) => new Message.createAsync('tool', invocation.result || '[No content]', invocation.id)));
734734 await toolCallMessage.setToolCalls(invocations);
735735 if (chatCompletion.canAffordAll([toolCallMessage, ...toolResultMessages])) {
736736 for (const resultMessage of toolResultMessages) {
737737 chatCompletion.insertAtStart(resultMessage, 'chatHistory');
@@ -748,7 +748,8 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
748748 if (type === 'continue' && oai_settings.continue_prefill && chatPrompt === firstNonInjected) {
749749 // in case we are using continue_prefill and the latest message is an assistant message, we want to prepend the users assistant prefill on the message
750750 if (chatPrompt.role === 'assistant') {
751751 const collectioncontinueMessage = new MessageCollection('continuePrefill', newawait Message.createAsync(chatMessage.role, substituteParams(oai_settings.assistant_prefill + '\n\n') + chatMessage.content, chatMessage.identifier));
752+ const collection = new MessageCollection('continuePrefill', );
752753 chatCompletion.add(collection, -1);
753754 continue;
754755 }
@@ -787,15 +788,16 @@ async function populateChatHistory(messages, prompts, chatCompletion, type = nul
787788 * @param {ChatCompletion} chatCompletion - An instance of ChatCompletion class that will be populated with the prompts.
788789 * @param {Object[]} messageExamples - Array containing all message examples.
789790 */
790791async function populateDialogueExamples(prompts, chatCompletion, messageExamples) {
791792 if (!prompts.has('dialogueExamples')) {
792793 return;
793794 }
794795
795796 chatCompletion.add(new MessageCollection('dialogueExamples'), prompts.index('dialogueExamples'));
796797 if (Array.isArray(messageExamples) && messageExamples.length) {
797798 const newExampleChat = newawait Message.createAsync('system', substituteParams(oai_settings.new_example_chat_prompt), 'newChat');
798799 for (const dialogue of [...messageExamples].forEach((dialogue, dialogueIndex) => {
800+ const dialogueIndex = messageExamples.indexOf(dialogue);
799801 let examplesAdded = 0;
800802
801803 if (chatCompletion.canAfford(newExampleChat)) chatCompletion.insert(newExampleChat, 'dialogueExamples');
@@ -806,8 +808,8 @@ function populateDialogueExamples(prompts, chatCompletion, messageExamples) {
806808 const content = prompt.content || '';
807809 const identifier = `dialogueExamples ${dialogueIndex}-${promptIndex}`;
808810
809811 const chatMessage = newawait Message.createAsync(role, content, identifier);
810812 await chatMessage.setName(prompt.name);
811813 if (!chatCompletion.canAfford(chatMessage)) {
812814 break;
813815 }
@@ -818,7 +820,7 @@ function populateDialogueExamples(prompts, chatCompletion, messageExamples) {
818820 if (0 === examplesAdded) {
819821 chatCompletion.removeLastFrom('dialogueExamples');
820822 }
821823 });
822824 }
823825}
824826
@@ -873,7 +875,7 @@ function getPromptRole(role) {
873875 */
874876async function populateChatCompletion(prompts, chatCompletion, { bias, quietPrompt, quietImage, type, cyclePrompt, messages, messageExamples }) {
875877 // Helper function for preparing a prompt, that already exists within the prompt collection, for completion
876878 const addToChatCompletion = async (source, target = null) => {
877879 // We need the prompts array to determine a position for the source.
878880 if (false === prompts.has(source)) return;
879881
@@ -891,30 +893,31 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
891893
892894 const index = target ? prompts.index(target) : prompts.index(source);
893895 const collection = new MessageCollection(source);
894- collection.add(Message.fromPrompt(prompt));
896+ const message = await Message.fromPromptAsync(prompt);
897+ collection.add(message);
895898 chatCompletion.add(collection, index);
896899 };
897900
898901 chatCompletion.reserveBudget(3); // every reply is primed with <|start|>assistant<|message|>
899902 // Character and world information
900903 await addToChatCompletion('worldInfoBefore');
901904 await addToChatCompletion('main');
902905 await addToChatCompletion('worldInfoAfter');
903906 await addToChatCompletion('charDescription');
904907 await addToChatCompletion('charPersonality');
905908 await addToChatCompletion('scenario');
906909 await addToChatCompletion('personaDescription');
907910
908911 // Collection of control prompts that will always be positioned last
909912 chatCompletion.setOverriddenPrompts(prompts.overriddenPrompts);
910913 const controlPrompts = new MessageCollection('controlPrompts');
911914
912915 const impersonateMessage = await Message.fromPromptfromPromptAsync(prompts.get('impersonate')) ?? null;
913916 if (type === 'impersonate') controlPrompts.add(impersonateMessage);
914917
915918 // Add quiet prompt to control prompts
916919 // This should always be last, even in control prompts. Add all further control prompts BEFORE this prompt
917920 const quietPromptMessage = await Message.fromPromptfromPromptAsync(prompts.get('quietPrompt')) ?? null;
918921 if (quietPromptMessage && quietPromptMessage.content) {
919922 if (isImageInliningSupported() && quietImage) {
920923 await quietPromptMessage.addImage(quietImage);
@@ -940,20 +943,23 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
940943 return acc;
941944 }, []);
942945
943946 for (const identifier of [...systemPrompts, ...userRelativePrompts].forEach(identifier => addToChatCompletion(identifier)); {
947+ await addToChatCompletion(identifier);
948+ }
944949
945950 // Add enhance definition instruction
946951 if (prompts.has('enhanceDefinitions')) await addToChatCompletion('enhanceDefinitions');
947952
948953 // Bias
949954 if (bias && bias.trim().length) await addToChatCompletion('bias');
950955
951956 // Tavern Extras - Summary
952957 if (prompts.has('summary')) {
953958 const summary = prompts.get('summary');
954959
955960 if (summary.position) {
956- chatCompletion.insert(Message.fromPrompt(summary), 'main', summary.position);
961+ const message = await Message.fromPromptAsync(summary);
962+ chatCompletion.insert(message, 'main', summary.position);
957963 }
958964 }
959965
@@ -962,7 +968,8 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
962968 const authorsNote = prompts.get('authorsNote');
963969
964970 if (authorsNote.position) {
965- chatCompletion.insert(Message.fromPrompt(authorsNote), 'main', authorsNote.position);
971+ const message = await Message.fromPromptAsync(authorsNote);
972+ chatCompletion.insert(message, 'main', authorsNote.position);
966973 }
967974 }
968975
@@ -971,7 +978,8 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
971978 const vectorsMemory = prompts.get('vectorsMemory');
972979
973980 if (vectorsMemory.position) {
974- chatCompletion.insert(Message.fromPrompt(vectorsMemory), 'main', vectorsMemory.position);
981+ const message = await Message.fromPromptAsync(vectorsMemory);
982+ chatCompletion.insert(message, 'main', vectorsMemory.position);
975983 }
976984 }
977985
@@ -980,7 +988,8 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
980988 const vectorsDataBank = prompts.get('vectorsDataBank');
981989
982990 if (vectorsDataBank.position) {
983- chatCompletion.insert(Message.fromPrompt(vectorsDataBank), 'main', vectorsDataBank.position);
991+ const message = await Message.fromPromptAsync(vectorsDataBank);
992+ chatCompletion.insert(message, 'main', vectorsDataBank.position);
984993 }
985994 }
986995
@@ -989,13 +998,15 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
989998 const smartContext = prompts.get('smartContext');
990999
9911000 if (smartContext.position) {
992- chatCompletion.insert(Message.fromPrompt(smartContext), 'main', smartContext.position);
1001+ const message = await Message.fromPromptAsync(smartContext);
1002+ chatCompletion.insert(message, 'main', smartContext.position);
9931003 }
9941004 }
9951005
9961006 // Other relative extension prompts
9971007 for (const prompt of prompts.collection.filter(p => p.extension && p.position)) {
998- chatCompletion.insert(Message.fromPrompt(prompt), 'main', prompt.position);
1008+ const message = await Message.fromPromptAsync(prompt);
1009+ chatCompletion.insert(message, 'main', prompt.position);
9991010 }
10001011
10011012 // Pre-allocation of tokens for tool data
@@ -1003,7 +1014,7 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
10031014 const toolData = {};
10041015 await ToolManager.registerFunctionToolsOpenAI(toolData);
10051016 const toolMessage = [{ role: 'user', content: JSON.stringify(toolData) }];
10061017 const toolTokens = await tokenHandler.countcountAsync(toolMessage);
10071018 chatCompletion.reserveBudget(toolTokens);
10081019 }
10091020
@@ -1012,11 +1023,11 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm
10121023
10131024 // Decide whether dialogue examples should always be added
10141025 if (power_user.pin_examples) {
10151026 await populateDialogueExamples(prompts, chatCompletion, messageExamples);
10161027 await populateChatHistory(messages, prompts, chatCompletion, type, cyclePrompt);
10171028 } else {
10181029 await populateChatHistory(messages, prompts, chatCompletion, type, cyclePrompt);
10191030 await populateDialogueExamples(prompts, chatCompletion, messageExamples);
10201031 }
10211032
10221033 chatCompletion.freeBudget(controlPrompts);
@@ -1281,7 +1292,7 @@ export async function prepareOpenAIMessages({
12811292 promptManager.setChatCompletion(chatCompletion);
12821293
12831294 if (oai_settings.squash_system_messages && dryRun == false) {
12841295 await chatCompletion.squashSystemMessages();
12851296 }
12861297
12871298 // All information is up-to-date, render.
@@ -2127,8 +2138,11 @@ async function calculateLogitBias() {
21272138}
21282139
21292140class TokenHandler {
2130- constructor(countTokenFn) {
2141+ /**
2131- this.countTokenFn = countTokenFn;
2142+ * @param {(messages: object[] | object, full?: boolean) => Promise<number>} countTokenAsyncFn Function to count tokens
2143+ */
2144+ constructor(countTokenAsyncFn) {
2145+ this.countTokenAsyncFn = countTokenAsyncFn;
21322146 this.counts = {
21332147 'start_chat': 0,
21342148 'prompt': 0,
@@ -2157,8 +2171,15 @@ class TokenHandler {
21572171 this.counts[type] -= value;
21582172 }
21592173
2160- count(messages, full, type) {
2174+ /**
2161- const token_count = this.countTokenFn(messages, full);
2175+ * Count tokens for a message or messages.
2176+ * @param {object|any[]} messages Messages to count tokens for
2177+ * @param {boolean} [full] Count full tokens
2178+ * @param {string} [type] Identifier for the token count
2179+ * @returns {Promise<number>} The token count
2180+ */
2181+ async countAsync(messages, full, type) {
2182+ const token_count = await this.countTokenAsyncFn(messages, full);
21622183 this.counts[type] += token_count;
21632184
21642185 return token_count;
@@ -2178,7 +2199,7 @@ class TokenHandler {
21782199}
21792200
21802201
21812202const tokenHandler = new TokenHandler(countTokensOpenAIcountTokensOpenAIAsync);
21822203
21832204// Thrown by ChatCompletion when a requested prompt couldn't be found.
21842205class IdentifierNotFoundError extends Error {
@@ -2228,6 +2249,7 @@ class Message {
22282249 * @param {string} role - The role of the entity creating the message.
22292250 * @param {string} content - The actual content of the message.
22302251 * @param {string} identifier - A unique identifier for the message.
2252+ * @private Don't use this constructor directly. Use createAsync instead.
22312253 */
22322254 constructor(role, content, identifier) {
22332255 this.identifier = identifier;
@@ -2239,18 +2261,32 @@ class Message {
22392261 this.role = 'system';
22402262 }
22412263
2242- if (typeof this.content === 'string' && this.content.length > 0) {
2264+ this.tokens = 0;
2243- this.tokens = tokenHandler.count({ role: this.role, content: this.content });
2265+ }
2244- } else {
2266+
2245- this.tokens = 0;
2267+ /**
2268+ * Create a new Message instance.
2269+ * @param {string} role
2270+ * @param {string} content
2271+ * @param {string} identifier
2272+ * @returns {Promise<Message>} Message instance
2273+ */
2274+ static async createAsync(role, content, identifier) {
2275+ const message = new Message(role, content, identifier);
2276+
2277+ if (typeof message.content === 'string' && message.content.length > 0) {
2278+ message.tokens = await tokenHandler.countAsync({ role: message.role, content: message.content });
22462279 }
2280+
2281+ return message;
22472282 }
22482283
22492284 /**
22502285 * Reconstruct the message from a tool invocation.
22512286 * @param {import('./tool-calling.js').ToolInvocation[]} invocations - The tool invocations to reconstruct the message from.
2287+ * @returns {Promise<void>}
22522288 */
22532289 async setToolCalls(invocations) {
22542290 this.tool_calls = invocations.map(i => ({
22552291 id: i.id,
22562292 type: 'function',
@@ -2259,12 +2295,17 @@ class Message {
22592295 name: i.name,
22602296 },
22612297 }));
22622298 this.tokens = await tokenHandler.countcountAsync({ role: this.role, tool_calls: JSON.stringify(this.tool_calls) });
22632299 }
22642300
2265- setName(name) {
2301+ /**
2302+ * Add a name to the message.
2303+ * @param {string} name Name to set for the message.
2304+ * @returns {Promise<void>}
2305+ */
2306+ async setName(name) {
22662307 this.name = name;
22672308 this.tokens = await tokenHandler.countcountAsync({ role: this.role, content: this.content, name: this.name });
22682309 }
22692310
22702311 async addImage(image) {
@@ -2356,13 +2397,13 @@ class Message {
23562397 }
23572398
23582399 /**
23592400 * Create a new Message instance from a prompt asynchronously.
23602401 * @static
23612402 * @param {Object} prompt - The prompt object.
23622403 * @returns {Promise<Message>} A new instance of Message.
23632404 */
23642405 static fromPromptasync fromPromptAsync(prompt) {
23652406 return new Message.createAsync(prompt.role, prompt.content, prompt.identifier);
23662407 }
23672408
23682409 /**
@@ -2488,8 +2529,9 @@ export class ChatCompletion {
24882529
24892530 /**
24902531 * Combines consecutive system messages into one if they have no name attached.
2532+ * @returns {Promise<void>}
24912533 */
24922534 async squashSystemMessages() {
24932535 const excludeList = ['newMainChat', 'newChat', 'groupNudge'];
24942536 this.messages.collection = this.messages.flatten();
24952537
@@ -2509,7 +2551,7 @@ export class ChatCompletion {
25092551 if (shouldSquash(message)) {
25102552 if (lastMessage && shouldSquash(lastMessage)) {
25112553 lastMessage.content += '\n' + message.content;
25122554 lastMessage.tokens = await tokenHandler.countcountAsync({ role: lastMessage.role, content: lastMessage.content });
25132555 }
25142556 else {
25152557 squashedMessages.push(message);