Merge pull request #3893 from SillyTavern/gemini-2.5-thinking Thinking Budget 2.5: Electric Googaloo

cfc41163e27568206efa804c029ed62e107fe262

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

Signed
4 files changed, +122 -20Showing whitespace changes
public/index.html+7 -3
@@ -2048,16 +2048,20 @@
2048 </span>2048 </span>
2049 </div>2049 </div>
2050 </div>2050 </div>
2051 <div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,claude,xai">2051 <div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,claude,xai,makersuite">
2052 <div class="flex-container oneline-dropdown" title="Constrains effort on reasoning for reasoning models.&#10;Currently supported values are low, medium, and high.&#10;Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response." data-i18n="[title]Constrains effort on reasoning for reasoning models.">2052 <div class="flex-container oneline-dropdown" title="Constrains effort on reasoning for reasoning models.&#10;Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response." data-i18n="[title]Constrains effort on reasoning for reasoning models.">
2053 <label for="openai_reasoning_effort">2053 <label for="openai_reasoning_effort">
2054 <span data-i18n="Reasoning Effort">Reasoning Effort</span>2054 <span data-i18n="Reasoning Effort">Reasoning Effort</span>
2055 <i data-source="claude" class="opacity50p fa-solid fa-circle-info" title="Allocates a portion of the response length for thinking (low: 10%, medium: 25%, high: 50%), but minimum 1024 tokens."></i>2055 <i data-source="openai,custom,xai" class="opacity50p fa-solid fa-circle-info" title="OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level."></i>
2056 <i data-source="claude,makersuite" class="opacity50p fa-solid fa-circle-info" title="Allocates a portion of the response length for thinking (low: 10%, medium: 25%, high: 50%). Other options are model-dependent."></i>
2056 </label>2057 </label>
2057 <select id="openai_reasoning_effort">2058 <select id="openai_reasoning_effort">
2059 <option data-i18n="openai_reasoning_effort_auto" value="auto">Auto</option>
2060 <option data-i18n="openai_reasoning_effort_minimum" value="min">Mininum</option>
2058 <option data-i18n="openai_reasoning_effort_low" value="low">Low</option>2061 <option data-i18n="openai_reasoning_effort_low" value="low">Low</option>
2059 <option data-i18n="openai_reasoning_effort_medium" value="medium">Medium</option>2062 <option data-i18n="openai_reasoning_effort_medium" value="medium">Medium</option>
2060 <option data-i18n="openai_reasoning_effort_high" value="high">High</option>2063 <option data-i18n="openai_reasoning_effort_high" value="high">High</option>
2064 <option data-i18n="openai_reasoning_effort_maximum" value="max">Maximum</option>
2061 </select>2065 </select>
2062 </div>2066 </div>
2063 </div>2067 </div>
public/scripts/openai.js+36 -3
@@ -216,6 +216,15 @@ const openrouter_middleout_types = {
216 OFF: 'off',216 OFF: 'off',
217};217};
218218
219export const reasoning_effort_types = {
220 auto: 'auto',
221 low: 'low',
222 medium: 'medium',
223 high: 'high',
224 min: 'min',
225 max: 'max',
226};
227
219const sensitiveFields = [228const sensitiveFields = [
220 'reverse_proxy',229 'reverse_proxy',
221 'proxy_password',230 'proxy_password',
@@ -382,7 +391,7 @@ const default_settings = {
382 continue_postfix: continue_postfix_types.SPACE,391 continue_postfix: continue_postfix_types.SPACE,
383 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,392 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
384 show_thoughts: true,393 show_thoughts: true,
385 reasoning_effort: 'medium',394 reasoning_effort: reasoning_effort_types.auto,
386 enable_web_search: false,395 enable_web_search: false,
387 request_images: false,396 request_images: false,
388 seed: -1,397 seed: -1,
@@ -463,7 +472,7 @@ const oai_settings = {
463 continue_postfix: continue_postfix_types.SPACE,472 continue_postfix: continue_postfix_types.SPACE,
464 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,473 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
465 show_thoughts: true,474 show_thoughts: true,
466 reasoning_effort: 'medium',475 reasoning_effort: reasoning_effort_types.auto,
467 enable_web_search: false,476 enable_web_search: false,
468 request_images: false,477 request_images: false,
469 seed: -1,478 seed: -1,
@@ -1937,6 +1946,30 @@ async function sendAltScaleRequest(messages, logit_bias, signal, type) {
1937 return data.output;1946 return data.output;
1938}1947}
19391948
1949function getReasoningEffort() {
1950 // These sources expect the effort as string.
1951 const reasoningEffortSources = [
1952 chat_completion_sources.OPENAI,
1953 chat_completion_sources.CUSTOM,
1954 chat_completion_sources.XAI,
1955 ];
1956
1957 if (!reasoningEffortSources.includes(oai_settings.chat_completion_source)) {
1958 return oai_settings.reasoning_effort;
1959 }
1960
1961 switch (oai_settings.reasoning_effort) {
1962 case reasoning_effort_types.auto:
1963 return undefined;
1964 case reasoning_effort_types.min:
1965 return reasoning_effort_types.low;
1966 case reasoning_effort_types.max:
1967 return reasoning_effort_types.high;
1968 default:
1969 return oai_settings.reasoning_effort;
1970 }
1971}
1972
1940/**1973/**
1941 * Send a chat completion request to backend1974 * Send a chat completion request to backend
1942 * @param {string} type (impersonate, quiet, continue, etc)1975 * @param {string} type (impersonate, quiet, continue, etc)
@@ -2023,7 +2056,7 @@ async function sendOpenAIRequest(type, messages, signal) {
2023 'char_name': name2,2056 'char_name': name2,
2024 'group_names': getGroupNames(),2057 'group_names': getGroupNames(),
2025 'include_reasoning': Boolean(oai_settings.show_thoughts),2058 'include_reasoning': Boolean(oai_settings.show_thoughts),
2026 'reasoning_effort': String(oai_settings.reasoning_effort),2059 'reasoning_effort': getReasoningEffort(),
2027 'enable_web_search': Boolean(oai_settings.enable_web_search),2060 'enable_web_search': Boolean(oai_settings.enable_web_search),
2028 'request_images': Boolean(oai_settings.request_images),2061 'request_images': Boolean(oai_settings.request_images),
2029 'custom_prompt_post_processing': oai_settings.custom_prompt_post_processing,2062 'custom_prompt_post_processing': oai_settings.custom_prompt_post_processing,
src/endpoints/backends/chat-completions.js+20 -5
@@ -28,7 +28,8 @@ import {
28 cachingAtDepthForOpenRouterClaude,28 cachingAtDepthForOpenRouterClaude,
29 cachingAtDepthForClaude,29 cachingAtDepthForClaude,
30 getPromptNames,30 getPromptNames,
31 calculateBudgetTokens,31 calculateClaudeBudgetTokens,
32 calculateGoogleBudgetTokens,
32} from '../../prompt-converters.js';33} from '../../prompt-converters.js';
3334
34import { readSecret, SECRET_KEYS } from '../secrets.js';35import { readSecret, SECRET_KEYS } from '../secrets.js';
@@ -202,7 +203,7 @@ async function sendClaudeRequest(request, response) {
202 // No prefill when thinking203 // No prefill when thinking
203 voidPrefill = true;204 voidPrefill = true;
204 const reasoningEffort = request.body.reasoning_effort;205 const reasoningEffort = request.body.reasoning_effort;
205 const budgetTokens = calculateBudgetTokens(requestBody.max_tokens, reasoningEffort, requestBody.stream);206 const budgetTokens = calculateClaudeBudgetTokens(requestBody.max_tokens, reasoningEffort, requestBody.stream);
206 const minThinkTokens = 1024;207 const minThinkTokens = 1024;
207 if (requestBody.max_tokens <= minThinkTokens) {208 if (requestBody.max_tokens <= minThinkTokens) {
208 const newValue = requestBody.max_tokens + minThinkTokens;209 const newValue = requestBody.max_tokens + minThinkTokens;
@@ -340,6 +341,7 @@ async function sendMakerSuiteRequest(request, response) {
340 const stream = Boolean(request.body.stream);341 const stream = Boolean(request.body.stream);
341 const enableWebSearch = Boolean(request.body.enable_web_search);342 const enableWebSearch = Boolean(request.body.enable_web_search);
342 const requestImages = Boolean(request.body.request_images);343 const requestImages = Boolean(request.body.request_images);
344 const reasoningEffort = String(request.body.reasoning_effort);
343 const isThinking = model.includes('thinking');345 const isThinking = model.includes('thinking');
344 const isGemma = model.includes('gemma');346 const isGemma = model.includes('gemma');
345347
@@ -412,13 +414,26 @@ async function sendMakerSuiteRequest(request, response) {
412 tools.push({ function_declarations: functionDeclarations });414 tools.push({ function_declarations: functionDeclarations });
413 }415 }
414416
417 // One more models list to maintain, yay
418 const thinkingBudgetModels = [
419 'gemini-2.5-flash-preview-04-17',
420 ];
421
422 if (thinkingBudgetModels.includes(model)) {
423 const thinkingBudget = calculateGoogleBudgetTokens(generationConfig.maxOutputTokens, reasoningEffort);
424
425 if (Number.isInteger(thinkingBudget)) {
426 generationConfig.thinkingConfig = { thinkingBudget: thinkingBudget };
427 }
428 }
429
415 let body = {430 let body = {
416 contents: prompt.contents,431 contents: prompt.contents,
417 safetySettings: safetySettings,432 safetySettings: safetySettings,
418 generationConfig: generationConfig,433 generationConfig: generationConfig,
419 };434 };
420435
421 if (useSystemPrompt) {436 if (useSystemPrompt && Array.isArray(prompt.system_instruction.parts) && prompt.system_instruction.parts.length) {
422 body.systemInstruction = prompt.system_instruction;437 body.systemInstruction = prompt.system_instruction;
423 }438 }
424439
@@ -868,7 +883,7 @@ async function sendXaiRequest(request, response) {
868 bodyParams['stop'] = request.body.stop;883 bodyParams['stop'] = request.body.stop;
869 }884 }
870885
871 if (['grok-3-mini-beta', 'grok-3-mini-fast-beta'].includes(request.body.model)) {886 if (request.body.reasoning_effort && ['grok-3-mini-beta', 'grok-3-mini-fast-beta'].includes(request.body.model)) {
872 bodyParams['reasoning_effort'] = request.body.reasoning_effort === 'high' ? 'high' : 'low';887 bodyParams['reasoning_effort'] = request.body.reasoning_effort === 'high' ? 'high' : 'low';
873 }888 }
874889
@@ -1258,7 +1273,7 @@ router.post('/generate', function (request, response) {
1258 }1273 }
12591274
1260 // A few of OpenAIs reasoning models support reasoning effort1275 // A few of OpenAIs reasoning models support reasoning effort
1261 if ([CHAT_COMPLETION_SOURCES.CUSTOM, CHAT_COMPLETION_SOURCES.OPENAI].includes(request.body.chat_completion_source)) {1276 if (request.body.reasoning_effort && [CHAT_COMPLETION_SOURCES.CUSTOM, CHAT_COMPLETION_SOURCES.OPENAI].includes(request.body.chat_completion_source)) {
1262 if (['o1', 'o3-mini', 'o3-mini-2025-01-31', 'o4-mini', 'o4-mini-2025-04-16', 'o3', 'o3-2025-04-16'].includes(request.body.model)) {1277 if (['o1', 'o3-mini', 'o3-mini-2025-01-31', 'o4-mini', 'o4-mini-2025-04-16', 'o3', 'o3-2025-04-16'].includes(request.body.model)) {
1263 bodyParams['reasoning_effort'] = request.body.reasoning_effort;1278 bodyParams['reasoning_effort'] = request.body.reasoning_effort;
1264 }1279 }
src/prompt-converters.js+59 -9
@@ -3,6 +3,15 @@ import { getConfigValue, tryParse } from './util.js';
33
4const PROMPT_PLACEHOLDER = getConfigValue('promptPlaceholder', 'Let\'s get started.');4const PROMPT_PLACEHOLDER = getConfigValue('promptPlaceholder', 'Let\'s get started.');
55
6const REASONING_EFFORT = {
7 auto: 'auto',
8 low: 'low',
9 medium: 'medium',
10 high: 'high',
11 min: 'min',
12 max: 'max',
13};
14
6/**15/**
7 * @typedef {object} PromptNames16 * @typedef {object} PromptNames
8 * @property {string} charName Character name17 * @property {string} charName Character name
@@ -356,7 +365,7 @@ export function convertCohereMessages(messages, names) {
356 * @param {string} model Model name365 * @param {string} model Model name
357 * @param {boolean} useSysPrompt Use system prompt366 * @param {boolean} useSysPrompt Use system prompt
358 * @param {PromptNames} names Prompt names367 * @param {PromptNames} names Prompt names
359 * @returns {{contents: *[], system_instruction: {parts: {text: string}}}} Prompt for Google MakerSuite models368 * @returns {{contents: *[], system_instruction: {parts: {text: string}[]}}} Prompt for Google MakerSuite models
360 */369 */
361export function convertGooglePrompt(messages, model, useSysPrompt, names) {370export function convertGooglePrompt(messages, model, useSysPrompt, names) {
362 const visionSupportedModels = [371 const visionSupportedModels = [
@@ -394,8 +403,8 @@ export function convertGooglePrompt(messages, model, useSysPrompt, names) {
394 ];403 ];
395404
396 const isMultimodal = visionSupportedModels.includes(model);405 const isMultimodal = visionSupportedModels.includes(model);
406 const sysPrompt = [];
397407
398 let sys_prompt = '';
399 if (useSysPrompt) {408 if (useSysPrompt) {
400 while (messages.length > 1 && messages[0].role === 'system') {409 while (messages.length > 1 && messages[0].role === 'system') {
401 // Append example names if not already done by the frontend (e.g. for group chats).410 // Append example names if not already done by the frontend (e.g. for group chats).
@@ -409,12 +418,12 @@ export function convertGooglePrompt(messages, model, useSysPrompt, names) {
409 messages[0].content = `${names.charName}: ${messages[0].content}`;418 messages[0].content = `${names.charName}: ${messages[0].content}`;
410 }419 }
411 }420 }
412 sys_prompt += `${messages[0].content}\n\n`;421 sysPrompt.push(messages[0].content);
413 messages.shift();422 messages.shift();
414 }423 }
415 }424 }
416425
417 const system_instruction = { parts: [{ text: sys_prompt.trim() }] };426 const system_instruction = { parts: sysPrompt.map(text => ({ text })) };
418 const toolNameMap = {};427 const toolNameMap = {};
419428
420 const contents = [];429 const contents = [];
@@ -944,25 +953,32 @@ export function cachingAtDepthForOpenRouterClaude(messages, cachingAtDepth) {
944}953}
945954
946/**955/**
947 * Calculate the budget tokens for a given reasoning effort.956 * Calculate the Claude budget tokens for a given reasoning effort.
948 * @param {number} maxTokens Maximum tokens957 * @param {number} maxTokens Maximum tokens
949 * @param {string} reasoningEffort Reasoning effort958 * @param {string} reasoningEffort Reasoning effort
950 * @param {boolean} stream If streaming is enabled959 * @param {boolean} stream If streaming is enabled
951 * @returns {number} Budget tokens960 * @returns {number} Budget tokens
952 */961 */
953export function calculateBudgetTokens(maxTokens, reasoningEffort, stream) {962export function calculateClaudeBudgetTokens(maxTokens, reasoningEffort, stream) {
954 let budgetTokens = 0;963 let budgetTokens = 0;
955964
956 switch (reasoningEffort) {965 switch (reasoningEffort) {
957 case 'low':966 case REASONING_EFFORT.min:
967 budgetTokens = 1024;
968 break;
969 case REASONING_EFFORT.low:
958 budgetTokens = Math.floor(maxTokens * 0.1);970 budgetTokens = Math.floor(maxTokens * 0.1);
959 break;971 break;
960 case 'medium':972 case REASONING_EFFORT.auto:
973 case REASONING_EFFORT.medium:
961 budgetTokens = Math.floor(maxTokens * 0.25);974 budgetTokens = Math.floor(maxTokens * 0.25);
962 break;975 break;
963 case 'high':976 case REASONING_EFFORT.high:
964 budgetTokens = Math.floor(maxTokens * 0.5);977 budgetTokens = Math.floor(maxTokens * 0.5);
965 break;978 break;
979 case REASONING_EFFORT.max:
980 budgetTokens = Math.floor(maxTokens * 0.95);
981 break;
966 }982 }
967983
968 budgetTokens = Math.max(budgetTokens, 1024);984 budgetTokens = Math.max(budgetTokens, 1024);
@@ -973,3 +989,37 @@ export function calculateBudgetTokens(maxTokens, reasoningEffort, stream) {
973989
974 return budgetTokens;990 return budgetTokens;
975}991}
992
993/**
994 * Calculate the Google budget tokens for a given reasoning effort.
995 * @param {number} maxTokens Maximum tokens
996 * @param {string} reasoningEffort Reasoning effort
997 * @returns {number?} Budget tokens
998 */
999export function calculateGoogleBudgetTokens(maxTokens, reasoningEffort) {
1000 let budgetTokens = 0;
1001
1002 switch (reasoningEffort) {
1003 case REASONING_EFFORT.auto:
1004 return null;
1005 case REASONING_EFFORT.min:
1006 budgetTokens = 0;
1007 break;
1008 case REASONING_EFFORT.low:
1009 budgetTokens = Math.floor(maxTokens * 0.1);
1010 break;
1011 case REASONING_EFFORT.medium:
1012 budgetTokens = Math.floor(maxTokens * 0.25);
1013 break;
1014 case REASONING_EFFORT.high:
1015 budgetTokens = Math.floor(maxTokens * 0.5);
1016 break;
1017 case REASONING_EFFORT.max:
1018 budgetTokens = maxTokens;
1019 break;
1020 }
1021
1022 budgetTokens = Math.min(budgetTokens, 24576);
1023
1024 return budgetTokens;
1025}