Skip to content

The agent that grows with you

refactor: single canonical reasoning-effort vocabulary ends the per-vendor clamp drift

Tekniumf7d90c941038
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 21a0a7533b9..c2797ffad26 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -1551,15 +1551,15 @@ class _CodexCompletionsAdapter:
# Codex backend, which rejects e.g. {"effort": null}
# with a 400.
effort = reasoning_cfg.get("effort") or "medium"
- # Codex backend rejects "minimal"; clamp to "low" to
- # match the main-agent Codex transport behavior. "ultra"
- # is Hermes-internal ladder vocabulary with no wire
- # equivalent anywhere on this API; cap it at "max"
- # (same class as #89503).
- if effort == "minimal":
- effort = "low"
- elif effort == "ultra":
- effort = "max"
+ # Same declared vocabulary + shared clamp as the main
+ # Codex transport (agent.reasoning_effort): the backend
+ # rejects "minimal" and the internal "ultra" level.
+ from agent.reasoning_effort import (
+ CODEX_RESPONSES_EFFORTS,
+ clamp_effort,
+ )
+
+ effort = clamp_effort(effort, CODEX_RESPONSES_EFFORTS)
resp_kwargs["reasoning"] = {
"effort": effort,
"summary": "auto",
diff --git a/agent/reasoning_effort.py b/agent/reasoning_effort.py
new file mode 100644
index 00000000000..bb4eeded641
--- /dev/null
+++ b/agent/reasoning_effort.py
@@ -0,0 +1,187 @@
+"""Canonical reasoning-effort vocabulary and wire clamping.
+
+Hermes' internal effort ladder (``hermes_constants.VALID_REASONING_EFFORTS``
+plus the ``none`` disable level) is wider than what any single provider wire
+accepts. Historically every transport and provider profile hand-rolled its own
+translation map, and the class of bugs that produced was constant: a new
+internal level (``ultra``) leaking to a wire that rejects it with HTTP 400
+(#89503, #70058), or an unknown level being dropped to a weak default so the
+strongest ask resolved *weaker* than an explicit ``high`` — a ladder
+inversion (#74295, #87279).
+
+This module is the single source of truth both kinds of code use instead:
+
+- :data:`EFFORT_LADDER` — canonical low→high ordering.
+- :func:`clamp_effort` — the one clamping policy: keep a supported level
+ verbatim, otherwise take the **nearest weaker** supported level (never
+ silently escalate cost above what was asked), and only when nothing weaker
+ exists take the weakest supported level (a provider whose minimum thinking
+ level is ``high`` serves ``high`` for a ``low`` ask — GLM-5.2's shape).
+- Named wire-vocabulary constants for the common OpenAI-compatible surfaces,
+ so call sites declare *data* ("this route accepts these levels") rather
+ than logic.
+
+Rules for call sites:
+
+1. **Wire shape stays local.** Whether a route wants ``extra_body.reasoning``,
+ a top-level ``reasoning_effort`` string, or a ``thinking`` toggle is the
+ caller's business. Only the *vocabulary math* lives here.
+2. **Unset stays unset.** ``clamp_effort`` translates an explicit request; it
+ does not invent one. When the user expressed no effort, prefer omitting
+ the field so the server default applies.
+3. **Never patch a predicate.** When a provider rejects a level, fix its
+ declared supported set (data), never add another vendor-name special case
+ at the call site.
+"""
+
+from __future__ import annotations
+
+from typing import Optional, Sequence
+
+# Canonical low→high ordering used for nearest-level clamping. Superset of
+# hermes_constants.VALID_REASONING_EFFORTS ("none" included so an explicit
+# disable can be clamped too when a provider publishes it as a level).
+EFFORT_LADDER: tuple[str, ...] = (
+ "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra",
+)
+
+# ``ultra`` is Hermes-internal ladder vocabulary (the Codex product tier); no
+# provider wire accepts it verbatim anywhere. Every declared wire set below
+# therefore stops at ``max`` — ``ultra`` always clamps down.
+
+#: The widest OpenAI-compatible wire vocabulary (OpenRouter, Nous Portal):
+#: exactly max|xhigh|high|medium|low|minimal|none.
+OPENAI_COMPAT_WIRE_EFFORTS: tuple[str, ...] = (
+ "none", "minimal", "low", "medium", "high", "xhigh", "max",
+)
+
+#: OpenAI/Codex Responses backend (``minimal`` is rejected → clamps to low).
+CODEX_RESPONSES_EFFORTS: tuple[str, ...] = (
+ "low", "medium", "high", "xhigh", "max",
+)
+
+#: xAI Responses — Grok 4.6+ accepts xhigh; older Grok tops out at high.
+XAI_GROK46_EFFORTS: tuple[str, ...] = ("low", "medium", "high", "xhigh")
+XAI_LEGACY_EFFORTS: tuple[str, ...] = ("low", "medium", "high")
+
+#: Actual Computer relays (SGLang/vLLM): none/low/medium/high/max.
+ACTUAL_RELAY_EFFORTS: tuple[str, ...] = ("none", "low", "medium", "high", "max")
+
+#: Moonshot/Kimi K3: low/high/max (server default high).
+KIMI_K3_EFFORTS: tuple[str, ...] = ("low", "high", "max")
+#: Moonshot/Kimi K2-era models: low/medium/high.
+KIMI_K2_EFFORTS: tuple[str, ...] = ("low", "medium", "high")
+
+#: Tencent TokenHub: low/medium/high.
+TOKENHUB_EFFORTS: tuple[str, ...] = ("low", "medium", "high")
+
+#: Kimi K3's vendor-documented translation quirks (platform.kimi.ai
+#: thinking-model guide): ``high`` is K3's positional middle AND server
+#: default, so ``medium`` rounds to it rather than down to ``low``; ``xhigh``
+#: rounds up to ``max`` (K3's top tier), matching the kimi-coding plugin.
+KIMI_K3_OVERRIDES: dict[str, str] = {"medium": "high", "xhigh": "max"}
+
+#: GLM-5.2 native reasoning_effort knob: exactly two enabled levels,
+#: ``high`` (its minimum thinking level) and ``max`` (per Z.AI/BigModel
+#: docs). ``xhigh`` requests the top tier, not the floor.
+GLM52_EFFORTS: tuple[str, ...] = ("high", "max")
+GLM52_OVERRIDES: dict[str, str] = {"xhigh": "max"}
+
+#: DeepSeek V4 OpenAI-compat endpoint: low/medium/high/max; ``xhigh``
+#: requests the top tier (matches the shipped profile mapping).
+DEEPSEEK_V4_EFFORTS: tuple[str, ...] = ("low", "medium", "high", "max")
+DEEPSEEK_V4_OVERRIDES: dict[str, str] = {"xhigh": "max"}
+
+#: Ollama Cloud /v1/chat/completions: accepts {none, low, medium, high, max};
+#: rejects ``minimal`` with HTTP 400. ``xhigh`` requests the top tier.
+OLLAMA_CLOUD_EFFORTS: tuple[str, ...] = ("none", "low", "medium", "high", "max")
+OLLAMA_CLOUD_OVERRIDES: dict[str, str] = {"xhigh": "max"}
+
+#: Meta Model API (Muse): minimal..xhigh; rejects ``none``.
+META_AI_EFFORTS: tuple[str, ...] = ("minimal", "low", "medium", "high", "xhigh")
+
+#: Upstage Solar Pro/Open: low/medium/high.
+SOLAR_EFFORTS: tuple[str, ...] = ("low", "medium", "high")
+
+
+def kimi_supported_efforts(model: Optional[str]) -> tuple[str, ...]:
+ """Supported effort set for a Moonshot/Kimi model slug.
+
+ K3 is served as the bare slug ``k3`` and the ``kimi-k3*`` aliases; its
+ documented set is low/high/max. Everything earlier speaks low/medium/high.
+ """
+ m = (model or "").strip().lower().split("/")[-1]
+ if m == "k3" or m.startswith("kimi-k3"):
+ return KIMI_K3_EFFORTS
+ return KIMI_K2_EFFORTS
+
+
+def clamp_effort(
+ effort: Optional[str],
+ supported: Optional[Sequence[str]],
+ overrides: Optional[dict[str, str]] = None,
+) -> Optional[str]:
+ """Clamp a requested reasoning effort onto a wire's supported levels.
+
+ ``overrides`` is an optional declared mapping consulted first, for routes
+ whose vendor documents a translation that differs from nearest-weaker
+ (Kimi K3 documents ``medium → high``: high is its positional middle and
+ server default). Overrides are data, not logic — a call site never adds
+ vendor ``if``\\ s around this function.
+
+ Otherwise: returns the requested effort unchanged when it is supported,
+ when the supported set is unknown (``None``/empty), or when the effort
+ isn't a recognized ladder level (custom providers may use bespoke names —
+ pass through rather than guess). Otherwise returns the **nearest weaker**
+ supported level, so a clamp never silently escalates cost; when nothing
+ weaker exists, the weakest supported level is returned (the caller asked
+ for *some* thinking and the provider's floor is the closest honest match).
+
+ The policy is monotonic: a stronger request never resolves to a weaker
+ wire level than a weaker request would.
+ """
+ requested = str(effort or "").strip().lower()
+ if not requested or not supported:
+ return effort
+ supported_norm = [
+ str(level).strip().lower()
+ for level in supported
+ if str(level).strip().lower() in EFFORT_LADDER
+ ]
+ if not supported_norm or requested in supported_norm:
+ return effort
+ if overrides:
+ mapped = overrides.get(requested)
+ if mapped in supported_norm:
+ return mapped
+ if requested not in EFFORT_LADDER:
+ return effort
+ # "none" disables reasoning — it is never a *degradation target* for an
+ # enabled ask (clamping "minimal" to "none" would silently switch
+ # thinking off). It still passes through verbatim when requested.
+ candidates = [level for level in supported_norm if level != "none"]
+ if not candidates:
+ return effort
+ requested_idx = EFFORT_LADDER.index(requested)
+ below = [
+ level for level in candidates
+ if EFFORT_LADDER.index(level) < requested_idx
+ ]
+ if below:
+ return max(below, key=EFFORT_LADDER.index)
+ return min(candidates, key=EFFORT_LADDER.index)
+
+
+def requested_effort(reasoning_config: Optional[dict]) -> Optional[str]:
+ """Extract the user's explicit effort from a reasoning config, or None.
+
+ Returns ``None`` when the config is absent, malformed, carries no effort,
+ or reasoning is explicitly disabled — callers should then omit the wire
+ field entirely so the server default applies (rule 2 above).
+ """
+ if not isinstance(reasoning_config, dict):
+ return None
+ if reasoning_config.get("enabled") is False:
+ return None
+ effort = str(reasoning_config.get("effort") or "").strip().lower()
+ return effort or None
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index b1f9a8b0a44..bec0f9a82b0 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -13,6 +13,15 @@ import json
from typing import Any, Dict
from agent.lmstudio_reasoning import resolve_lmstudio_effort
+from agent.reasoning_effort import (
+ KIMI_K3_EFFORTS,
+ KIMI_K3_OVERRIDES,
+ OPENAI_COMPAT_WIRE_EFFORTS,
+ TOKENHUB_EFFORTS,
+ clamp_effort,
+ kimi_supported_efforts,
+ requested_effort,
+)
from agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_tools
from agent.prompt_builder import DEVELOPER_ROLE_MODELS
from agent.transports.base import ProviderTransport
@@ -90,17 +99,19 @@ def _reasoning_config_for_model(model: str, reasoning_config: dict | None) -> di
(the /reasoning command documents none..xhigh|max|ultra). OpenAI-
compatible wires — OpenRouter chief among them — accept exactly
max|xhigh|high|medium|low|minimal|none and reject the extension with
- HTTP 400, so an ``ultra`` configured for an Anthropic default leaks
- untranslated when a per-job/per-turn override pins a non-Anthropic
- model on this transport and the whole call fails (#89503). Map the
- extension to its wire cap for every model on this path; the Anthropic
- adapter keeps its own richer mapping.
+ HTTP 400 (#89503). Clamp against the declared wire vocabulary via the
+ shared policy in ``agent.reasoning_effort``; provider profiles with
+ narrower sets clamp again downstream.
"""
if not isinstance(reasoning_config, dict):
return reasoning_config
- if str(reasoning_config.get("effort") or "").strip().lower() == "ultra":
+ effort = str(reasoning_config.get("effort") or "").strip().lower()
+ if not effort:
+ return reasoning_config
+ clamped = clamp_effort(effort, OPENAI_COMPAT_WIRE_EFFORTS)
+ if clamped != effort:
normalized = dict(reasoning_config)
- normalized["effort"] = "max"
+ normalized["effort"] = clamped
return normalized
return reasoning_config
@@ -567,36 +578,22 @@ class ChatCompletionsTransport(ProviderTransport):
and reasoning_config.get("enabled") is False
)
if not _kimi_thinking_off:
- # K3 accepts low/high/max only (default high) — "medium" and
- # Hermes' upper-ladder levels 400 or silently degrade. Mirror
- # the kimi-coding plugin's _K3_EFFORT_MAP; older Kimi models
- # keep the low/medium/high vocabulary with the stronger
- # Hermes levels capped at high instead of being dropped
- # (dropping them inverted the ladder: ultra sent the
- # "medium" default, weaker than an explicit high).
- _e = ""
- if reasoning_config and isinstance(reasoning_config, dict):
- _e = (reasoning_config.get("effort") or "").strip().lower()
- if "k3" in (model or "").lower():
- _kimi_effort = {
- "minimal": "low",
- "low": "low",
- "medium": "high",
- "high": "high",
- "xhigh": "max",
- "max": "max",
- "ultra": "max",
- }.get(_e, "high")
+ # Kimi vocabularies are declared in agent.reasoning_effort:
+ # K3 = low/high/max (with the vendor-documented medium→high,
+ # xhigh→max rounding), K2-era = low/medium/high. Default when
+ # no effort was requested: K3's server default is high,
+ # K2-era's is medium.
+ _supported = kimi_supported_efforts(model)
+ _overrides = (
+ KIMI_K3_OVERRIDES if _supported is KIMI_K3_EFFORTS else None
+ )
+ _e = requested_effort(reasoning_config)
+ if _e is None:
+ _kimi_effort = (
+ "high" if _supported is KIMI_K3_EFFORTS else "medium"
+ )
else:
- _kimi_effort = {
- "minimal": "low",
- "low": "low",
- "medium": "medium",
- "high": "high",
- "xhigh": "high",
- "max": "high",
- "ultra": "high",
- }.get(_e, "medium")
+ _kimi_effort = clamp_effort(_e, _supported, _overrides)
api_kwargs["reasoning_effort"] = _kimi_effort
# Tencent TokenHub: top-level reasoning_effort (unless thinking disabled)
@@ -607,22 +604,13 @@ class ChatCompletionsTransport(ProviderTransport):
and reasoning_config.get("enabled") is False
)
if not _tokenhub_thinking_off:
- # TokenHub accepts low/medium/high. Map Hermes' full ladder
- # onto that set instead of dropping unknown levels to the
- # "high" default — dropping inverted the ladder for
- # "minimal" (asked for the least, got the most).
- _tokenhub_effort = "high"
- if reasoning_config and isinstance(reasoning_config, dict):
- _e = (reasoning_config.get("effort") or "").strip().lower()
- _tokenhub_effort = {
- "minimal": "low",
- "low": "low",
- "medium": "medium",
- "high": "high",
- "xhigh": "high",
- "max": "high",
- "ultra": "high",
- }.get(_e, "high")
+ # TokenHub accepts low/medium/high (declared in
+ # agent.reasoning_effort); default high when no effort was
+ # requested.
+ _e = requested_effort(reasoning_config)
+ _tokenhub_effort = (
+ "high" if _e is None else clamp_effort(_e, TOKENHUB_EFFORTS)
+ )
api_kwargs["reasoning_effort"] = _tokenhub_effort
# LM Studio: top-level reasoning_effort. Only emit when the model
diff --git a/agent/transports/codex.py b/agent/transports/codex.py
index 247cc18dfe3..b7727a03988 100644
--- a/agent/transports/codex.py
+++ b/agent/transports/codex.py
@@ -27,6 +27,13 @@ def _cache_scope_from_session_id(session_id: Optional[str]) -> str:
match = _CRON_SESSION_ID_RE.match(sid)
return match.group(1) if match else sid
+from agent.reasoning_effort import (
+ ACTUAL_RELAY_EFFORTS,
+ CODEX_RESPONSES_EFFORTS,
+ XAI_GROK46_EFFORTS,
+ XAI_LEGACY_EFFORTS,
+ clamp_effort,
+)
from agent.transports.base import ProviderTransport
from agent.transports.types import NormalizedResponse, ToolCall
@@ -432,34 +439,30 @@ class ResponsesApiTransport(ProviderTransport):
elif reasoning_config.get("effort"):
reasoning_effort = reasoning_config["effort"]
- # "ultra" is Hermes-internal ladder vocabulary (the Codex product
- # tier); no Responses-API backend accepts it verbatim, so the
- # baseline maps it to its wire cap "max" for EVERY model — the old
- # gpt-5.6-only guard leaked "ultra" untranslated to sibling models
- # and the request 400'd (same class as #89503 on the
- # chat-completions transport). Backend-specific branches below
- # override the baseline where the ceiling is narrower.
- _effort_clamp = {"minimal": "low", "ultra": "max"}
+ # Wire vocabularies are declared in agent.reasoning_effort; the shared
+ # clamp policy (nearest weaker supported level, never escalate,
+ # never invert the ladder) replaces the per-backend hand maps that
+ # repeatedly leaked internal levels like "ultra" to the wire
+ # (#89503 class) or clamped one rung below a model's real ceiling
+ # (#87279).
if params.get("is_xai_responses", False):
from agent.model_metadata import is_grok_46_family
- # Grok 4.6 accepts xhigh as a wire value; older Grok models top
- # out at high. max/ultra are Hermes ladder aliases for "this
- # model's ceiling", so they clamp to the strongest level the
- # model actually accepts — xhigh on grok-4.6, high elsewhere —
- # never one rung below it (#87279).
- if is_grok_46_family(model):
- _effort_clamp.update({"max": "xhigh", "ultra": "xhigh"})
- else:
- _effort_clamp["xhigh"] = "high"
- _effort_clamp.update({"max": "high", "ultra": "high"})
- if (params.get("provider") or "").strip().lower() == "actual":
- # Actual Computer relays to SGLang/vLLM backends that accept only
- # none/low/medium/high/max for reasoning effort — a forwarded
- # xhigh/ultra fails with a wrapped HTTP 400 ("Expecting value:
- # line 1 column 1"). Clamp Hermes' wider set to the supported one.
- _effort_clamp.update({"xhigh": "high", "ultra": "max"})
- reasoning_effort = _effort_clamp.get(reasoning_effort, reasoning_effort)
+ # Grok 4.6 accepts xhigh as a wire value; older Grok tops out
+ # at high.
+ _supported = (
+ XAI_GROK46_EFFORTS if is_grok_46_family(model)
+ else XAI_LEGACY_EFFORTS
+ )
+ elif (params.get("provider") or "").strip().lower() == "actual":
+ # Actual Computer relays to SGLang/vLLM backends:
+ # none/low/medium/high/max.
+ _supported = ACTUAL_RELAY_EFFORTS
+ else:
+ # OpenAI/Codex Responses backend rejects "minimal" and the
+ # internal "ultra" level.
+ _supported = CODEX_RESPONSES_EFFORTS
+ reasoning_effort = clamp_effort(reasoning_effort, _supported)
response_tools = _responses_tools(tools)
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 91129db7b8d..f40eb693bab 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1705,12 +1705,10 @@ def warm_openrouter_reasoning_caps_async() -> None:
).start()
-# Canonical low→high ordering used for nearest-level clamping. Superset of
-# hermes_constants.VALID_REASONING_EFFORTS ("none" included so an explicit
-# disable can be clamped too when a provider publishes it as a level).
-_REASONING_EFFORT_ORDER = (
- "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra",
-)
+# Canonical low→high ordering used for nearest-level clamping. Kept as an
+# alias of the single source of truth in ``agent.reasoning_effort``.
+from agent.reasoning_effort import EFFORT_LADDER as _REASONING_EFFORT_ORDER
+from agent.reasoning_effort import clamp_effort as _clamp_effort
def clamp_reasoning_effort_to_supported(
@@ -1719,38 +1717,17 @@ def clamp_reasoning_effort_to_supported(
) -> Optional[str]:
"""Clamp a requested reasoning effort to a provider's supported levels.
- Returns the requested effort unchanged when it is supported, when the
- supported list is unknown (None/empty), or when the effort isn't a
- recognized level (custom providers may use bespoke names — pass through
- rather than guess). Otherwise returns the nearest supported level,
- preferring the closest LOWER level so a clamp never silently escalates
- cost (requesting ``xhigh`` against ``[low, medium, high]`` yields
- ``high``; requesting ``minimal`` against ``[low, medium]`` yields
- ``low`` because no lower level exists).
+ Thin wrapper over the canonical policy in
+ :func:`agent.reasoning_effort.clamp_effort` (single implementation for
+ every transport and provider profile): keep a supported level verbatim,
+ otherwise nearest WEAKER supported level (never silently escalate cost),
+ weakest supported level when nothing weaker exists, pass through unknown
+ supported-sets and bespoke level names unchanged.
Ported from PrimeIntellect-ai/prime-agent#1258's thinking-level-map
normalization.
"""
- requested = str(effort or "").strip().lower()
- if not requested or not supported_efforts:
- return effort
- supported = [
- str(level).strip().lower()
- for level in supported_efforts
- if str(level).strip().lower() in _REASONING_EFFORT_ORDER
- ]
- if not supported or requested in supported:
- return effort
- if requested not in _REASONING_EFFORT_ORDER:
- return effort
- requested_idx = _REASONING_EFFORT_ORDER.index(requested)
- below = [
- level for level in supported
- if _REASONING_EFFORT_ORDER.index(level) < requested_idx
- ]
- if below:
- return max(below, key=_REASONING_EFFORT_ORDER.index)
- return min(supported, key=_REASONING_EFFORT_ORDER.index)
+ return _clamp_effort(effort, supported_efforts)
def fetch_openrouter_models(
diff --git a/plugins/model-providers/custom/__init__.py b/plugins/model-providers/custom/__init__.py
index 6353b59f59f..e3f02bc8229 100644
--- a/plugins/model-providers/custom/__init__.py
+++ b/plugins/model-providers/custom/__init__.py
@@ -64,12 +64,17 @@ class CustomProfile(ProviderProfile):
top_level["reasoning_effort"] = "none"
extra_body["think"] = False
elif _effort:
- # "ultra" is Hermes-internal ladder vocabulary — no known
- # OpenAI-compatible backend accepts it verbatim (GLM/ARK,
- # vLLM and SGLang all top out at "max"); cap it at the wire
- # ceiling instead of forwarding a guaranteed 400 (#89503).
- top_level["reasoning_effort"] = (
- "max" if _effort == "ultra" else _effort
+ # Clamp the internal ladder onto the widest OpenAI-compatible
+ # wire vocabulary (shared policy in agent.reasoning_effort) —
+ # GLM/ARK, vLLM and SGLang all top out at "max"; forwarding
+ # "ultra" verbatim is a guaranteed 400 (#89503).
+ from agent.reasoning_effort import (
+ OPENAI_COMPAT_WIRE_EFFORTS,
+ clamp_effort,
+ )
+
+ top_level["reasoning_effort"] = clamp_effort(
+ _effort, OPENAI_COMPAT_WIRE_EFFORTS
)
return extra_body, top_level
diff --git a/plugins/model-providers/deepseek/__init__.py b/plugins/model-providers/deepseek/__init__.py
index cf8c20f2d22..1273f51ed6e 100644
--- a/plugins/model-providers/deepseek/__init__.py
+++ b/plugins/model-providers/deepseek/__init__.py
@@ -71,15 +71,24 @@ class DeepSeekProfile(ProviderProfile):
if not enabled:
return extra_body, top_level
- # Effort mapping. Pass low/medium/high through; stronger levels → max.
- # When no effort is set we omit reasoning_effort so DeepSeek applies
- # its server default (currently high).
+ # Effort mapping via the shared vocabulary in agent.reasoning_effort
+ # (DeepSeek V4: low/medium/high/max, xhigh rounds up to max). When no
+ # effort is set we omit reasoning_effort so DeepSeek applies its
+ # server default (currently high).
if isinstance(reasoning_config, dict):
+ from agent.reasoning_effort import (
+ DEEPSEEK_V4_EFFORTS,
+ DEEPSEEK_V4_OVERRIDES,
+ clamp_effort,
+ )
+
effort = (reasoning_config.get("effort") or "").strip().lower()
- if effort in {"xhigh", "max", "ultra"}:
- top_level["reasoning_effort"] = "max"
- elif effort in {"low", "medium", "high"}:
- top_level["reasoning_effort"] = effort
+ if effort and effort != "none":
+ clamped = clamp_effort(
+ effort, DEEPSEEK_V4_EFFORTS, DEEPSEEK_V4_OVERRIDES
+ )
+ if clamped in DEEPSEEK_V4_EFFORTS:
+ top_level["reasoning_effort"] = clamped
return extra_body, top_level
diff --git a/plugins/model-providers/kimi-coding/__init__.py b/plugins/model-providers/kimi-coding/__init__.py
index 339dbdd358f..23b33417a2a 100644
--- a/plugins/model-providers/kimi-coding/__init__.py
+++ b/plugins/model-providers/kimi-coding/__init__.py
@@ -87,24 +87,22 @@ class KimiProfile(ProviderProfile):
# Enabled: prefer an explicit effort; only fall back to extra_body
# thinking when no recognized effort is requested.
- # K3 accepts low/high/max (default high). Map Hermes' wider effort
- # vocabulary onto K3's set:
- # low, minimal → low
- # medium, high → high
- # xhigh, max, ultra → max
- # ref: https://www.kimi.com/code/docs/en/kimi-code/models.html
- _K3_EFFORT_MAP = {
- "minimal": "low",
- "low": "low",
- "medium": "high",
- "high": "high",
- "xhigh": "max",
- "max": "max",
- "ultra": "max",
- }
+ # K3's vocabulary (low/high/max, default high) and its documented
+ # rounding (medium→high, xhigh→max) are declared in
+ # agent.reasoning_effort — shared with the chat-completions
+ # transport's Kimi path so both stay in sync.
+ from agent.reasoning_effort import (
+ KIMI_K3_EFFORTS,
+ KIMI_K3_OVERRIDES,
+ clamp_effort,
+ )
+
effort = (reasoning_config.get("effort") or "").strip().lower()
- k3_effort = _K3_EFFORT_MAP.get(effort)
- if k3_effort:
+ if effort and effort != "none":
+ k3_effort = clamp_effort(effort, KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES)
+ else:
+ k3_effort = None
+ if k3_effort in KIMI_K3_EFFORTS:
top_level["reasoning_effort"] = k3_effort
else:
extra_body["thinking"] = {"type": "enabled"}
diff --git a/plugins/model-providers/meta-ai/__init__.py b/plugins/model-providers/meta-ai/__init__.py
index 3f44fdc65e6..de2a3847f58 100644
--- a/plugins/model-providers/meta-ai/__init__.py
+++ b/plugins/model-providers/meta-ai/__init__.py
@@ -38,10 +38,9 @@ from providers.base import ProviderProfile
def _resolve_effort(reasoning_config: dict | None) -> str:
"""Map Hermes' reasoning_config to a Meta-safe ``reasoning_effort`` value.
- - reasoning disabled / effort "none" -> "minimal" (Meta 400s on "none")
- - low | medium | high -> passthrough
- - max | xhigh | ultra -> "xhigh"
- - unset / unknown -> "medium"
+ Meta's vocabulary (minimal..xhigh; rejects ``none``) is declared in
+ agent.reasoning_effort. Disabled/"none" maps to ``minimal`` (the closest
+ Meta has to off); unset/bespoke levels fall to ``medium``.
"""
rc = reasoning_config or {}
if rc.get("enabled") is False:
@@ -49,11 +48,11 @@ def _resolve_effort(reasoning_config: dict | None) -> str:
effort = str(rc.get("effort") or "").strip().lower()
if effort in {"", "none"}:
return "minimal" if effort == "none" else "medium"
- if effort in {"low", "medium", "high"}:
- return effort
- if effort in {"max", "xhigh", "ultra"}:
- return "xhigh"
- return "medium"
+
+ from agent.reasoning_effort import META_AI_EFFORTS, clamp_effort
+
+ clamped = clamp_effort(effort, META_AI_EFFORTS)
+ return clamped if clamped in META_AI_EFFORTS else "medium"
class MetaAIProfile(ProviderProfile):
diff --git a/plugins/model-providers/ollama-cloud/__init__.py b/plugins/model-providers/ollama-cloud/__init__.py
index e849c1da27f..ccc1eb19b31 100644
--- a/plugins/model-providers/ollama-cloud/__init__.py
+++ b/plugins/model-providers/ollama-cloud/__init__.py
@@ -64,16 +64,22 @@ class OllamaCloudProfile(ProviderProfile):
return {}, {}
if effort == "none":
return {}, {"reasoning_effort": "none"} # explicit off switch
- if effort in ("xhigh", "max", "ultra"):
- top_level["reasoning_effort"] = "max"
- elif effort in ("low", "medium", "high"):
- top_level["reasoning_effort"] = effort
- # Any other value (including "minimal", which Ollama Cloud's
- # /v1/chat/completions rejects with HTTP 400 — its accepted set is
- # {low, medium, high, max, none}) is omitted so the model applies
- # its own default rather than triggering a hard 400. Matches the
- # sibling deepseek / opencode-zen profiles, which target the same
- # backend and omit unrecognized efforts rather than send garbage.
+ # Accepted set {none, low, medium, high, max} is declared in
+ # agent.reasoning_effort ("minimal" is rejected with HTTP 400 →
+ # clamps to low; xhigh rounds up to max). Bespoke levels outside
+ # the ladder are omitted so the model applies its own default
+ # rather than triggering a hard 400.
+ from agent.reasoning_effort import (
+ OLLAMA_CLOUD_EFFORTS,
+ OLLAMA_CLOUD_OVERRIDES,
+ clamp_effort,
+ )
+
+ clamped = clamp_effort(
+ effort, OLLAMA_CLOUD_EFFORTS, OLLAMA_CLOUD_OVERRIDES
+ )
+ if clamped in OLLAMA_CLOUD_EFFORTS:
+ top_level["reasoning_effort"] = clamped
return {}, top_level
diff --git a/plugins/model-providers/opencode-zen/__init__.py b/plugins/model-providers/opencode-zen/__init__.py
index 7704442deba..7b6789b8948 100644
--- a/plugins/model-providers/opencode-zen/__init__.py
+++ b/plugins/model-providers/opencode-zen/__init__.py
@@ -75,8 +75,8 @@ class OpenCodeGoProfile(ProviderProfile):
if _is_glm_5_2_model(model):
# GLM-5.2 on OpenCode Go uses its native OpenAI-compatible
- # reasoning_effort knob, which has exactly two enabled levels:
- # high and max. Map Hermes' richer scale onto those; leave the
+ # reasoning_effort knob (high/max — declared in
+ # agent.reasoning_effort, shared with the zai profile); leave the
# server default alone when reasoning is disabled or unset.
if not isinstance(reasoning_config, dict):
return extra_body, top_level
@@ -85,7 +85,16 @@ class OpenCodeGoProfile(ProviderProfile):
effort = (reasoning_config.get("effort") or "").strip().lower()
if not effort or effort == "none":
return extra_body, top_level
- top_level["reasoning_effort"] = "max" if effort in {"xhigh", "max", "ultra"} else "high"
+ from agent.reasoning_effort import (
+ GLM52_EFFORTS,
+ GLM52_OVERRIDES,
+ clamp_effort,
+ )
+
+ clamped = clamp_effort(effort, GLM52_EFFORTS, GLM52_OVERRIDES)
+ top_level["reasoning_effort"] = (
+ clamped if clamped in GLM52_EFFORTS else "high"
+ )
return extra_body, top_level
if _is_kimi_k2_model(model):
@@ -102,10 +111,12 @@ class OpenCodeGoProfile(ProviderProfile):
return extra_body, top_level
effort = (reasoning_config.get("effort") or "").strip().lower()
- if effort in {"xhigh", "max", "ultra"}:
- top_level["reasoning_effort"] = "high"
- elif effort in {"low", "medium", "high"}:
- top_level["reasoning_effort"] = effort
+ if effort and effort != "none":
+ from agent.reasoning_effort import KIMI_K2_EFFORTS, clamp_effort
+
+ clamped = clamp_effort(effort, KIMI_K2_EFFORTS)
+ if clamped in KIMI_K2_EFFORTS:
+ top_level["reasoning_effort"] = clamped
# Avoid "cannot specify both 'thinking' and 'reasoning_effort'" HTTP 400:
# only send extra_body["thinking"] when no reasoning_effort is set.
@@ -126,10 +137,18 @@ class OpenCodeGoProfile(ProviderProfile):
if isinstance(reasoning_config, dict):
effort = (reasoning_config.get("effort") or "").strip().lower()
- if effort in {"xhigh", "max", "ultra"}:
- top_level["reasoning_effort"] = "max"
- elif effort in {"low", "medium", "high"}:
- top_level["reasoning_effort"] = effort
+ if effort and effort != "none":
+ from agent.reasoning_effort import (
+ DEEPSEEK_V4_EFFORTS,
+ DEEPSEEK_V4_OVERRIDES,
+ clamp_effort,
+ )
+
+ clamped = clamp_effort(
+ effort, DEEPSEEK_V4_EFFORTS, DEEPSEEK_V4_OVERRIDES
+ )
+ if clamped in DEEPSEEK_V4_EFFORTS:
+ top_level["reasoning_effort"] = clamped
# Avoid "cannot specify both 'thinking' and 'reasoning_effort'" HTTP 400:
# only send extra_body["thinking"] when no reasoning_effort is set.
diff --git a/plugins/model-providers/upstage/__init__.py b/plugins/model-providers/upstage/__init__.py
index b050051bade..1d6f5749f0a 100644
--- a/plugins/model-providers/upstage/__init__.py
+++ b/plugins/model-providers/upstage/__init__.py
@@ -75,21 +75,24 @@ class UpstageProfile(ProviderProfile):
if reasoning_config.get("enabled") is False:
return {}, top_level
- # Map Hermes' effort vocabulary onto Solar's accepted set. xhigh/max/
- # ultra collapse to high (Solar's strongest). minimal → off (omit).
- # Unknown-but-enabled efforts (future vocabulary additions above
- # "high", per the max/ultra precedent in #62650) also collapse to
- # high rather than silently downgrading to the medium default.
+ # Map Hermes' effort vocabulary onto Solar's accepted set via the
+ # shared clamp (agent.reasoning_effort). minimal → omit (Solar's
+ # minimal means off); unknown-but-enabled bespoke levels collapse to
+ # high rather than silently downgrading (#62650 precedent).
effort = (reasoning_config.get("effort") or "").strip().lower()
if not effort:
top_level["reasoning_effort"] = _DEFAULT_REASONING_EFFORT
return {}, top_level
- mapped = {
- "minimal": None,
- "low": "low",
- "medium": "medium",
- "high": "high",
- }.get(effort, "high")
+ if effort == "minimal":
+ return {}, top_level
+
+ from agent.reasoning_effort import EFFORT_LADDER, SOLAR_EFFORTS, clamp_effort
+
+ mapped = clamp_effort(effort, SOLAR_EFFORTS)
+ if mapped not in SOLAR_EFFORTS:
+ # Bespoke level outside the ladder — Solar precedent is to run
+ # at full strength rather than quietly fall to the default.
+ mapped = "high" if effort not in EFFORT_LADDER else None
if mapped:
top_level["reasoning_effort"] = mapped
diff --git a/plugins/model-providers/zai/__init__.py b/plugins/model-providers/zai/__init__.py
index 76426b77dcd..322068617e1 100644
--- a/plugins/model-providers/zai/__init__.py
+++ b/plugins/model-providers/zai/__init__.py
@@ -76,10 +76,14 @@ def _glm_5_2_reasoning_effort(reasoning_config: dict | None) -> str | None:
if not effort or effort == "none":
return None
- if effort in {"xhigh", "max", "ultra"}:
- return "max"
- # low / medium / minimal / high all clamp to GLM-5.2's minimum: high.
- return "high"
+ # GLM-5.2's two-level vocabulary (high = its minimum thinking level,
+ # max = top tier) is declared in agent.reasoning_effort; xhigh rounds up
+ # to max. Everything at or below high clamps to high — GLM cannot think
+ # less than that.
+ from agent.reasoning_effort import GLM52_EFFORTS, GLM52_OVERRIDES, clamp_effort
+
+ clamped = clamp_effort(effort, GLM52_EFFORTS, GLM52_OVERRIDES)
+ return clamped if clamped in GLM52_EFFORTS else "high"
class ZaiProfile(ProviderProfile):
diff --git a/tests/agent/test_reasoning_effort_module.py b/tests/agent/test_reasoning_effort_module.py
new file mode 100644
index 00000000000..5b96a0dd803
--- /dev/null
+++ b/tests/agent/test_reasoning_effort_module.py
@@ -0,0 +1,151 @@
+"""Tests for agent.reasoning_effort — the canonical effort ladder + clamp.
+
+This module is the single source of truth every transport and provider
+profile uses to translate Hermes' internal effort ladder onto a wire's
+supported vocabulary. The policy under test:
+
+- supported levels pass through verbatim
+- unsupported levels clamp to the nearest WEAKER supported level (never
+ escalate above the ask, never invert the ladder)
+- nothing weaker → weakest supported level
+- "none" is never a degradation target (would silently disable thinking)
+- declared overrides (vendor-documented roundings) win over nearest-weaker
+- unknown supported-sets and bespoke level names pass through unchanged
+"""
+
+import pytest
+
+from agent.reasoning_effort import (
+ CODEX_RESPONSES_EFFORTS,
+ EFFORT_LADDER,
+ GLM52_EFFORTS,
+ GLM52_OVERRIDES,
+ KIMI_K2_EFFORTS,
+ KIMI_K3_EFFORTS,
+ KIMI_K3_OVERRIDES,
+ OPENAI_COMPAT_WIRE_EFFORTS,
+ clamp_effort,
+ kimi_supported_efforts,
+ requested_effort,
+)
+from hermes_constants import VALID_REASONING_EFFORTS
+
+
+class TestLadderContract:
+ def test_ladder_is_superset_of_valid_efforts(self):
+ """The canonical ladder must cover every level users can configure —
+ an internal level missing from the ladder would pass through clamps
+ unchanged and leak to the wire (the #89503 class)."""
+ for level in VALID_REASONING_EFFORTS:
+ assert level in EFFORT_LADDER, level
+
+ def test_no_declared_wire_set_contains_ultra(self):
+ """ultra is internal vocabulary; every wire set must exclude it so it
+ always clamps down."""
+ import agent.reasoning_effort as mod
+
+ for name in dir(mod):
+ if name.endswith("_EFFORTS"):
+ assert "ultra" not in getattr(mod, name), name
+
+
+class TestClampEffort:
+ def test_supported_levels_pass_through(self):
+ for level in OPENAI_COMPAT_WIRE_EFFORTS:
+ assert clamp_effort(level, OPENAI_COMPAT_WIRE_EFFORTS) == level
+
+ def test_ultra_clamps_to_max_on_openai_wire(self):
+ assert clamp_effort("ultra", OPENAI_COMPAT_WIRE_EFFORTS) == "max"
+
+ def test_nearest_weaker_never_escalates(self):
+ # xhigh against low..high → high (weaker), never max.
+ assert clamp_effort("xhigh", ("low", "medium", "high", "max")) == "high"
+
+ def test_floor_when_nothing_weaker(self):
+ assert clamp_effort("minimal", ("low", "medium")) == "low"
+
+ def test_none_is_never_a_degradation_target(self):
+ # minimal against {none, low}: clamping to none would silently
+ # disable thinking — must take low.
+ assert clamp_effort("minimal", ("none", "low", "high")) == "low"
+
+ def test_none_still_passes_through_when_requested(self):
+ assert clamp_effort("none", ("none", "low", "high")) == "none"
+
+ def test_unknown_supported_set_passes_through(self):
+ assert clamp_effort("ultra", None) == "ultra"
+ assert clamp_effort("ultra", []) == "ultra"
+
+ def test_bespoke_level_passes_through(self):
+ assert clamp_effort("turbo-9000", ("low", "high")) == "turbo-9000"
+
+ def test_empty_effort_passes_through(self):
+ assert clamp_effort(None, ("low",)) is None
+ assert clamp_effort("", ("low",)) == ""
+
+ def test_overrides_win(self):
+ assert clamp_effort("medium", KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES) == "high"
+ assert clamp_effort("xhigh", KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES) == "max"
+
+ def test_override_ignored_when_target_unsupported(self):
+ # An override pointing outside the supported set falls back to the
+ # ladder walk instead of emitting an invalid level.
+ assert clamp_effort("medium", ("low", "high"), {"medium": "max"}) == "low"
+
+ def test_monotonic_over_full_ladder(self):
+ """A stronger ask never resolves weaker than a weaker ask — for every
+ declared wire set."""
+ import agent.reasoning_effort as mod
+
+ sets = [
+ getattr(mod, name) for name in dir(mod) if name.endswith("_EFFORTS")
+ ]
+ enabled_ladder = [l for l in EFFORT_LADDER if l != "none"]
+ for supported in sets:
+ prev_rank = -1
+ for level in enabled_ladder:
+ out = clamp_effort(level, supported)
+ rank = EFFORT_LADDER.index(out)
+ assert rank >= prev_rank, (supported, level, out)
+ prev_rank = rank
+
+
+class TestKimiVocabulary:
+ @pytest.mark.parametrize(
+ "model", ["k3", "kimi-k3", "kimi-k3-cot", "moonshotai/kimi-k3"]
+ )
+ def test_k3_slugs(self, model):
+ assert kimi_supported_efforts(model) is KIMI_K3_EFFORTS
+
+ @pytest.mark.parametrize(
+ "model", ["kimi-k2.6", "moonshotai/kimi-k2-0905", "kimi-latest", None]
+ )
+ def test_k2_era_slugs(self, model):
+ assert kimi_supported_efforts(model) is KIMI_K2_EFFORTS
+
+
+class TestGlm52Vocabulary:
+ def test_two_level_set(self):
+ assert clamp_effort("ultra", GLM52_EFFORTS, GLM52_OVERRIDES) == "max"
+ assert clamp_effort("xhigh", GLM52_EFFORTS, GLM52_OVERRIDES) == "max"
+ # GLM's floor is high — weaker asks land there.
+ assert clamp_effort("low", GLM52_EFFORTS, GLM52_OVERRIDES) == "high"
+ assert clamp_effort("medium", GLM52_EFFORTS, GLM52_OVERRIDES) == "high"
+
+
+class TestCodexVocabulary:
+ def test_minimal_and_ultra(self):
+ assert clamp_effort("minimal", CODEX_RESPONSES_EFFORTS) == "low"
+ assert clamp_effort("ultra", CODEX_RESPONSES_EFFORTS) == "max"
+
+
+class TestRequestedEffort:
+ def test_extracts_effort(self):
+ assert requested_effort({"enabled": True, "effort": "High"}) == "high"
+
+ def test_none_when_absent_or_disabled(self):
+ assert requested_effort(None) is None
+ assert requested_effort({}) is None
+ assert requested_effort({"enabled": False, "effort": "high"}) is None
+ assert requested_effort("not-a-dict") is None
+ assert requested_effort({"effort": ""}) is None
diff --git a/tests/plugins/model_providers/test_ollama_cloud_profile.py b/tests/plugins/model_providers/test_ollama_cloud_profile.py
index 7321aae91e2..540a509aa4a 100644
--- a/tests/plugins/model_providers/test_ollama_cloud_profile.py
+++ b/tests/plugins/model_providers/test_ollama_cloud_profile.py
@@ -118,15 +118,17 @@ class TestOllamaCloudReasoningEffort:
)
assert top_level == {}
- def test_minimal_effort_omitted(self, ollama_cloud_profile):
- """``minimal`` is a real Hermes effort level but is not documented for
- Ollama Cloud's /v1/chat/completions, so it is omitted rather than sent
- verbatim (which could trigger a 400)."""
+ def test_minimal_effort_clamps_to_low(self, ollama_cloud_profile):
+ """``minimal`` is a real Hermes effort level but is rejected by
+ Ollama Cloud's /v1/chat/completions. The shared clamp degrades it to
+ ``low`` — the nearest supported level — instead of silently dropping
+ the user's ask (old behavior left the server default, i.e. MORE
+ thinking than requested: a ladder inversion)."""
_, top_level = ollama_cloud_profile.build_api_kwargs_extras(
supports_reasoning=True,
reasoning_config={"enabled": True, "effort": "minimal"},
)
- assert top_level == {}
+ assert top_level == {"reasoning_effort": "low"}
class TestOllamaCloudFullKwargsIntegration:
diff --git a/tests/plugins/model_providers/test_opencode_go_profile.py b/tests/plugins/model_providers/test_opencode_go_profile.py
index 24b4274a3a5..5b24821cf9d 100644
--- a/tests/plugins/model_providers/test_opencode_go_profile.py
+++ b/tests/plugins/model_providers/test_opencode_go_profile.py
@@ -35,14 +35,16 @@ class TestOpenCodeGoKimiReasoning:
assert extra_body == {"thinking": {"type": "disabled"}}
assert top_level == {}
- def test_minimal_effort_enables_thinking_without_effort(self, opencode_go_profile):
- # "minimal" is not a Moonshot-supported value — drop it, keep thinking on.
+ def test_minimal_effort_clamps_to_low(self, opencode_go_profile):
+ # "minimal" is below Moonshot's floor — the shared clamp degrades it
+ # to "low" (nearest supported) instead of dropping the ask and
+ # leaving the server default (which was MORE thinking than asked).
extra_body, top_level = opencode_go_profile.build_api_kwargs_extras(
reasoning_config={"enabled": True, "effort": "minimal"},
model="kimi-k2.6",
)
- assert extra_body == {"thinking": {"type": "enabled"}}
- assert top_level == {}
+ assert extra_body == {}
+ assert top_level == {"reasoning_effort": "low"}
@pytest.mark.parametrize(
"effort",