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 -20Ignore whitespace
public/index.html+7 -3
@@ -2048,16 +2048,20 @@
20482048 </span>
20492049 </div>
20502050 </div>
20512051 <div class="flex-container flexFlowColumn wide100p textAlignCenter marginTop10" data-source="openai,custom,claude,xai,makersuite">
20522052 <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.">
20532053 <label for="openai_reasoning_effort">
20542054 <span data-i18n="Reasoning Effort">Reasoning Effort</span>
20552055 <i data-source="claudeopenai,custom,xai" class="opacity50p fa-solid fa-circle-info" title="AllocatesOpenAI-style aoptions: portionlow, ofmedium, thehigh. responseMinimum lengthand formaximum thinkingare (low:aliased 10%,to medium:low 25%,and high:. 50%),Auto butdoes minimumnot 1024send tokensan 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>
20562057 </label>
20572058 <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>
20582061 <option data-i18n="openai_reasoning_effort_low" value="low">Low</option>
20592062 <option data-i18n="openai_reasoning_effort_medium" value="medium">Medium</option>
20602063 <option data-i18n="openai_reasoning_effort_high" value="high">High</option>
2064+ <option data-i18n="openai_reasoning_effort_maximum" value="max">Maximum</option>
20612065 </select>
20622066 </div>
20632067 </div>
public/scripts/openai.js+36 -3
@@ -216,6 +216,15 @@ const openrouter_middleout_types = {
216216 OFF: 'off',
217217};
218218
219+export const reasoning_effort_types = {
220+ auto: 'auto',
221+ low: 'low',
222+ medium: 'medium',
223+ high: 'high',
224+ min: 'min',
225+ max: 'max',
226+};
227+
219228const sensitiveFields = [
220229 'reverse_proxy',
221230 'proxy_password',
@@ -382,7 +391,7 @@ const default_settings = {
382391 continue_postfix: continue_postfix_types.SPACE,
383392 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
384393 show_thoughts: true,
385394 reasoning_effort: 'medium'reasoning_effort_types.auto,
386395 enable_web_search: false,
387396 request_images: false,
388397 seed: -1,
@@ -463,7 +472,7 @@ const oai_settings = {
463472 continue_postfix: continue_postfix_types.SPACE,
464473 custom_prompt_post_processing: custom_prompt_post_processing_types.NONE,
465474 show_thoughts: true,
466475 reasoning_effort: 'medium'reasoning_effort_types.auto,
467476 enable_web_search: false,
468477 request_images: false,
469478 seed: -1,
@@ -1937,6 +1946,30 @@ async function sendAltScaleRequest(messages, logit_bias, signal, type) {
19371946 return data.output;
19381947}
19391948
1949+function 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+
19401973/**
19411974 * Send a chat completion request to backend
19421975 * @param {string} type (impersonate, quiet, continue, etc)
@@ -2023,7 +2056,7 @@ async function sendOpenAIRequest(type, messages, signal) {
20232056 'char_name': name2,
20242057 'group_names': getGroupNames(),
20252058 'include_reasoning': Boolean(oai_settings.show_thoughts),
20262059 'reasoning_effort': StringgetReasoningEffort(oai_settings.reasoning_effort),
20272060 'enable_web_search': Boolean(oai_settings.enable_web_search),
20282061 'request_images': Boolean(oai_settings.request_images),
20292062 'custom_prompt_post_processing': oai_settings.custom_prompt_post_processing,
src/endpoints/backends/chat-completions.js+20 -5
@@ -28,7 +28,8 @@ import {
2828 cachingAtDepthForOpenRouterClaude,
2929 cachingAtDepthForClaude,
3030 getPromptNames,
3131 calculateBudgetTokenscalculateClaudeBudgetTokens,
32+ calculateGoogleBudgetTokens,
3233} from '../../prompt-converters.js';
3334
3435import { readSecret, SECRET_KEYS } from '../secrets.js';
@@ -202,7 +203,7 @@ async function sendClaudeRequest(request, response) {
202203 // No prefill when thinking
203204 voidPrefill = true;
204205 const reasoningEffort = request.body.reasoning_effort;
205206 const budgetTokens = calculateBudgetTokenscalculateClaudeBudgetTokens(requestBody.max_tokens, reasoningEffort, requestBody.stream);
206207 const minThinkTokens = 1024;
207208 if (requestBody.max_tokens <= minThinkTokens) {
208209 const newValue = requestBody.max_tokens + minThinkTokens;
@@ -340,6 +341,7 @@ async function sendMakerSuiteRequest(request, response) {
340341 const stream = Boolean(request.body.stream);
341342 const enableWebSearch = Boolean(request.body.enable_web_search);
342343 const requestImages = Boolean(request.body.request_images);
344+ const reasoningEffort = String(request.body.reasoning_effort);
343345 const isThinking = model.includes('thinking');
344346 const isGemma = model.includes('gemma');
345347
@@ -412,13 +414,26 @@ async function sendMakerSuiteRequest(request, response) {
412414 tools.push({ function_declarations: functionDeclarations });
413415 }
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+
415430 let body = {
416431 contents: prompt.contents,
417432 safetySettings: safetySettings,
418433 generationConfig: generationConfig,
419434 };
420435
421- if (useSystemPrompt) {
436+ if (useSystemPrompt && Array.isArray(prompt.system_instruction.parts) && prompt.system_instruction.parts.length) {
422437 body.systemInstruction = prompt.system_instruction;
423438 }
424439
@@ -868,7 +883,7 @@ async function sendXaiRequest(request, response) {
868883 bodyParams['stop'] = request.body.stop;
869884 }
870885
871886 if (request.body.reasoning_effort && ['grok-3-mini-beta', 'grok-3-mini-fast-beta'].includes(request.body.model)) {
872887 bodyParams['reasoning_effort'] = request.body.reasoning_effort === 'high' ? 'high' : 'low';
873888 }
874889
@@ -1258,7 +1273,7 @@ router.post('/generate', function (request, response) {
12581273 }
12591274
12601275 // A few of OpenAIs reasoning models support reasoning effort
12611276 if (request.body.reasoning_effort && [CHAT_COMPLETION_SOURCES.CUSTOM, CHAT_COMPLETION_SOURCES.OPENAI].includes(request.body.chat_completion_source)) {
12621277 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)) {
12631278 bodyParams['reasoning_effort'] = request.body.reasoning_effort;
12641279 }
src/prompt-converters.js+59 -9
@@ -3,6 +3,15 @@ import { getConfigValue, tryParse } from './util.js';
33
44const PROMPT_PLACEHOLDER = getConfigValue('promptPlaceholder', 'Let\'s get started.');
55
6+const REASONING_EFFORT = {
7+ auto: 'auto',
8+ low: 'low',
9+ medium: 'medium',
10+ high: 'high',
11+ min: 'min',
12+ max: 'max',
13+};
14+
615/**
716 * @typedef {object} PromptNames
817 * @property {string} charName Character name
@@ -356,7 +365,7 @@ export function convertCohereMessages(messages, names) {
356365 * @param {string} model Model name
357366 * @param {boolean} useSysPrompt Use system prompt
358367 * @param {PromptNames} names Prompt names
359368 * @returns {{contents: *[], system_instruction: {parts: {text: string}[]}}} Prompt for Google MakerSuite models
360369 */
361370export function convertGooglePrompt(messages, model, useSysPrompt, names) {
362371 const visionSupportedModels = [
@@ -394,8 +403,8 @@ export function convertGooglePrompt(messages, model, useSysPrompt, names) {
394403 ];
395404
396405 const isMultimodal = visionSupportedModels.includes(model);
406+ const sysPrompt = [];
397407
398- let sys_prompt = '';
399408 if (useSysPrompt) {
400409 while (messages.length > 1 && messages[0].role === 'system') {
401410 // 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) {
409418 messages[0].content = `${names.charName}: ${messages[0].content}`;
410419 }
411420 }
412- sys_prompt += `${messages[0].content}\n\n`;
421+ sysPrompt.push(messages[0].content);
413422 messages.shift();
414423 }
415424 }
416425
417426 const system_instruction = { parts: [{ sysPrompt.map(text: sys_prompt.trim=> (){ text }])) };
418427 const toolNameMap = {};
419428
420429 const contents = [];
@@ -944,25 +953,32 @@ export function cachingAtDepthForOpenRouterClaude(messages, cachingAtDepth) {
944953}
945954
946955/**
947956 * Calculate the Claude budget tokens for a given reasoning effort.
948957 * @param {number} maxTokens Maximum tokens
949958 * @param {string} reasoningEffort Reasoning effort
950959 * @param {boolean} stream If streaming is enabled
951960 * @returns {number} Budget tokens
952961 */
953962export function calculateBudgetTokenscalculateClaudeBudgetTokens(maxTokens, reasoningEffort, stream) {
954963 let budgetTokens = 0;
955964
956965 switch (reasoningEffort) {
957966 case 'low'REASONING_EFFORT.min:
967+ budgetTokens = 1024;
968+ break;
969+ case REASONING_EFFORT.low:
958970 budgetTokens = Math.floor(maxTokens * 0.1);
959971 break;
960972 case 'medium'REASONING_EFFORT.auto:
973+ case REASONING_EFFORT.medium:
961974 budgetTokens = Math.floor(maxTokens * 0.25);
962975 break;
963976 case 'REASONING_EFFORT.high':
964977 budgetTokens = Math.floor(maxTokens * 0.5);
965978 break;
979+ case REASONING_EFFORT.max:
980+ budgetTokens = Math.floor(maxTokens * 0.95);
981+ break;
966982 }
967983
968984 budgetTokens = Math.max(budgetTokens, 1024);
@@ -973,3 +989,37 @@ export function calculateBudgetTokens(maxTokens, reasoningEffort, stream) {
973989
974990 return budgetTokens;
975991}
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+ */
999+export 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+}