mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 21:09:48 +08:00
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.
This commit is contained in:
@@ -356,7 +356,7 @@ def _default_toggle_on(
|
||||
"""Infer whether a binary-toggle model thinks by default when no turn override is set."""
|
||||
configured = (configured_effort or "").strip().lower()
|
||||
if configured:
|
||||
return configured not in _THINKING_OFF_EFFORTS
|
||||
return configured not in THINKING_OFF_EFFORTS
|
||||
if _is_qwen_instruct(model_name):
|
||||
return False
|
||||
patterns = _PROVIDER_REASONING_PATTERNS.get(resolved_provider, ())
|
||||
@@ -417,9 +417,13 @@ def resolve_reasoning_control(
|
||||
if model_name == "minimax-m3.1-flash":
|
||||
return {"mode": "levels", "levels": ["low", "medium", "high", "xhigh", "max"]}
|
||||
if model_name == "minimax-m3":
|
||||
# The vendor table is none/adaptive, but "adaptive" is not a legal
|
||||
# turn wire value. Off is "none" (matching the table) and on is
|
||||
# "high", which minimax_reasoning_kwargs maps to thinking=adaptive.
|
||||
# Keep aligned with resolveReasoningControl in web/lib/reasoning-effort.ts.
|
||||
return {
|
||||
"mode": "toggle",
|
||||
"off_value": "minimal",
|
||||
"off_value": "none",
|
||||
"on_value": "high",
|
||||
"default_on": _default_toggle_on(resolved_provider, model_name, configured_effort),
|
||||
}
|
||||
|
||||
@@ -228,19 +228,23 @@ def classify_reasoning_param_error(exc: Exception) -> Literal["param", "value"]
|
||||
if not any(field in text for field in _REASONING_FIELD_MARKERS):
|
||||
return None
|
||||
|
||||
is_unsupported_param_value = (
|
||||
"unsupported parameter value" in text or "unsupported_parameter_value" in text
|
||||
)
|
||||
if not is_unsupported_param_value and any(
|
||||
marker in text for marker in _REASONING_PARAM_UNKNOWN_MARKERS
|
||||
):
|
||||
return "param"
|
||||
|
||||
# Value constraints must win over parameter-unknown markers: providers
|
||||
# often phrase a bad *value* as "Unsupported parameter: 'reasoning_effort'.
|
||||
# Supported values are 'low' and 'medium'." Treating that as a
|
||||
# parameter-level rejection would cache a disablement and silently drop
|
||||
# every other valid level for the endpoint. A value classification only
|
||||
# triggers a one-off retry, so it is the conservative choice whenever a
|
||||
# value constraint is present.
|
||||
if any(
|
||||
marker in text for marker in _REASONING_VALUE_MARKERS
|
||||
) or _REASONING_VALUE_CONSTRAINT_RE.search(text):
|
||||
return "value"
|
||||
|
||||
if any(marker in text for marker in _REASONING_PARAM_UNKNOWN_MARKERS):
|
||||
if _REASONING_VALUE_IN_UNSUPPORTED_RE.search(text):
|
||||
return "value"
|
||||
return "param"
|
||||
|
||||
if any(marker in text for marker in ("not supported", "unsupported", "does not support")):
|
||||
if _REASONING_VALUE_IN_UNSUPPORTED_RE.search(text):
|
||||
return "value"
|
||||
|
||||
@@ -293,3 +293,32 @@ def test_resolve_reasoning_control_respects_declared_reasoning_for_unlisted_anth
|
||||
assert resolve_reasoning_control("anthropic", "claude-sonnet-4", declared_reasoning=False) == {
|
||||
"mode": "none"
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider", ["minimax", "minimax_anthropic"])
|
||||
def test_minimax_m3_toggle_uses_turn_legal_values_that_map_to_vendor_modes(provider):
|
||||
"""MiniMax-M3 toggles none/high: both pass the turn contract (adaptive does
|
||||
not) and map to thinking disabled/adaptive on the wire (PR #2938 review)."""
|
||||
from deeptutor.services.llm.reasoning_params import (
|
||||
minimax_reasoning_kwargs,
|
||||
resolve_reasoning_control,
|
||||
)
|
||||
from deeptutor.services.model_selection.llm import VALID_REASONING_EFFORTS
|
||||
|
||||
control = resolve_reasoning_control(provider, "MiniMax-M3")
|
||||
assert control["mode"] == "toggle"
|
||||
assert control["off_value"] == "none"
|
||||
assert control["on_value"] == "high"
|
||||
assert {control["off_value"], control["on_value"]} <= set(VALID_REASONING_EFFORTS)
|
||||
|
||||
anthropic = provider == "minimax_anthropic"
|
||||
on = minimax_reasoning_kwargs("MiniMax-M3", control["on_value"], anthropic=anthropic)
|
||||
off = minimax_reasoning_kwargs("MiniMax-M3", control["off_value"], anthropic=anthropic)
|
||||
thinking = (
|
||||
(lambda kw: kw["thinking"]) if anthropic else (lambda kw: kw["extra_body"]["thinking"])
|
||||
)
|
||||
assert thinking(on) == {"type": "adaptive"}
|
||||
assert thinking(off) == {"type": "disabled"}
|
||||
|
||||
saved_on = resolve_reasoning_control(provider, "MiniMax-M3", configured_effort="adaptive")
|
||||
assert saved_on["default_on"] is True
|
||||
|
||||
@@ -172,6 +172,15 @@ def test_is_reasoning_param_unsupported_matches_only_400_reasoning_rejections():
|
||||
400,
|
||||
),
|
||||
("Unsupported parameter value: 'high' for 'reasoning_effort'", 400),
|
||||
# Mixed phrasing: parameter-unknown marker plus a value constraint must
|
||||
# stay value-level so the endpoint is not disabled for valid levels.
|
||||
(
|
||||
"Unsupported parameter: 'reasoning_effort'. Supported values are 'low' and 'medium'.",
|
||||
400,
|
||||
),
|
||||
("Unsupported parameter: reasoning_effort='high'", 400),
|
||||
("Unknown parameter value for reasoning_effort, must be one of ['low']", 400),
|
||||
("unsupported_parameter: thinking.type must be 'enabled' or 'disabled'", 400),
|
||||
("reasoning_effort='high' is not supported", 400),
|
||||
("'high' is not supported for reasoning_effort", 400),
|
||||
("Model does not support 'high' for reasoning_effort", 400),
|
||||
@@ -413,79 +422,80 @@ def test_openai_compat_provider_value_rejection_retries_once_without_disabling_l
|
||||
)
|
||||
|
||||
for use_stream in (False, True):
|
||||
llm_capabilities._RUNTIME_DISABLED_REASONING_PARAMS.clear()
|
||||
try:
|
||||
relay_a = OpenAICompatProvider(
|
||||
api_key="key-a",
|
||||
api_base="https://relay-a.example.com/v1",
|
||||
default_model="shared-model",
|
||||
spec=find_by_name("custom"),
|
||||
provider_name="custom",
|
||||
configure_env=False,
|
||||
)
|
||||
relay_b = OpenAICompatProvider(
|
||||
api_key="key-b",
|
||||
api_base="https://relay-b.example.com/v1",
|
||||
default_model="shared-model",
|
||||
spec=find_by_name("custom"),
|
||||
provider_name="custom",
|
||||
configure_env=False,
|
||||
)
|
||||
seen_a: list[dict] = []
|
||||
seen_b: list[dict] = []
|
||||
for err_msg in (
|
||||
"Invalid value: 'high' for 'reasoning_effort'. Supported values are: 'low'.",
|
||||
"Unsupported parameter: 'reasoning_effort'. Supported values are 'low' and 'medium'.",
|
||||
):
|
||||
llm_capabilities._RUNTIME_DISABLED_REASONING_PARAMS.clear()
|
||||
try:
|
||||
relay_a = OpenAICompatProvider(
|
||||
api_key="key-a",
|
||||
api_base="https://relay-a.example.com/v1",
|
||||
default_model="shared-model",
|
||||
spec=find_by_name("custom"),
|
||||
provider_name="custom",
|
||||
configure_env=False,
|
||||
)
|
||||
relay_b = OpenAICompatProvider(
|
||||
api_key="key-b",
|
||||
api_base="https://relay-b.example.com/v1",
|
||||
default_model="shared-model",
|
||||
spec=find_by_name("custom"),
|
||||
provider_name="custom",
|
||||
configure_env=False,
|
||||
)
|
||||
seen_a: list[dict] = []
|
||||
seen_b: list[dict] = []
|
||||
|
||||
async def fake_a(**kwargs):
|
||||
seen_a.append(dict(kwargs))
|
||||
if kwargs.get("reasoning_effort") == "high":
|
||||
raise FakeBadRequest(
|
||||
"Invalid value: 'high' for 'reasoning_effort'. Supported values are: 'low'.",
|
||||
400,
|
||||
)
|
||||
return _ok_response(bool(kwargs.get("stream")))
|
||||
async def fake_a(**kwargs):
|
||||
seen_a.append(dict(kwargs))
|
||||
if kwargs.get("reasoning_effort") == "high":
|
||||
raise FakeBadRequest(err_msg, 400)
|
||||
return _ok_response(bool(kwargs.get("stream")))
|
||||
|
||||
async def fake_b(**kwargs):
|
||||
seen_b.append(dict(kwargs))
|
||||
return _ok_response(bool(kwargs.get("stream")))
|
||||
async def fake_b(**kwargs):
|
||||
seen_b.append(dict(kwargs))
|
||||
return _ok_response(bool(kwargs.get("stream")))
|
||||
|
||||
relay_a._client.chat.completions.create = fake_a # type: ignore[method-assign]
|
||||
relay_b._client.chat.completions.create = fake_b # type: ignore[method-assign]
|
||||
relay_a._client.chat.completions.create = fake_a # type: ignore[method-assign]
|
||||
relay_b._client.chat.completions.create = fake_b # type: ignore[method-assign]
|
||||
|
||||
async def _call(provider: OpenAICompatProvider, effort: str):
|
||||
if use_stream:
|
||||
return await provider.chat_stream(
|
||||
async def _call(provider: OpenAICompatProvider, effort: str):
|
||||
if use_stream:
|
||||
return await provider.chat_stream(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="shared-model",
|
||||
reasoning_effort=effort,
|
||||
)
|
||||
return await provider.chat(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="shared-model",
|
||||
reasoning_effort=effort,
|
||||
)
|
||||
return await provider.chat(
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="shared-model",
|
||||
reasoning_effort=effort,
|
||||
|
||||
# 1. Send high to A -> rejected with 400, retries once without reasoning_effort.
|
||||
res1 = asyncio.run(_call(relay_a, "high"))
|
||||
assert res1.content == "ok"
|
||||
assert len(seen_a) == 2
|
||||
assert seen_a[0].get("reasoning_effort") == "high"
|
||||
assert "reasoning_effort" not in seen_a[1]
|
||||
assert not is_reasoning_params_disabled_at_runtime(
|
||||
"custom", "shared-model", "https://relay-a.example.com/v1"
|
||||
)
|
||||
|
||||
# 1. Send high to A -> rejected with 400, retries once without reasoning_effort.
|
||||
res1 = asyncio.run(_call(relay_a, "high"))
|
||||
assert res1.content == "ok"
|
||||
assert len(seen_a) == 2
|
||||
assert seen_a[0].get("reasoning_effort") == "high"
|
||||
assert "reasoning_effort" not in seen_a[1]
|
||||
assert not is_reasoning_params_disabled_at_runtime(
|
||||
"custom", "shared-model", "https://relay-a.example.com/v1"
|
||||
)
|
||||
# 2. Send low to A -> A still receives low.
|
||||
res2 = asyncio.run(_call(relay_a, "low"))
|
||||
assert res2.content == "ok"
|
||||
assert len(seen_a) == 3
|
||||
assert seen_a[2].get("reasoning_effort") == "low"
|
||||
|
||||
# 2. Send low to A -> A still receives low.
|
||||
res2 = asyncio.run(_call(relay_a, "low"))
|
||||
assert res2.content == "ok"
|
||||
assert len(seen_a) == 3
|
||||
assert seen_a[2].get("reasoning_effort") == "low"
|
||||
|
||||
# 3. Send low to B -> B still receives low.
|
||||
res3 = asyncio.run(_call(relay_b, "low"))
|
||||
assert res3.content == "ok"
|
||||
assert len(seen_b) == 1
|
||||
assert seen_b[0].get("reasoning_effort") == "low"
|
||||
finally:
|
||||
llm_capabilities._RUNTIME_DISABLED_REASONING_PARAMS.clear()
|
||||
# 3. Send low to B -> B still receives low.
|
||||
res3 = asyncio.run(_call(relay_b, "low"))
|
||||
assert res3.content == "ok"
|
||||
assert len(seen_b) == 1
|
||||
assert seen_b[0].get("reasoning_effort") == "low"
|
||||
finally:
|
||||
llm_capabilities._RUNTIME_DISABLED_REASONING_PARAMS.clear()
|
||||
|
||||
|
||||
def test_openai_compat_provider_param_rejection_cache_is_scoped_by_endpoint() -> None:
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
getQuickProviderGroups,
|
||||
pickRecommendedModel,
|
||||
resolveQuickPresetRegion,
|
||||
selectChatModelIds,
|
||||
type FriendlyErrorResult,
|
||||
type QuickProviderPreset,
|
||||
} from "@/lib/quick-setup-presets";
|
||||
@@ -160,6 +161,28 @@ export function QuickModelSetupWorkspace() {
|
||||
const [errorState, setErrorState] = useState<FriendlyErrorResult | null>(null);
|
||||
const [showRawError, setShowRawError] = useState(false);
|
||||
|
||||
// Generation counter + AbortController for in-flight Quick Setup connects so
|
||||
// switching vendor/region, hiding the form, or unmounting discards stale
|
||||
// probe/apply responses instead of saving the old vendor or clearing the
|
||||
// newly entered API key.
|
||||
const connectSeqRef = useRef(0);
|
||||
const connectAbortRef = useRef<AbortController | null>(null);
|
||||
|
||||
const cancelInFlightConnect = useCallback(() => {
|
||||
connectSeqRef.current += 1;
|
||||
connectAbortRef.current?.abort();
|
||||
connectAbortRef.current = null;
|
||||
setSubmitting(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
connectSeqRef.current += 1;
|
||||
connectAbortRef.current?.abort();
|
||||
connectAbortRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const [setupResult, setSetupResult] = useState<SetupResultState | null>(null);
|
||||
const [selectedSyncServices, setSelectedSyncServices] = useState<ServiceName[]>(
|
||||
[],
|
||||
@@ -210,6 +233,7 @@ export function QuickModelSetupWorkspace() {
|
||||
|
||||
const handleSelectVendor = (vendorId: string) => {
|
||||
if (vendorId === selectedVendorId) return;
|
||||
cancelInFlightConnect();
|
||||
setSelectedVendorId(vendorId);
|
||||
setSelectedRegionId(null);
|
||||
setApiKey("");
|
||||
@@ -224,6 +248,7 @@ export function QuickModelSetupWorkspace() {
|
||||
|
||||
const handleSelectRegion = (regionId: string) => {
|
||||
if (regionId === activeRegion?.id) return;
|
||||
cancelInFlightConnect();
|
||||
setSelectedRegionId(regionId);
|
||||
setApiKey("");
|
||||
setShowApiKey(false);
|
||||
@@ -255,6 +280,15 @@ export function QuickModelSetupWorkspace() {
|
||||
return;
|
||||
}
|
||||
|
||||
const seq = ++connectSeqRef.current;
|
||||
const isStale = () => connectSeqRef.current !== seq;
|
||||
connectAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
connectAbortRef.current = controller;
|
||||
|
||||
const presetSnapshot = selectedPreset;
|
||||
const manualModelSnapshot = manualModel.trim();
|
||||
|
||||
setSubmitting(true);
|
||||
setErrorState(null);
|
||||
setShowRawError(false);
|
||||
@@ -263,17 +297,21 @@ export function QuickModelSetupWorkspace() {
|
||||
const probeRes = await apiFetch(apiUrl("/api/settings/test-provider"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
service: "llm",
|
||||
binding: selectedPreset.id,
|
||||
binding: presetSnapshot.id,
|
||||
base_url: baseUrl,
|
||||
api_key: trimmedKey,
|
||||
api_format: "auto",
|
||||
}),
|
||||
});
|
||||
if (isStale()) return;
|
||||
|
||||
const probePayload = (await probeRes.json().catch(() => ({}))) as Discovery & {
|
||||
detail?: string;
|
||||
};
|
||||
if (isStale()) return;
|
||||
|
||||
const probeAccepted =
|
||||
probeRes.ok &&
|
||||
@@ -295,13 +333,10 @@ export function QuickModelSetupWorkspace() {
|
||||
const probeSkipped = probePayload.status === "unavailable";
|
||||
const discoveredIds = probeSkipped
|
||||
? []
|
||||
: (probePayload.models ?? [])
|
||||
.filter((m) => !m.services?.length || m.services.includes("llm"))
|
||||
.map((m) => m.id.trim())
|
||||
.filter(Boolean);
|
||||
: selectChatModelIds(probePayload.models ?? []);
|
||||
|
||||
const chosenModel =
|
||||
manualModel.trim() || pickRecommendedModel(selectedPreset, discoveredIds);
|
||||
manualModelSnapshot || pickRecommendedModel(presetSnapshot, discoveredIds);
|
||||
|
||||
if (!chosenModel) {
|
||||
setErrorState({
|
||||
@@ -315,12 +350,12 @@ export function QuickModelSetupWorkspace() {
|
||||
const connectionId = `conn-${randomUuid().slice(0, 8)}`;
|
||||
const profileId = `llm-${randomUuid().slice(0, 8)}`;
|
||||
const modelEntryId = `model-${randomUuid().slice(0, 8)}`;
|
||||
const displayName = t(selectedPreset.nameKey);
|
||||
const displayName = t(presetSnapshot.nameKey);
|
||||
|
||||
const connection: CatalogConnection = {
|
||||
id: connectionId,
|
||||
name: displayName,
|
||||
provider: selectedPreset.id,
|
||||
provider: presetSnapshot.id,
|
||||
api_key: trimmedKey,
|
||||
base_url: baseUrl,
|
||||
api_version: "",
|
||||
@@ -334,7 +369,7 @@ export function QuickModelSetupWorkspace() {
|
||||
const llmProfile: CatalogProfile = {
|
||||
id: profileId,
|
||||
name: displayName,
|
||||
binding: selectedPreset.id,
|
||||
binding: presetSnapshot.id,
|
||||
connection_id: connectionId,
|
||||
base_url: baseUrl,
|
||||
api_key: trimmedKey,
|
||||
@@ -352,6 +387,7 @@ export function QuickModelSetupWorkspace() {
|
||||
const applyRes = await apiFetch(apiUrl("/api/settings/apply/provider"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
service: "llm",
|
||||
profile: llmProfile,
|
||||
@@ -360,7 +396,11 @@ export function QuickModelSetupWorkspace() {
|
||||
active_model_id: modelEntryId,
|
||||
}),
|
||||
});
|
||||
if (isStale()) return;
|
||||
|
||||
const applyPayload = await applyRes.json().catch(() => ({}));
|
||||
if (isStale()) return;
|
||||
|
||||
if (!applyRes.ok) {
|
||||
throw new Error(
|
||||
typeof applyPayload.detail === "string"
|
||||
@@ -378,18 +418,20 @@ export function QuickModelSetupWorkspace() {
|
||||
kind: "task_choice",
|
||||
task: { mode: "inherit" },
|
||||
});
|
||||
if (isStale()) return;
|
||||
}
|
||||
}
|
||||
|
||||
await reloadSettings();
|
||||
if (isStale()) return;
|
||||
|
||||
const extraCandidates = getSyncableCapabilities(selectedPreset.id).filter(
|
||||
const extraCandidates = getSyncableCapabilities(presetSnapshot.id).filter(
|
||||
(svc) => !hasActiveService(catalog.services, svc),
|
||||
);
|
||||
setSelectedSyncServices(extraCandidates);
|
||||
setSyncedServices([]);
|
||||
setSetupResult({
|
||||
providerId: selectedPreset.id,
|
||||
providerId: presetSnapshot.id,
|
||||
providerLabel: displayName,
|
||||
connectionId,
|
||||
connection,
|
||||
@@ -402,6 +444,7 @@ export function QuickModelSetupWorkspace() {
|
||||
setApiKey("");
|
||||
setShowApiKey(false);
|
||||
} catch (error) {
|
||||
if (isStale()) return;
|
||||
setErrorState(
|
||||
formatFriendlySetupError(
|
||||
null,
|
||||
@@ -409,7 +452,12 @@ export function QuickModelSetupWorkspace() {
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
if (!isStale()) {
|
||||
if (connectAbortRef.current === controller) {
|
||||
connectAbortRef.current = null;
|
||||
}
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -893,6 +941,7 @@ export function QuickModelSetupWorkspace() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
cancelInFlightConnect();
|
||||
setShowAddForm((prev) => !prev);
|
||||
setSetupResult(null);
|
||||
}}
|
||||
|
||||
@@ -206,11 +206,43 @@ export function resolveQuickPresetRegion(
|
||||
return regions.find((region) => region.id === preferredId) ?? regions[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Model ids that are clearly not chat/completion models (embeddings, rerankers,
|
||||
* speech, image/video generation, moderation). Used only when the provider's
|
||||
* /models listing carries no `services` metadata — e.g. OpenAI returns
|
||||
* `text-embedding-3-small` alongside chat models with nothing to tell them
|
||||
* apart, and it must never become the default chat model.
|
||||
*/
|
||||
const NON_CHAT_MODEL_ID_RE =
|
||||
/(?:^|[-_/.:])(?:text-)?embed(?:ding)?s?(?:$|[-_/.:\d])|embedding|rerank|(?:^|[-_/])bge-|(?:^|[-_/])m3e|(?:^|[-_/])tts(?:$|[-_/.\d])|(?:^|[-_/])speech|whisper|transcri|(?:^|[-_/])asr(?:$|[-_/.\d])|dall-e|imagen|(?:^|[-_/])image-|-image(?:$|[-_/.:])|stable-diffusion|sdxl|(?:^|[-_/])flux|cogview|cogvideo|wanx|(?:^|[-_/])veo|-video(?:$|[-_/.:])|(?:^|[-_/])video-|moderation/;
|
||||
|
||||
export function isLikelyChatModelId(id: string): boolean {
|
||||
return !NON_CHAT_MODEL_ID_RE.test(id.trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat-capable model ids from a probe listing. Explicit `services` metadata
|
||||
* always wins; entries without it fall back to the id heuristic above.
|
||||
*/
|
||||
export function selectChatModelIds(
|
||||
models: ReadonlyArray<{ id: string; services?: string[] | null }>,
|
||||
): string[] {
|
||||
return models
|
||||
.filter((m) =>
|
||||
m.services?.length ? m.services.includes("llm") : isLikelyChatModelId(m.id),
|
||||
)
|
||||
.map((m) => m.id.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Pick the best default model given discovered models and vendor recommendations. */
|
||||
export function pickRecommendedModel(
|
||||
preset: QuickProviderPreset,
|
||||
discovered: string[],
|
||||
): string {
|
||||
// Defence in depth: callers should already pass chat-only ids, but a
|
||||
// non-chat id must never be returned as the default chat model.
|
||||
discovered = discovered.filter(isLikelyChatModelId);
|
||||
if (discovered.length > 0) {
|
||||
const lowerMap = new Map(discovered.map((id) => [id.toLowerCase(), id]));
|
||||
for (const candidate of preset.recommendedModels) {
|
||||
|
||||
@@ -326,6 +326,21 @@ function canonicalProvider(provider: string | null | undefined): string {
|
||||
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,
|
||||
@@ -391,8 +406,12 @@ export function supportedReasoningEffortValues(
|
||||
if (option.declared_reasoning !== true && isQwenInstruct(modelName)) {
|
||||
return [];
|
||||
}
|
||||
const fromTables = tableSupportedReasoningEffortValues(option);
|
||||
if (fromTables.length > 0) return fromTables;
|
||||
// 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);
|
||||
@@ -518,6 +537,14 @@ export function resolveReasoningControl(
|
||||
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.
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
findQuickPreset,
|
||||
formatFriendlySetupError,
|
||||
getQuickProviderGroups,
|
||||
isLikelyChatModelId,
|
||||
pickRecommendedModel,
|
||||
resolveQuickPresetRegion,
|
||||
selectChatModelIds,
|
||||
} from "../lib/quick-setup-presets";
|
||||
|
||||
test("getQuickProviderGroups prioritizes domestic vendors for zh and global vendors for non-zh", () => {
|
||||
@@ -88,3 +90,41 @@ test("formatFriendlySetupError maps auth, quota, network, access, and fallback f
|
||||
"quickSetup.error.genericTitle",
|
||||
);
|
||||
});
|
||||
|
||||
test("selectChatModelIds and pickRecommendedModel exclude non-chat models lacking services metadata", () => {
|
||||
assert.equal(isLikelyChatModelId("text-embedding-3-small"), false);
|
||||
assert.equal(isLikelyChatModelId("text-embedding-3-large"), false);
|
||||
assert.equal(isLikelyChatModelId("BAAI/bge-m3"), false);
|
||||
assert.equal(isLikelyChatModelId("Qwen/Qwen3-Embedding-8B"), false);
|
||||
assert.equal(isLikelyChatModelId("whisper-1"), false);
|
||||
assert.equal(isLikelyChatModelId("tts-1"), false);
|
||||
assert.equal(isLikelyChatModelId("dall-e-3"), false);
|
||||
assert.equal(isLikelyChatModelId("omni-moderation-latest"), false);
|
||||
assert.equal(isLikelyChatModelId("gpt-5.4"), true);
|
||||
assert.equal(isLikelyChatModelId("MiniMax-M3"), true);
|
||||
assert.equal(isLikelyChatModelId("deepseek-chat"), true);
|
||||
|
||||
// Explicit services metadata takes precedence; missing metadata falls back to heuristic.
|
||||
assert.deepEqual(
|
||||
selectChatModelIds([
|
||||
{ id: "text-embedding-3-small" },
|
||||
{ id: "gpt-5.4" },
|
||||
{ id: "whisper-1" },
|
||||
{ id: "custom-embed-tagged-llm", services: ["llm"] },
|
||||
{ id: "gpt-labeled-embedding", services: ["embedding"] },
|
||||
]),
|
||||
["gpt-5.4", "custom-embed-tagged-llm"],
|
||||
);
|
||||
|
||||
// Even if callers pass unfiltered IDs, pickRecommendedModel never chooses an embedding model.
|
||||
const openai = findQuickPreset("openai")!;
|
||||
assert.equal(
|
||||
pickRecommendedModel(openai, ["text-embedding-3-small", "gpt-5.4"]),
|
||||
"gpt-5.4",
|
||||
);
|
||||
// When only non-chat models are returned, fall back to the preset's recommended chat model.
|
||||
assert.equal(
|
||||
pickRecommendedModel(openai, ["text-embedding-3-small", "text-embedding-3-large"]),
|
||||
openai.recommendedModels[0],
|
||||
);
|
||||
});
|
||||
|
||||
@@ -78,6 +78,11 @@ function makeSettings(overrides: Record<string, unknown> = {}) {
|
||||
default_base_url: "https://api.minimax.io/v1",
|
||||
services: {},
|
||||
},
|
||||
{
|
||||
provider: "openai",
|
||||
default_base_url: "https://api.openai.com/v1",
|
||||
services: {},
|
||||
},
|
||||
],
|
||||
providers: {
|
||||
llm: [],
|
||||
@@ -317,4 +322,128 @@ describe("QuickModelSetupWorkspace", () => {
|
||||
expect(screen.getByText("quickSetup.error.missingKeyTitle")).toBeTruthy();
|
||||
expect(mockApiFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never picks an embedding model without services metadata as the default chat model", async () => {
|
||||
const settings = makeSettings();
|
||||
mockUseSettings.mockReturnValue(settings);
|
||||
mockApiFetch.mockImplementation((url: string) => {
|
||||
if (url === "/api/settings/test-provider") {
|
||||
return jsonResponse({
|
||||
status: "connected",
|
||||
// Neither entry carries `services` metadata and neither matches OpenAI's recommended list.
|
||||
models: [{ id: "text-embedding-3-small" }, { id: "gpt-5.4" }],
|
||||
});
|
||||
}
|
||||
if (url === "/api/settings/apply/provider") {
|
||||
return jsonResponse({ catalog: emptyCatalog() });
|
||||
}
|
||||
return jsonResponse({});
|
||||
});
|
||||
|
||||
render(<QuickModelSetupWorkspace />);
|
||||
fireEvent.click(screen.getByText("quickSetup.step1.moreProviders"));
|
||||
fireEvent.click(screen.getByText("quickSetup.vendor.openai.name"));
|
||||
fireEvent.change(screen.getByPlaceholderText("sk-..."), {
|
||||
target: { value: "sk-openai-test" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /quickSetup\.action\.verifyAndEnable/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockInvalidateLLMOptionsCache).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const applyCall = mockApiFetch.mock.calls.find(
|
||||
([url]) => url === "/api/settings/apply/provider",
|
||||
);
|
||||
expect(applyCall).toBeTruthy();
|
||||
const applyBody = JSON.parse(applyCall![1].body as string);
|
||||
expect(applyBody.profile.models[0].model).toBe("gpt-5.4");
|
||||
expect(applyBody.profile.models[0].model).not.toBe("text-embedding-3-small");
|
||||
});
|
||||
|
||||
it("discards an in-flight probe response when switching vendors so it cannot save or clear the new key", async () => {
|
||||
const settings = makeSettings();
|
||||
mockUseSettings.mockReturnValue(settings);
|
||||
|
||||
let resolveDeepSeekProbe!: (value: unknown) => void;
|
||||
const deepSeekProbePromise = new Promise((resolve) => {
|
||||
resolveDeepSeekProbe = resolve;
|
||||
});
|
||||
|
||||
mockApiFetch.mockImplementation((url: string, init?: { body?: string }) => {
|
||||
if (url === "/api/settings/test-provider") {
|
||||
const body = JSON.parse(init?.body ?? "{}");
|
||||
if (body.binding === "deepseek") {
|
||||
return deepSeekProbePromise;
|
||||
}
|
||||
return jsonResponse({
|
||||
status: "connected",
|
||||
models: [{ id: "Qwen/Qwen3-32B" }],
|
||||
});
|
||||
}
|
||||
if (url === "/api/settings/apply/provider") {
|
||||
return jsonResponse({ catalog: emptyCatalog() });
|
||||
}
|
||||
return jsonResponse({});
|
||||
});
|
||||
|
||||
render(<QuickModelSetupWorkspace />);
|
||||
|
||||
// 1. Submit DeepSeek with its probe held open.
|
||||
const keyInput = screen.getByPlaceholderText("sk-...") as HTMLInputElement;
|
||||
fireEvent.change(keyInput, { target: { value: "sk-deepseek" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /quickSetup\.action\.verifyAndEnable/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApiFetch).toHaveBeenCalledWith(
|
||||
"/api/settings/test-provider",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
// 2. Switch to SiliconFlow while DeepSeek's probe is still pending, then type a new key.
|
||||
fireEvent.click(screen.getByText("quickSetup.vendor.siliconflow.name"));
|
||||
expect(keyInput.value).toBe("");
|
||||
fireEvent.change(keyInput, { target: { value: "sk-siliconflow-new" } });
|
||||
expect(keyInput.value).toBe("sk-siliconflow-new");
|
||||
|
||||
// 3. Release the stale DeepSeek probe response.
|
||||
resolveDeepSeekProbe({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
status: "connected",
|
||||
models: [{ id: "deepseek-chat" }],
|
||||
}),
|
||||
});
|
||||
|
||||
// Give microtasks time to flush.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Stale DeepSeek response must NOT call apply/provider, show success, or clear the new key.
|
||||
const applyCalls = mockApiFetch.mock.calls.filter(
|
||||
([url]) => url === "/api/settings/apply/provider",
|
||||
);
|
||||
expect(applyCalls).toHaveLength(0);
|
||||
expect(screen.queryByText("quickSetup.success.title")).toBeNull();
|
||||
expect(keyInput.value).toBe("sk-siliconflow-new");
|
||||
|
||||
// 4. Submitting SiliconFlow works immediately (not stuck in submitting state).
|
||||
const submitButton = screen.getByRole("button", {
|
||||
name: /quickSetup\.action\.verifyAndEnable/,
|
||||
}) as HTMLButtonElement;
|
||||
expect(submitButton.disabled).toBe(false);
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockInvalidateLLMOptionsCache).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
const finalApplyCall = mockApiFetch.mock.calls.find(
|
||||
([url]) => url === "/api/settings/apply/provider",
|
||||
);
|
||||
expect(finalApplyCall).toBeTruthy();
|
||||
const finalApplyBody = JSON.parse(finalApplyCall![1].body as string);
|
||||
expect(finalApplyBody.profile.binding).toBe("siliconflow");
|
||||
expect(finalApplyBody.profile.api_key).toBe("sk-siliconflow-new");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,10 @@ import { expect, it, vi } from "vitest";
|
||||
|
||||
import ReasoningEffortSelector from "@/components/chat/home/ReasoningEffortSelector";
|
||||
import type { LLMOption } from "@/lib/llm-options";
|
||||
import {
|
||||
dropUnvalidatedReasoningEffort,
|
||||
effectiveReasoningEffort,
|
||||
} from "@/lib/reasoning-effort";
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
|
||||
@@ -221,3 +225,46 @@ it("aligns default-on toggle state so models enabled by default turn off on a si
|
||||
fireEvent.click(configuredToggle);
|
||||
expect(onChange).toHaveBeenLastCalledWith("minimal");
|
||||
});
|
||||
|
||||
it("emits wire-valid values from the MiniMax-M3 Thinking toggle that survive pre-send validation", () => {
|
||||
for (const m3Option of [
|
||||
option({
|
||||
provider: "minimax",
|
||||
model: "MiniMax-M3",
|
||||
reasoning_control: {
|
||||
mode: "toggle",
|
||||
off_value: "none",
|
||||
on_value: "high",
|
||||
default_on: false,
|
||||
},
|
||||
}),
|
||||
option({ provider: "minimax", model: "MiniMax-M3" }),
|
||||
]) {
|
||||
const onChange = vi.fn();
|
||||
const { rerender, unmount } = render(
|
||||
<ReasoningEffortSelector option={m3Option} value={null} onChange={onChange} />,
|
||||
);
|
||||
const toggle = screen.getByRole("button", { name: "Reasoning effort" });
|
||||
expect(toggle.getAttribute("aria-pressed")).toBe("false");
|
||||
|
||||
// Click ON -> emits "high" and survives effectiveReasoningEffort / dropUnvalidatedReasoningEffort.
|
||||
fireEvent.click(toggle);
|
||||
expect(onChange).toHaveBeenLastCalledWith("high");
|
||||
expect(effectiveReasoningEffort(m3Option, "high")).toBe("high");
|
||||
expect(
|
||||
dropUnvalidatedReasoningEffort({ reasoning_effort: "high" }, m3Option),
|
||||
).toEqual({ reasoning_effort: "high" });
|
||||
|
||||
// Re-render with "high" -> shows active, clicking OFF emits "none" and survives validation.
|
||||
rerender(
|
||||
<ReasoningEffortSelector option={m3Option} value="high" onChange={onChange} />,
|
||||
);
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Reasoning effort" }).getAttribute("aria-pressed"),
|
||||
).toBe("true");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reasoning effort" }));
|
||||
expect(onChange).toHaveBeenLastCalledWith("none");
|
||||
expect(effectiveReasoningEffort(m3Option, "none")).toBe("none");
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -26,6 +26,45 @@ test("MiniMax Flash exposes adaptive effort levels and preserves saved values",
|
||||
}
|
||||
});
|
||||
|
||||
test("MiniMax-M3 Thinking toggle sends a value the composer validation keeps", () => {
|
||||
for (const provider of ["minimax", "minimax_anthropic"]) {
|
||||
// Backend-resolved control (mirrors resolve_reasoning_control).
|
||||
const withBackend = {
|
||||
provider,
|
||||
model: "MiniMax-M3",
|
||||
reasoning_control: {
|
||||
mode: "toggle" as const,
|
||||
off_value: "none",
|
||||
on_value: "high",
|
||||
default_on: false,
|
||||
},
|
||||
};
|
||||
// Client-only fallback (no reasoning_control from the server).
|
||||
const tableOnly = { provider, model: "MiniMax-M3" };
|
||||
for (const option of [withBackend, tableOnly]) {
|
||||
const control = resolveReasoningControl(option);
|
||||
assert.equal(control.kind, "toggle");
|
||||
if (control.kind !== "toggle") continue;
|
||||
assert.equal(control.offValue, "none");
|
||||
assert.equal(control.onValue, "high");
|
||||
// Turning Thinking on must survive the pre-send filter.
|
||||
assert.equal(effectiveReasoningEffort(option, control.onValue), "high");
|
||||
assert.equal(effectiveReasoningEffort(option, control.offValue), "none");
|
||||
assert.deepEqual(
|
||||
dropUnvalidatedReasoningEffort({ reasoning_effort: "high" }, option),
|
||||
{ reasoning_effort: "high" },
|
||||
);
|
||||
}
|
||||
// A saved "adaptive" config means thinking is on by default.
|
||||
const saved = resolveReasoningControl({
|
||||
provider,
|
||||
model: "MiniMax-M3",
|
||||
reasoning_effort: "adaptive",
|
||||
});
|
||||
assert.equal(saved.kind === "toggle" && saved.defaultOn, true);
|
||||
}
|
||||
});
|
||||
|
||||
test("Gemini 3 and 2.5 Pro do not list the invalid none effort", () => {
|
||||
assert.deepEqual(values("gemini", "gemini-3.6-flash"), [
|
||||
"",
|
||||
|
||||
Reference in New Issue
Block a user