Files
DeepTutor/web/lib/reasoning-effort.ts
OrdoAbChao7 d7240fd377 fix(llm,web): address PR #2938 review findings
- Check value-constraint markers before parameter-unknown markers in
  classify_reasoning_param_error so mixed phrasings like
  'Unsupported parameter: ... Supported values are ...' retry once
  without disabling reasoning params for the whole endpoint.
- Align MiniMax-M3 Thinking toggle (none/high) across backend
  resolve_reasoning_control and frontend validation so turning
  Thinking on survives effectiveReasoningEffort/dropUnvalidatedReasoningEffort.
- Filter non-chat model IDs (e.g. text-embedding-3-small) when /models
  probe entries omit services metadata.
- Cancel and discard stale in-flight Quick Setup probe/apply responses
  when switching vendors/regions or closing the form so old responses
  cannot save the prior vendor or clear the newly entered API key.
- Sync THINKING_OFF_EFFORTS symbol rename from upstream/dev.
2026-12-02 10:29:30 +08:00

613 lines
20 KiB
TypeScript

export type ReasoningEffortOption = {
value: string;
label: string;
};
/**
* The wire vocabulary a turn's `llm_selection.reasoning_effort` may carry —
* mirrors `VALID_REASONING_EFFORTS` in deeptutor/services/model_selection/llm.py.
* Values outside this set (e.g. provider-specific "adaptive") are rejected by
* the backend turn contract, so chat-side pickers must filter them out.
*/
export const VALID_REASONING_EFFORTS: ReadonlySet<string> = new Set([
"none",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
]);
/**
* Normalize an untrusted reasoning-effort value from persisted state.
* Returns the lowercase value when it is a legal wire value, else null —
* illegal values are dropped rather than forwarded to the provider.
*/
export function normalizeReasoningEffort(value: unknown): string | null {
if (typeof value !== "string") return null;
const normalized = value.trim().toLowerCase();
return normalized && VALID_REASONING_EFFORTS.has(normalized)
? normalized
: null;
}
const LABELS: Record<string, string> = {
"": "Provider default (Auto)",
none: "None",
minimal: "Minimal",
low: "Low",
medium: "Medium",
high: "High",
xhigh: "Extra high",
max: "Maximum",
adaptive: "Adaptive",
};
// Mirrors the reasoning-relevant half of PROVIDER_ALIASES in
// deeptutor/services/provider_registry.py. A profile stored as "azure" or
// "openai-compatible" resolves to the same adapter as its canonical name, so
// the lookup below has to see the canonical name or the selector vanishes.
const PROVIDER_ALIASES: Record<string, string> = {
azure: "azure_openai",
azureopenai: "azure_openai",
google: "gemini",
google_genai: "gemini",
claude: "anthropic",
openai_compatible: "custom",
anthropic_compatible: "custom_anthropic",
};
const STD_LEVELS = ["none", "low", "medium", "high"];
const ADAPTIVE_LEVELS = ["none", "adaptive"];
const DEEPSEEK_DEFAULT_ON = [
"deepseek-reasoner",
"deepseek-v4-pro",
"deepseek-v4-flash",
"deepseek-v4.1-flash",
"deepseek-flash",
];
const QWEN_THINKING = ["qwen3", "qwen-3", "qwq", "qwen-plus"];
const OPENAI_PROVIDERS = new Set([
"openai",
"azure_openai",
"openai_codex",
"github_copilot",
]);
const BINARY_THINKING_PROVIDERS = new Set([
"deepseek",
"volcengine",
"volcengine_coding_plan",
"byteplus",
"byteplus_coding_plan",
"dashscope",
"minimax",
]);
const EXTRA_MINIMAL_OFF_PROVIDERS = new Set([
"siliconflow",
"zhipu",
"moonshot",
]);
function isMinimalOffProvider(provider: string): boolean {
return (
BINARY_THINKING_PROVIDERS.has(provider) ||
EXTRA_MINIMAL_OFF_PROVIDERS.has(provider)
);
}
function isThinkingEnabled(value: string): boolean {
return value !== "none" && value !== "minimal" && value !== "minimum";
}
function includesAny(value: string, patterns: string[]): boolean {
return patterns.some((pattern) => value.includes(pattern));
}
function options(values: string[], current: string): ReasoningEffortOption[] {
const normalizedCurrent = current.trim().toLowerCase();
const resolved = [...values];
if (normalizedCurrent && !resolved.includes(normalizedCurrent)) {
resolved.push(normalizedCurrent);
}
if (resolved.length === 0) return [];
return ["", ...resolved].map((value) => ({
value,
label: LABELS[value] ?? value,
}));
}
/**
* Return conservative reasoning-effort choices for a provider/model pair.
*
* The provider adapters do not share one universal enum. In particular,
* Gemini 3 and Gemini 2.5 Pro reject `none`, while several OpenAI-compatible
* providers only expose an on/off thinking switch. Unknown model families stay
* hidden unless a catalog already contains an explicit value.
*
* A value already stored for the model is always listed even when this table
* excludes it, so a hand-edited or newly-invalidated setting stays visible and
* can be reset to Auto — that is the recovery path for a profile that is
* currently sending a value its provider rejects.
*/
export function reasoningEffortOptions(
binding: string | null | undefined,
model: string | null | undefined,
current = "",
declaredReasoning?: boolean | null,
): ReasoningEffortOption[] {
const fromTables = tableReasoningEffortOptions(binding, model, current);
// A user who declared the model's reasoning support in Settings overrides
// the tables: "yes" exposes the cross-gateway levels when the tables know
// nothing, "no" hides the control (a stored value stays visible so it can
// still be reset).
if (declaredReasoning === true && fromTables.length === 0) {
return options(STD_LEVELS, current);
}
if (declaredReasoning === false) {
return options([], current);
}
return fromTables;
}
function tableReasoningEffortOptions(
binding: string | null | undefined,
model: string | null | undefined,
current: string,
): ReasoningEffortOption[] {
const provider = canonicalProvider(binding);
const modelName = (model ?? "").trim().toLowerCase();
if (provider === "minimax" || provider === "minimax_anthropic") {
if (modelName === "minimax-m3.1-flash") {
return options(["low", "medium", "high", "xhigh", "max"], current);
}
if (modelName === "minimax-m3") {
return options(ADAPTIVE_LEVELS, current);
}
}
if (provider === "gemini" || modelName.includes("gemini")) {
if (
modelName.includes("gemini-3") ||
modelName.includes("gemini-2.5-pro")
) {
return options(["minimal", "low", "medium", "high"], current);
}
return options(
modelName.includes("gemini-2.5") ? STD_LEVELS : STD_LEVELS.slice(1),
current,
);
}
if (
provider === "anthropic" ||
provider === "custom_anthropic" ||
modelName.includes("claude")
) {
// Effort-based families (Opus 4.7 onward) take `thinking: {type:
// "adaptive"}` and reject enabled+budget_tokens; the older thinking
// families are the mirror image and 400 on adaptive. Keep the two lists
// aligned with _EFFORT_BASED_FAMILIES in
// deeptutor/services/llm/provider_core/anthropic_provider.py.
if (
includesAny(modelName, [
"opus-4-7",
"opus-4-8",
"opus-5",
"sonnet-5",
"fable-5",
"mythos-5",
])
) {
return options(ADAPTIVE_LEVELS, current);
}
return options(
includesAny(modelName, [
"claude-3-7",
"claude-4",
"claude-sonnet-4",
"claude-opus-4",
"claude-haiku-4",
])
? STD_LEVELS
: [],
current,
);
}
if (
(OPENAI_PROVIDERS.has(provider) ||
provider === "custom" ||
provider === "zhipu") &&
(modelName === "glm-5.3" || modelName.endsWith("/glm-5.3"))
) {
// GLM-5.3 always thinks; older GLM families have different controls.
// https://docs.bigmodel.cn/cn/guide/models/text/glm-5.3
return options(["low", "high", "max"], current);
}
if (provider === "custom") {
// A user-supplied OpenAI-compatible endpoint may route to any upstream
// model, so expose the common cross-gateway levels and let Auto handle
// providers without an explicit control.
return options(STD_LEVELS, current);
}
if (BINARY_THINKING_PROVIDERS.has(provider)) {
const supported =
provider === "minimax" ||
includesAny(modelName, DEEPSEEK_DEFAULT_ON) ||
includesAny(modelName, QWEN_THINKING);
return options(supported ? ["minimal", "high"] : [], current);
}
if (OPENAI_PROVIDERS.has(provider)) {
// gpt-5.6-sol does not share the gpt-5 enum: it takes `none` at the bottom
// instead of `minimal`, and adds `max` above `xhigh`. It has to be matched
// before the generic branch, and the two lists stay separate because the
// other gpt-5.6 variants have not been confirmed to accept `max` — this
// table exists to keep a rejected level off the menu, so a guess here is
// the same bug in the other direction.
//
// Only the API-key `openai`/`azure_openai` bindings reach this; a managed
// Codex (OAuth) model is driven by the live
// `codex_supported_reasoning_levels` from the account catalog instead.
if (modelName.includes("gpt-5.6-sol")) {
return options(
["none", "low", "medium", "high", "xhigh", "max"],
current,
);
}
if (includesAny(modelName, ["gpt-5", "codex"])) {
return options(["minimal", "low", "medium", "high", "xhigh"], current);
}
if (includesAny(modelName, ["o1", "o3", "o4"])) {
return options(STD_LEVELS.slice(1), current);
}
}
return options([], current);
}
export function reasoningEffortOptionsFromSupportedLevels(
values: readonly string[],
): ReasoningEffortOption[] {
const supported = [
...new Set(values.map((value) => value.trim()).filter(Boolean)),
];
return options(supported, "");
}
export function setModelReasoningEffort(
model: { reasoning_effort?: string },
value: string,
): void {
const normalized = value.trim();
if (normalized) {
model.reasoning_effort = normalized;
} else {
delete model.reasoning_effort;
}
}
/**
* The catalog fields reasoning-effort validation needs from a model option.
* Structural so `LLMOption` satisfies it without lib → features imports.
*/
export interface BackendReasoningControl {
mode: "none" | "toggle" | "levels";
levels?: string[];
off_value?: string;
on_value?: string;
default_on?: boolean;
}
export interface ReasoningEffortModelOption {
provider?: string | null;
model?: string | null;
reasoning_effort?: string | null;
supported_reasoning_efforts?: string[] | null;
reasoning_control?: BackendReasoningControl | null;
declared_reasoning?: boolean | null;
}
const R1_TOKEN_RE = /(?:^|[^a-z0-9])r1(?:$|[^a-z0-9])/;
function isQwenInstruct(modelName: string): boolean {
return modelName.includes("qwen") && modelName.split(/[-_/]/).includes("instruct");
}
function canonicalProvider(provider: string | null | undefined): string {
const canonical = (provider ?? "").trim().toLowerCase().replaceAll("-", "_");
return PROVIDER_ALIASES[canonical] ?? canonical;
}
/**
* MiniMax-M3's settings table is `none`/`adaptive`, but `adaptive` is not a
* turn wire value. The composer therefore drives it as a toggle whose on
* value is `high` (mapped to `thinking: adaptive` server-side). Mirrors the
* minimax-m3 branch of `resolve_reasoning_control` in reasoning_params.py.
*/
const MINIMAX_M3_TOGGLE = { offValue: "none", onValue: "high" } as const;
function isMinimaxM3(provider: string, modelName: string): boolean {
return (
(provider === "minimax" || provider === "minimax_anthropic") &&
modelName === "minimax-m3"
);
}
function deriveToggleDefaultOn(
option: ReasoningEffortModelOption,
provider: string,
modelName: string,
): boolean {
const configured = (option.reasoning_effort ?? "").trim().toLowerCase();
if (configured) return isThinkingEnabled(configured);
if (isQwenInstruct(modelName)) return false;
if (provider === "deepseek") return includesAny(modelName, DEEPSEEK_DEFAULT_ON);
if (provider === "dashscope") return includesAny(modelName, QWEN_THINKING);
if (provider === "custom" || provider === "siliconflow") {
return (
includesAny(modelName, QWEN_THINKING) ||
includesAny(modelName, DEEPSEEK_DEFAULT_ON) ||
modelName.includes("deepseek-r1")
);
}
return false;
}
function tableSupportedReasoningEffortValues(
option: ReasoningEffortModelOption,
): string[] {
const offered = Array.isArray(option.supported_reasoning_efforts)
? reasoningEffortOptionsFromSupportedLevels(
option.supported_reasoning_efforts,
)
: reasoningEffortOptions(
option.provider,
option.model,
// Deliberately empty: passing the current override would re-add it
// through the tables' reset-recovery path (#641 review blocker).
"",
option.declared_reasoning,
);
return offered
.map((item) => item.value)
.filter((value) => VALID_REASONING_EFFORTS.has(value));
}
/**
* The reasoning-effort wire values a selected model supports (#641):
* 1. Backend-resolved `reasoning_control` (single source of truth) when present;
* 2. Live catalog `supported_reasoning_efforts` when published as an array;
* 3. Provider/model tables (honouring `declared_reasoning`), plus binary
* toggle vendors resolved via `resolveReasoningControl`, narrowed to
* `VALID_REASONING_EFFORTS`.
*
* Unlike the tables' own retention rule, a stored/stale value is NEVER
* re-added to this list — an unsupported level must not be offered, let
* alone sent to the provider.
*/
export function supportedReasoningEffortValues(
option: ReasoningEffortModelOption | null | undefined,
): string[] {
if (!option || option.declared_reasoning === false) return [];
if (
!option.reasoning_control &&
!Array.isArray(option.supported_reasoning_efforts)
) {
const modelName = (option.model ?? "").trim().toLowerCase();
if (option.declared_reasoning !== true && isQwenInstruct(modelName)) {
return [];
}
// MiniMax-M3's table filters down to just "none" (adaptive is not a wire
// value); fall through to the toggle so "high" (= adaptive) validates.
if (!isMinimaxM3(canonicalProvider(option.provider), modelName)) {
const fromTables = tableSupportedReasoningEffortValues(option);
if (fromTables.length > 0) return fromTables;
}
}
const control = resolveReasoningControl(option);
if (control.kind === "toggle") {
return [...new Set([control.offValue, control.onValue])].filter((value) =>
VALID_REASONING_EFFORTS.has(value),
);
}
if (control.kind === "levels") {
return control.options
.map((item) => item.value)
.filter((value) => VALID_REASONING_EFFORTS.has(value));
}
return [];
}
/**
* The override a turn may actually send for this model: the stored value
* only when it is in `supportedReasoningEffortValues`, else null (= the
* configured default / provider default). A null `option` resolves to null
* — an override that cannot be validated is treated as unsupported.
*/
export function effectiveReasoningEffort(
option: ReasoningEffortModelOption | null | undefined,
override: string | null | undefined,
): string | null {
const normalized = normalizeReasoningEffort(override);
if (!normalized) return null;
return supportedReasoningEffortValues(option).includes(normalized)
? normalized
: null;
}
/**
* Strip `reasoning_effort` from a selection the selected model would reject
* before the selection is put on the wire (#641).
*
* Choice: when `option` is null — options still loading, catalog error, or
* the profile no longer listed — the override is omitted rather than
* forwarded. An unvalidatable value is exactly the provider-error case, so
* the turn safely falls back to the configured default; the persisted
* conversation selection is left alone for the composer to reconcile once
* the option resolves.
*/
export function dropUnvalidatedReasoningEffort<
T extends { reasoning_effort?: string | null },
>(
selection: T | null,
option: ReasoningEffortModelOption | null | undefined,
): T | null {
if (!selection?.reasoning_effort) return selection;
if (effectiveReasoningEffort(option, selection.reasoning_effort)) {
return selection;
}
const { reasoning_effort: _unvalidated, ...rest } = selection;
return rest as T;
}
export type ReasoningControlMode =
| { kind: "none" }
| { kind: "toggle"; offValue: string; onValue: string; defaultOn: boolean }
| { kind: "levels"; options: ReasoningEffortOption[] };
/**
* Auto-detect the chat composer's reasoning control mode for a selected model:
* 0. Server-resolved `reasoning_control` (single source of truth).
* 1. Live catalog `supported_reasoning_efforts` (e.g. Codex OAuth) -> multi-level menu.
* 2. Known multi-level families (OpenAI GPT-5/o-series, Gemini 2.5/3, Claude 3.7/4+,
* GLM-5.3, MiniMax M3.1 Flash) -> multi-level menu.
* 3. Binary thinking vendors & general/custom fallback -> simple Thinking on/off toggle.
* 4. Models with no reasoning support -> hidden.
*/
export function resolveReasoningControl(
option: ReasoningEffortModelOption | null | undefined,
): ReasoningControlMode {
if (!option || option.declared_reasoning === false) {
return { kind: "none" };
}
const provider = canonicalProvider(option.provider);
const modelName = (option.model ?? "").trim().toLowerCase();
// 0. Server-resolved reasoning_control (single source of truth from /api/settings/llm-options).
if (option.reasoning_control) {
const ctrl = option.reasoning_control;
if (ctrl.mode === "none") return { kind: "none" };
if (ctrl.mode === "toggle") {
return {
kind: "toggle",
offValue: normalizeReasoningEffort(ctrl.off_value) ?? "none",
onValue: normalizeReasoningEffort(ctrl.on_value) ?? "high",
defaultOn:
typeof ctrl.default_on === "boolean"
? ctrl.default_on
: deriveToggleDefaultOn(option, provider, modelName),
};
}
if (ctrl.mode === "levels") {
const validLevels = (ctrl.levels ?? [])
.map((v) => normalizeReasoningEffort(v))
.filter((v): v is string => Boolean(v));
return validLevels.length === 0
? { kind: "none" }
: {
kind: "levels",
options: reasoningEffortOptionsFromSupportedLevels(validLevels),
};
}
}
// 1. Live provider-advertised levels always take precedence (#2732: null means absent).
if (Array.isArray(option.supported_reasoning_efforts)) {
const valid = tableSupportedReasoningEffortValues(option);
return valid.length === 0
? { kind: "none" }
: {
kind: "levels",
options: reasoningEffortOptionsFromSupportedLevels(valid),
};
}
if (option.declared_reasoning !== true && isQwenInstruct(modelName)) {
return { kind: "none" };
}
if (isMinimaxM3(provider, modelName)) {
return {
kind: "toggle",
...MINIMAX_M3_TOGGLE,
defaultOn: deriveToggleDefaultOn(option, provider, modelName),
};
}
const valid = tableSupportedReasoningEffortValues(option);
// 2. Known multi-level effort providers and families.
const isMultiLevelProvider =
OPENAI_PROVIDERS.has(provider) ||
provider === "gemini" ||
provider === "anthropic" ||
provider === "custom_anthropic" ||
modelName.includes("gemini") ||
modelName.includes("claude") ||
modelName === "glm-5.3" ||
modelName.endsWith("/glm-5.3") ||
((provider === "minimax" || provider === "minimax_anthropic") &&
modelName === "minimax-m3.1-flash");
if (isMultiLevelProvider && valid.length > 0) {
return {
kind: "levels",
options: reasoningEffortOptionsFromSupportedLevels(valid),
};
}
// 3. Binary thinking vendors & general/custom models default to Thinking on/off toggle.
const isToggleCandidate =
isMinimalOffProvider(provider) ||
provider === "custom" ||
option.declared_reasoning === true;
if (
isToggleCandidate &&
(provider === "custom" ||
option.declared_reasoning === true ||
provider === "minimax" ||
valid.length > 0 ||
R1_TOKEN_RE.test(modelName) ||
includesAny(modelName, QWEN_THINKING) ||
includesAny(modelName, [
"deepseek",
"doubao",
"thinking",
"reasoner",
"glm-4",
"glm-5",
"kimi",
]))
) {
return {
kind: "toggle",
offValue: isMinimalOffProvider(provider) ? "minimal" : "none",
onValue: "high",
defaultOn: deriveToggleDefaultOn(option, provider, modelName),
};
}
if (valid.length > 0) {
return {
kind: "toggle",
offValue: "none",
onValue: "high",
defaultOn: deriveToggleDefaultOn(option, provider, modelName),
};
}
return { kind: "none" };
}