Merge pull request #3484 from SillyTavern/reasoning-parsing-streaming Implement reasoning parsing during streaming, based on provided prefix/suffix

d15d49b295b0f84c8ed1a480043f605e71e768f9

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

Signed
3 files changed, +130 -24Showing whitespace changes
public/script.js+2 -1
@@ -3223,6 +3223,7 @@ class StreamingProcessor {
32233223
32243224 // Update reasoning
32253225 await this.reasoningHandler.process(messageId, mesChanged);
3226+ processedText = chat[messageId]['mes'];
32263227
32273228 // Token count update.
32283229 const tokenCountText = this.reasoningHandler.reasoning + processedText;
@@ -3373,7 +3374,7 @@ class StreamingProcessor {
33733374 this.messageLogprobs.push(...(Array.isArray(logprobs) ? logprobs : [logprobs]));
33743375 }
33753376 // Get the updated reasoning string into the handler
33763377 this.reasoningHandler.updateReasoning(this.messageId, state?.reasoning ?? '');
33773378 await eventSource.emit(event_types.STREAM_TOKEN_RECEIVED, text);
33783379 await sw.tick(async () => await this.onProgressStreaming(this.messageId, this.continueMessage + text));
33793380 }
public/scripts/reasoning.js+114 -22
@@ -3,7 +3,7 @@ import {
33} from '../lib.js';
44import { chat, closeMessageEditor, event_types, eventSource, main_api, messageFormatting, saveChatConditional, saveSettingsDebounced, substituteParams, updateMessageBlock } from '../script.js';
55import { getRegexedString, regex_placement } from './extensions/regex/engine.js';
66import { getCurrentLocale, t, translate } from './i18n.js';
77import { MacrosParser } from './macros.js';
88import { chat_completion_sources, getChatCompletionModel, oai_settings } from './openai.js';
99import { Popup } from './popup.js';
@@ -14,7 +14,19 @@ import { commonEnumProviders, enumIcons } from './slash-commands/SlashCommandCom
1414import { enumTypes, SlashCommandEnumValue } from './slash-commands/SlashCommandEnumValue.js';
1515import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
1616import { textgen_types, textgenerationwebui_settings } from './textgen-settings.js';
1717import { copyText, escapeRegex, isFalseBoolean, setDatasetProperty, trimSpaces } from './utils.js';
18+
19+/**
20+ * Enum representing the type of the reasoning for a message (where it came from)
21+ * @enum {string}
22+ * @readonly
23+ */
24+export const ReasoningType = {
25+ Model: 'model',
26+ Parsed: 'parsed',
27+ Manual: 'manual',
28+ Edited: 'edited',
29+};
1830
1931/**
2032 * Gets a message from a jQuery element.
@@ -130,7 +142,12 @@ export const ReasoningState = {
130142 * This class is used inside the {@link StreamingProcessor} to manage reasoning states and UI updates.
131143 */
132144export class ReasoningHandler {
145+ /** @type {boolean} True if the model supports reasoning, but hides the reasoning output */
133146 #isHiddenReasoningModel;
147+ /** @type {boolean} True if the handler is currently handling a manual parse of reasoning blocks */
148+ #isParsingReasoning = false;
149+ /** @type {number?} When reasoning is being parsed manually, and the reasoning has ended, this will be the index at which the actual messages starts */
150+ #parsingReasoningMesStartIndex = null;
134151
135152 /**
136153 * @param {Date?} [timeStarted=null] - When the generation started
@@ -138,6 +155,8 @@ export class ReasoningHandler {
138155 constructor(timeStarted = null) {
139156 /** @type {ReasoningState} The current state of the reasoning process */
140157 this.state = ReasoningState.None;
158+ /** @type {ReasoningType?} The type of the reasoning (where it came from) */
159+ this.type = null;
141160 /** @type {string} The reasoning output */
142161 this.reasoning = '';
143162 /** @type {Date} When the reasoning started */
@@ -148,7 +167,6 @@ export class ReasoningHandler {
148167 /** @type {Date} Initial starting time of the generation */
149168 this.initialTime = timeStarted ?? new Date();
150169
151- /** @type {boolean} True if the model supports reasoning, but hides the reasoning output */
152170 this.#isHiddenReasoningModel = isHiddenReasoningModel();
153171
154172 // Cached DOM elements for reasoning
@@ -195,6 +213,7 @@ export class ReasoningHandler {
195213 this.state = ReasoningState.Hidden;
196214 }
197215
216+ this.type = extra?.reasoning_type;
198217 this.reasoning = extra?.reasoning ?? '';
199218
200219 if (this.state !== ReasoningState.None) {
@@ -209,6 +228,7 @@ export class ReasoningHandler {
209228 // Make sure reset correctly clears all relevant states
210229 if (reset) {
211230 this.state = this.#isHiddenReasoningModel ? ReasoningState.Thinking : ReasoningState.None;
231+ this.type = null;
212232 this.reasoning = '';
213233 this.initialTime = new Date();
214234 this.startTime = null;
@@ -238,18 +258,19 @@ export class ReasoningHandler {
238258 * Updates the reasoning text/string for a message.
239259 *
240260 * @param {number} messageId - The ID of the message to update
241261 * @param {string?} [reasoning=null] - The reasoning text to update - If null or empty, uses the current reasoning
242262 * @param {Object} [options={}] - Optional arguments
243263 * @param {boolean} [options.persist=false] - Whether to persist the reasoning to the message object
264+ * @param {boolean} [options.allowReset=false] - Whether to allow empty reasoning provided to reset the reasoning, instead of just taking the existing one
244265 * @returns {boolean} - Returns true if the reasoning was changed, otherwise false
245266 */
246267 updateReasoning(messageId, reasoning = null, { persist = false, allowReset = false } = {}) {
247268 if (messageId == -1 || !chat[messageId]) {
248269 return false;
249270 }
250271
251272 reasoning = allowReset ? reasoning ?? this.reasoning : reasoning || this.reasoning;
252273 reasoning = power_user.trim_spaces ? reasoning.trimtrimSpaces() : reasoning);
253274
254275 // Ensure the chat extra exists
255276 if (!chat[messageId].extra) {
@@ -260,10 +281,13 @@ export class ReasoningHandler {
260281 const reasoningChanged = extra.reasoning !== reasoning;
261282 this.reasoning = getRegexedString(reasoning ?? '', regex_placement.REASONING);
262283
284+ this.type = (this.#isParsingReasoning || this.#parsingReasoningMesStartIndex) ? ReasoningType.Parsed : ReasoningType.Model;
285+
263286 if (persist) {
264287 // Build and save the reasoning data to message extras
265288 extra.reasoning = this.reasoning;
266289 extra.reasoning_duration = this.getDuration();
290+ extra.reasoning_type = (this.#isParsingReasoning || this.#parsingReasoningMesStartIndex) ? ReasoningType.Parsed : ReasoningType.Model;
267291 }
268292
269293 return reasoningChanged;
@@ -280,7 +304,10 @@ export class ReasoningHandler {
280304 * @returns {Promise<void>}
281305 */
282306 async process(messageId, mesChanged) {
283- if (!this.reasoning && !this.#isHiddenReasoningModel) return;
307+ mesChanged = this.#autoParseReasoningFromMessage(messageId, mesChanged);
308+
309+ if (!this.reasoning && !this.#isHiddenReasoningModel)
310+ return;
284311
285312 // Ensure reasoning string is updated and regexes are applied correctly
286313 const reasoningChanged = this.updateReasoning(messageId, null, { persist: true });
@@ -295,6 +322,53 @@ export class ReasoningHandler {
295322 }
296323 }
297324
325+ #autoParseReasoningFromMessage(messageId, mesChanged) {
326+ if (!power_user.reasoning.auto_parse)
327+ return;
328+ if (!power_user.reasoning.prefix || !power_user.reasoning.suffix)
329+ return mesChanged;
330+
331+ /** @type {{ mes: string, [key: string]: any}} */
332+ const message = chat[messageId];
333+ if (!message) return mesChanged;
334+
335+ // If we are done with reasoning parse, we just split the message correctly so the reasoning doesn't show up inside of it.
336+ if (this.#parsingReasoningMesStartIndex) {
337+ message.mes = trimSpaces(message.mes.slice(this.#parsingReasoningMesStartIndex));
338+ return mesChanged;
339+ }
340+
341+ if (this.state === ReasoningState.None) {
342+ // If streamed message starts with the opening, cut it out and put all inside reasoning
343+ if (message.mes.startsWith(power_user.reasoning.prefix) && message.mes.length > power_user.reasoning.prefix.length) {
344+ this.#isParsingReasoning = true;
345+
346+ // Manually set starting state here, as we might already have received the ending suffix
347+ this.state = ReasoningState.Thinking;
348+ this.startTime = this.initialTime;
349+ }
350+ }
351+
352+ if (!this.#isParsingReasoning)
353+ return mesChanged;
354+
355+ // If we are in manual parsing mode, all currently streaming mes tokens will go the the reasoning block
356+ const originalMes = message.mes;
357+ this.reasoning = originalMes.slice(power_user.reasoning.prefix.length);
358+ message.mes = '';
359+
360+ // If the reasoning contains the ending suffix, we cut that off and continue as message streaming
361+ if (this.reasoning.includes(power_user.reasoning.suffix)) {
362+ this.reasoning = this.reasoning.slice(0, this.reasoning.indexOf(power_user.reasoning.suffix));
363+ this.#parsingReasoningMesStartIndex = originalMes.indexOf(power_user.reasoning.suffix) + power_user.reasoning.suffix.length;
364+ message.mes = trimSpaces(originalMes.slice(this.#parsingReasoningMesStartIndex));
365+ this.#isParsingReasoning = false;
366+ }
367+
368+ // Only return the original mesChanged value if we haven't cut off the complete message
369+ return message.mes.length ? mesChanged : false;
370+ }
371+
298372 /**
299373 * Completes the reasoning process for a message.
300374 *
@@ -337,9 +411,10 @@ export class ReasoningHandler {
337411 // Update states to the relevant DOM elements
338412 setDatasetProperty(this.messageDom, 'reasoningState', this.state !== ReasoningState.None ? this.state : null);
339413 setDatasetProperty(this.messageReasoningDetailsDom, 'state', this.state);
414+ setDatasetProperty(this.messageReasoningDetailsDom, 'type', this.type);
340415
341416 // Update the reasoning message
342417 const reasoning = power_user.trim_spaces ? this.reasoning.trimtrimSpaces() : this.reasoning);
343418 const displayReasoning = messageFormatting(reasoning, '', false, false, messageId, {}, true);
344419 this.messageReasoningContentDom.innerHTML = displayReasoning;
345420
@@ -394,17 +469,14 @@ export class ReasoningHandler {
394469 const element = this.messageReasoningHeaderDom;
395470 const duration = this.getDuration();
396471 let data = null;
472+ let title = '';
397473 if (duration) {
398474 const durationStrseconds = moment.duration(duration).locale(getCurrentLocale()).humanizeasSeconds({ s: 50, ss: 3 });
399- const secondsStr = moment.duration(duration).asSeconds();
400-
401- const span = document.createElement('span');
402- span.title = t`${secondsStr} seconds`;
403- span.textContent = durationStr;
404475
405- element.textContent = t`Thought for `;
476+ const durationStr = moment.duration(duration).locale(getCurrentLocale()).humanize({ s: 50, ss: 3 });
406- element.appendChild(span);
477+ element.textContent = t`Thought for ${durationStr}`;
407478 data = String(secondsStrseconds);
479+ title = `${seconds} seconds`;
408480 } else if ([ReasoningState.Done, ReasoningState.Hidden].includes(this.state)) {
409481 element.textContent = t`Thought for some time`;
410482 data = 'unknown';
@@ -413,6 +485,12 @@ export class ReasoningHandler {
413485 data = null;
414486 }
415487
488+ if (this.type !== ReasoningType.Model) {
489+ title += ` [${translate(this.type)}]`;
490+ title = title.trim();
491+ }
492+ element.title = title;
493+
416494 setDatasetProperty(this.messageReasoningDetailsDom, 'duration', data);
417495 setDatasetProperty(element, 'duration', data);
418496 }
@@ -574,11 +652,16 @@ function registerReasoningSlashCommands() {
574652 callback: async (args, value) => {
575653 const messageId = !isNaN(Number(args.at)) ? Number(args.at) : chat.length - 1;
576654 const message = chat[messageId];
577655 if (!message?.extra) {
578656 return '';
579657 }
658+ // Make sure the message has an extra object
659+ if (!message.extra || typeof message.extra !== 'object') {
660+ message.extra = {};
661+ }
580662
581663 message.extra.reasoning = String(value ?? '');
664+ message.extra.reasoning_type = ReasoningType.Manual;
582665 await saveChatConditional();
583666
584667 closeMessageEditor('reasoning');
@@ -748,6 +831,7 @@ function setReasoningEventHandlers() {
748831 const textarea = messageBlock.find('.reasoning_edit_textarea');
749832 const reasoning = getRegexedString(String(textarea.val()), regex_placement.REASONING, { isEdit: true });
750833 message.extra.reasoning = reasoning;
834+ message.extra.reasoning_type = message.extra.reasoning_type ? ReasoningType.Edited : ReasoningType.Manual;
751835 await saveChatConditional();
752836 updateMessageBlock(messageId, message);
753837 textarea.remove();
@@ -808,6 +892,8 @@ function setReasoningEventHandlers() {
808892 return;
809893 }
810894 message.extra.reasoning = '';
895+ delete message.extra.reasoning_type;
896+ delete message.extra.reasoning_duration;
811897 await saveChatConditional();
812898 updateMessageBlock(messageId, message);
813899 const textarea = messageBlock.find('.reasoning_edit_textarea');
@@ -868,9 +954,9 @@ function parseReasoningFromString(str, { strict = true } = {}) {
868954 return '';
869955 });
870956
871957 if (didReplace && power_user.trim_spaces) {
872958 reasoning = reasoning.trimtrimSpaces(reasoning);
873959 content = content.trimtrimSpaces(content);
874960 }
875961
876962 return { reasoning, content };
@@ -899,6 +985,11 @@ function registerReasoningAppEvents() {
899985 return null;
900986 }
901987
988+ if (message.extra?.reasoning) {
989+ console.debug('[Reasoning] Message already has reasoning', idx);
990+ return null;
991+ }
992+
902993 const parsedReasoning = parseReasoningFromString(message.mes);
903994
904995 // No reasoning block found
@@ -916,6 +1007,7 @@ function registerReasoningAppEvents() {
9161007 // If reasoning was found, add it to the message
9171008 if (parsedReasoning.reasoning) {
9181009 message.extra.reasoning = getRegexedString(parsedReasoning.reasoning, regex_placement.REASONING);
1010+ message.extra.reasoning_type = ReasoningType.Parsed;
9191011 }
9201012
9211013 // Update the message text if it was changed
public/scripts/utils.js+14 -1
@@ -8,7 +8,7 @@ import {
88import { getContext } from './extensions.js';
99import { characters, getRequestHeaders, this_chid } from '../script.js';
1010import { isMobile } from './RossAscends-mods.js';
1111import { collapseNewlines, power_user } from './power-user.js';
1212import { debounce_timeout } from './constants.js';
1313import { Popup, POPUP_RESULT, POPUP_TYPE } from './popup.js';
1414import { SlashCommandClosure } from './slash-commands/SlashCommandClosure.js';
@@ -677,6 +677,19 @@ export function sortByCssOrder(a, b) {
677677}
678678
679679/**
680+ * Trims leading and trailing whitespace from the input string based on a configuration setting.
681+ * @param {string} input - The string to be trimmed
682+ * @returns {string} The trimmed string if trimming is enabled; otherwise, returns the original string
683+ */
684+
685+export function trimSpaces(input) {
686+ if (!input || typeof input !== 'string') {
687+ return input;
688+ }
689+ return power_user.trim_spaces ? input.trim() : input;
690+}
691+
692+/**
680693 * Trims a string to the end of a nearest sentence.
681694 * @param {string} input The string to trim.
682695 * @returns {string} The trimmed string.