Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

refactor(tencent): capability-driven thinking coercion

Felipe Rodrigues Gare Carniellic6b4cb93b712
diff --git a/litellm/llms/tencent/chat/transformation.py b/litellm/llms/tencent/chat/transformation.py
index 08b7c364e92..283a227943d 100644
--- a/litellm/llms/tencent/chat/transformation.py
+++ b/litellm/llms/tencent/chat/transformation.py
@@ -3,14 +3,36 @@ Translates from OpenAI's `/v1/chat/completions` to Tencent TokenHub's
OpenAI-compatible endpoint.
"""
-from typing import Final
+from collections.abc import Mapping
+from typing import Final, TypedDict
+from typing_extensions import ReadOnly
+
+import litellm
from litellm.secret_managers.main import get_secret_str
from litellm.utils import supports_reasoning
from ...openai.chat.gpt_transformation import OpenAIGPTConfig
+class ThinkingPayload(TypedDict, total=False):
+ """Tencent TokenHub `thinking` object.
+
+ `type` ("enabled"/"disabled"/"adaptive") is required by TokenHub when the
+ object is passed; `budget_tokens` is auto-filled server-side when omitted.
+ Ref: https://www.tencentcloud.com/document/product/1300/82345
+ """
+
+ type: ReadOnly[str]
+ budget_tokens: ReadOnly[int]
+
+
+class TencentExtraBody(TypedDict, total=False):
+ """`extra_body` payload for TokenHub chat requests."""
+
+ thinking: ReadOnly[Mapping[str, object]]
+
+
class TencentChatConfig(OpenAIGPTConfig):
def get_supported_openai_params(self, model: str) -> list:
params: Final = super().get_supported_openai_params(model)
@@ -25,42 +47,75 @@ class TencentChatConfig(OpenAIGPTConfig):
model: str,
drop_params: bool,
) -> dict:
- optional_params = super().map_openai_params(non_default_params, optional_params, model, drop_params)
-
- thinking_value: Final = optional_params.pop("thinking", None)
- reasoning_effort: Final = optional_params.pop("reasoning_effort", None)
-
- thinking: dict | None = None
+ mapped_params: Final = super().map_openai_params(non_default_params, optional_params, model, drop_params)
+
+ thinking_value: Final = mapped_params.pop("thinking", None)
+ reasoning_effort: Final = mapped_params.pop("reasoning_effort", None)
+
+ thinking: Final = self._resolve_thinking_payload(
+ model=model,
+ thinking_value=thinking_value,
+ reasoning_effort=reasoning_effort,
+ )
+ if thinking is None:
+ return mapped_params
+
+ # TokenHub expects `thinking` in the request JSON body, but the OpenAI
+ # SDK's chat.completions.create() rejects unknown top-level kwargs, so
+ # it travels via `extra_body`, which the SDK merges into the payload.
+ existing_extra_body: Final = mapped_params.pop("extra_body", None)
+ if isinstance(existing_extra_body, dict):
+ merged_extra_body: Final[TencentExtraBody] = {**existing_extra_body, "thinking": thinking}
+ else:
+ merged_extra_body: Final[TencentExtraBody] = {"thinking": thinking}
+ mapped_params["extra_body"] = merged_extra_body
+ return mapped_params
+
+ @classmethod
+ def _resolve_thinking_payload(
+ cls,
+ model: str,
+ thinking_value: object,
+ reasoning_effort: object,
+ ) -> Mapping[str, object] | None:
if isinstance(thinking_value, dict):
- thinking = thinking_value
- elif reasoning_effort is not None:
- # TokenHub recommends explicitly disabling thinking instead of
+ return cls._coerce_thinking_type_for_model(model=model, thinking=thinking_value)
+ if isinstance(reasoning_effort, str):
+ # TokenHub recommends explicitly disabling thinking rather than
# relying on per-model defaults (deepseek-v4-* default to enabled).
- thinking = {"type": "disabled" if reasoning_effort == "none" else "enabled"}
-
- if thinking is not None:
- thinking = self._normalize_thinking_type_for_model(model=model, thinking=thinking)
- # Tencent TokenHub expects `thinking` in the request JSON body, but
- # the OpenAI SDK's chat.completions.create() rejects unknown
- # top-level kwargs. Route it through `extra_body` so it is merged
- # into the payload instead of passed as a keyword argument.
- extra_body: Final = optional_params.setdefault("extra_body", {})
- extra_body["thinking"] = thinking
-
- return optional_params
+ payload: Final[ThinkingPayload] = {"type": "disabled" if reasoning_effort == "none" else "enabled"}
+ return cls._coerce_thinking_type_for_model(model=model, thinking=payload)
+ return None
@staticmethod
- def _normalize_thinking_type_for_model(model: str, thinking: dict) -> dict:
- """Coerce `thinking.type` values the model does not accept.
-
- MiniMax models on TokenHub only accept "adaptive" or "disabled" —
- sending "enabled" returns a 400. "adaptive" is the closest semantic
- (the model decides when to think), so "enabled" is coerced to it.
+ def _coerce_thinking_type_for_model(model: str, thinking: Mapping[str, object]) -> Mapping[str, object]:
+ """Coerce `thinking.type` to a value the model accepts.
+
+ MiniMax models on TokenHub only accept "adaptive"/"disabled" and reject
+ "enabled" with a 400; "adaptive" (the model decides when to think) is
+ the closest semantic, so "enabled" is coerced for them. The capability
+ is read from the model map's `supports_adaptive_thinking` flag, so
+ aliases and newly onboarded adaptive-only models need no code change.
Ref: https://www.tencentcloud.com/document/product/1300/82345
"""
- if thinking.get("type") == "enabled" and "minimax" in model.lower():
- return {**thinking, "type": "adaptive"}
- return thinking
+ if thinking.get("type") != "enabled" or not TencentChatConfig._is_adaptive_thinking_model(model):
+ return thinking
+
+ budget: Final = thinking.get("budget_tokens")
+ if isinstance(budget, int):
+ coerced_with_budget: Final[ThinkingPayload] = {"type": "adaptive", "budget_tokens": budget}
+ return coerced_with_budget
+ coerced: Final[ThinkingPayload] = {"type": "adaptive"}
+ return coerced
+
+ @staticmethod
+ def _is_adaptive_thinking_model(model: str) -> bool:
+ """Read `supports_adaptive_thinking` from the model map under tencent."""
+ try:
+ model_info: Final = litellm.get_model_info(model=model, custom_llm_provider="tencent")
+ except Exception: # noqa: BLE001 # get_model_info raises a bare Exception for unmapped models
+ return False
+ return model_info.get("supports_adaptive_thinking") is True
def _get_openai_compatible_provider_info(
self, api_base: str | None, api_key: str | None
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index 3af7d9e5019..884507a8905 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -49764,6 +49764,26 @@
"supports_reasoning": true,
"supports_vision": false
},
+ "tencent/minimax-m3": {
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 6e-08,
+ "input_cost_per_token": 3e-07,
+ "input_cost_per_token_cache_hit": 6e-08,
+ "litellm_provider": "tencent",
+ "max_input_tokens": 1000000,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "source": "https://www.tencentcloud.com/products/tokenhub",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
+ "supports_adaptive_thinking": true,
+ "supports_function_calling": true,
+ "supports_native_streaming": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_vision": false
+ },
"cognition/swe-1.6": {
"input_cost_per_token": 5e-07,
"output_cost_per_token": 2.5e-06,
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 3af7d9e5019..884507a8905 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -49764,6 +49764,26 @@
"supports_reasoning": true,
"supports_vision": false
},
+ "tencent/minimax-m3": {
+ "cache_creation_input_token_cost": 0.0,
+ "cache_read_input_token_cost": 6e-08,
+ "input_cost_per_token": 3e-07,
+ "input_cost_per_token_cache_hit": 6e-08,
+ "litellm_provider": "tencent",
+ "max_input_tokens": 1000000,
+ "mode": "chat",
+ "output_cost_per_token": 1.2e-06,
+ "source": "https://www.tencentcloud.com/products/tokenhub",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
+ "supports_adaptive_thinking": true,
+ "supports_function_calling": true,
+ "supports_native_streaming": true,
+ "supports_prompt_caching": true,
+ "supports_reasoning": true,
+ "supports_vision": false
+ },
"cognition/swe-1.6": {
"input_cost_per_token": 5e-07,
"output_cost_per_token": 2.5e-06,
diff --git a/tests/test_litellm/llms/tencent/chat/test_tencent_chat_transformation.py b/tests/test_litellm/llms/tencent/chat/test_tencent_chat_transformation.py
index 806d585a4c9..a540ea6cacd 100644
--- a/tests/test_litellm/llms/tencent/chat/test_tencent_chat_transformation.py
+++ b/tests/test_litellm/llms/tencent/chat/test_tencent_chat_transformation.py
@@ -159,17 +159,22 @@ def test_transform_request_never_passes_thinking_as_top_level_kwarg():
assert data["extra_body"]["thinking"] == {"type": "enabled", "budget_tokens": 1024}
-class TestMinimaxThinkingCoercion:
+class TestAdaptiveThinkingCoercion:
"""
- MiniMax models on TokenHub only accept thinking.type "adaptive"/"disabled" —
- "enabled" returns a 400. Ref: https://www.tencentcloud.com/document/product/1300/82345
+ Models flagged `supports_adaptive_thinking` in the cost map (e.g.
+ tencent/minimax-m3) only accept thinking.type "adaptive"/"disabled" —
+ "enabled" returns a 400 from TokenHub.
+ Ref: https://www.tencentcloud.com/document/product/1300/82345
"""
- def test_reasoning_effort_maps_to_adaptive_for_minimax(self):
+ def test_reasoning_effort_maps_to_adaptive_for_adaptive_only_model(self):
config = TencentChatConfig()
- with patch(
- "litellm.llms.tencent.chat.transformation.supports_reasoning",
- return_value=True,
+ with (
+ patch(
+ "litellm.llms.tencent.chat.transformation.supports_reasoning",
+ return_value=True,
+ ),
+ patch.object(TencentChatConfig, "_is_adaptive_thinking_model", return_value=True),
):
result = config.map_openai_params(
non_default_params={"reasoning_effort": "medium"},
@@ -180,26 +185,32 @@ class TestMinimaxThinkingCoercion:
assert result["extra_body"]["thinking"] == {"type": "adaptive"}
- def test_explicit_enabled_thinking_coerced_to_adaptive_for_minimax(self):
+ def test_explicit_enabled_thinking_coerced_to_adaptive(self):
config = TencentChatConfig()
- with patch(
- "litellm.llms.tencent.chat.transformation.supports_reasoning",
- return_value=True,
+ with (
+ patch(
+ "litellm.llms.tencent.chat.transformation.supports_reasoning",
+ return_value=True,
+ ),
+ patch.object(TencentChatConfig, "_is_adaptive_thinking_model", return_value=True),
):
result = config.map_openai_params(
non_default_params={"thinking": {"type": "enabled", "budget_tokens": 4096}},
optional_params={},
- model="minimax-m3",
+ model="tencent/minimax-m3",
drop_params=False,
)
assert result["extra_body"]["thinking"] == {"type": "adaptive", "budget_tokens": 4096}
- def test_disabled_thinking_kept_for_minimax(self):
+ def test_disabled_thinking_kept_for_adaptive_only_model(self):
config = TencentChatConfig()
- with patch(
- "litellm.llms.tencent.chat.transformation.supports_reasoning",
- return_value=True,
+ with (
+ patch(
+ "litellm.llms.tencent.chat.transformation.supports_reasoning",
+ return_value=True,
+ ),
+ patch.object(TencentChatConfig, "_is_adaptive_thinking_model", return_value=True),
):
result = config.map_openai_params(
non_default_params={"thinking": {"type": "disabled"}},
@@ -210,11 +221,14 @@ class TestMinimaxThinkingCoercion:
assert result["extra_body"]["thinking"] == {"type": "disabled"}
- def test_none_reasoning_effort_disables_thinking_for_minimax(self):
+ def test_none_reasoning_effort_disables_thinking_for_adaptive_only_model(self):
config = TencentChatConfig()
- with patch(
- "litellm.llms.tencent.chat.transformation.supports_reasoning",
- return_value=True,
+ with (
+ patch(
+ "litellm.llms.tencent.chat.transformation.supports_reasoning",
+ return_value=True,
+ ),
+ patch.object(TencentChatConfig, "_is_adaptive_thinking_model", return_value=True),
):
result = config.map_openai_params(
non_default_params={"reasoning_effort": "none"},
@@ -225,11 +239,14 @@ class TestMinimaxThinkingCoercion:
assert result["extra_body"]["thinking"] == {"type": "disabled"}
- def test_non_minimax_model_keeps_enabled(self):
+ def test_non_adaptive_model_keeps_enabled(self):
config = TencentChatConfig()
- with patch(
- "litellm.llms.tencent.chat.transformation.supports_reasoning",
- return_value=True,
+ with (
+ patch(
+ "litellm.llms.tencent.chat.transformation.supports_reasoning",
+ return_value=True,
+ ),
+ patch.object(TencentChatConfig, "_is_adaptive_thinking_model", return_value=False),
):
result = config.map_openai_params(
non_default_params={"reasoning_effort": "high"},
@@ -240,6 +257,28 @@ class TestMinimaxThinkingCoercion:
assert result["extra_body"]["thinking"] == {"type": "enabled"}
+ def test_unmapped_model_keeps_enabled(self):
+ """Models absent from the cost map never get coerced."""
+ config = TencentChatConfig()
+ assert config._is_adaptive_thinking_model("tencent/no-such-model") is False
+
+
+def test_minimax_m3_cost_map_entry_marks_adaptive_thinking():
+ """The capability flag driving the coercion must exist in the cost map
+ (and its backup, which is shipped with the package)."""
+ import json
+ from pathlib import Path
+
+ repo_root = Path(__file__).parents[5]
+ for filename in ("model_prices_and_context_window.json", "litellm/model_prices_and_context_window_backup.json"):
+ with open(repo_root / filename) as f:
+ entry = json.load(f).get("tencent/minimax-m3")
+
+ assert entry is not None, f"tencent/minimax-m3 not found in {filename}"
+ assert entry["litellm_provider"] == "tencent"
+ assert entry.get("supports_adaptive_thinking") is True
+ assert entry.get("supports_reasoning") is True
+
def test_get_complete_url_default():
config = TencentChatConfig()