feat(agent): adaptive thinking for Kimi-family Anthropic endpoints

Kimi's Anthropic-compatible endpoints (api.moonshot.cn/anthropic,
api.kimi.com/coding) implement the adaptive thinking contract — they
accept thinking.type=adaptive + output_config.effort (all of low,
medium, high, xhigh, max verified live) and return thinking blocks, and
the replay-validation 400s that originally motivated dropping the
parameter (#13848) no longer occur.

_supports_adaptive_thinking() now returns True for Kimi-family models,
so they get thinking={type: adaptive, display: summarized} +
output_config.effort via ADAPTIVE_EFFORT_MAP instead of nothing, and
the blanket drop of the thinking parameter for Kimi-family endpoints is
removed. MiniMax and other non-adaptive third parties keep the manual
budget_tokens path; Claude behavior is unchanged.
This commit is contained in:
liqiping 2026-07-19 00:52:23 +00:00 • committed by Teknium
parent 5f2bfb6631
commit 60811ced37
4 changed files with 112 additions and 98 deletions

View file

@ -247,7 +247,13 @@ def _supports_adaptive_thinking(model: str) -> bool:
only returns False for the explicit legacy list of older Claude families
that require manual budget-based thinking. Non-Claude Anthropic-Messages
models (minimax, qwen3, …) return False so they keep the manual path.
Kimi / Moonshot models are the exception: their Anthropic-compatible
endpoints implement the adaptive contract (``thinking.type="adaptive"``
+ ``output_config.effort``, including ``xhigh`` and ``display``).
"""
if _model_name_is_kimi_family(model):
return True
if not _is_claude_model(model):
return False
m = model.lower()
@ -2624,25 +2630,19 @@ def build_anthropic_kwargs(
# MiniMax Anthropic-compat endpoints support thinking (manual mode only,
# not adaptive). Haiku does NOT support extended thinking — skip entirely.
#
# Kimi's /coding endpoint speaks the Anthropic Messages protocol but has
# its own thinking semantics: when ``thinking.enabled`` is sent, Kimi
# validates the message history and requires every prior assistant
# tool-call message to carry OpenAI-style ``reasoning_content``. The
# Anthropic path never populates that field, and
# ``convert_messages_to_anthropic`` strips all Anthropic thinking blocks
# on third-party endpoints — so the request fails with HTTP 400
# "thinking is enabled but reasoning_content is missing in assistant
# tool call message at index N". Kimi's reasoning is driven server-side
# on the /coding route, so skip Anthropic's thinking parameter entirely
# for that host. (Kimi on chat_completions enables thinking via
# extra_body in the ChatCompletionsTransport — see #13503.)
# Kimi / Moonshot models also use adaptive thinking: their
# Anthropic-compatible endpoints (api.moonshot.cn/anthropic,
# api.kimi.com/coding) accept ``thinking.type="adaptive"`` +
# ``output_config.effort``, and the replay-validation 400s that
# originally motivated dropping the parameter (#13848) no longer
# occur. (Kimi on chat_completions enables thinking via extra_body
# in the ChatCompletionsTransport — see #13503.)
#
# On 4.7+ the `thinking.display` field defaults to "omitted", which
# silently hides reasoning text that Hermes surfaces in its CLI. We
# request "summarized" so the reasoning blocks stay populated — matching
# 4.6 behavior and preserving the activity-feed UX during long tool runs.
_is_kimi_coding = _is_kimi_family_endpoint(base_url, model)
if reasoning_config and isinstance(reasoning_config, dict) and not _is_kimi_coding:
if reasoning_config and isinstance(reasoning_config, dict):
if reasoning_config.get("enabled") is not False and "haiku" not in model.lower():
effort = str(reasoning_config.get("effort", "medium")).lower()
budget = THINKING_BUDGET.get(effort, 8000)

View file

@ -0,0 +1 @@
chouqin

View file

@ -1603,18 +1603,34 @@ class TestBuildAnthropicKwargs:
assert _forbids_sampling_params(m) is False, m
def test_non_claude_anthropic_models_use_manual_path(self):
"""Non-Claude Anthropic-Messages models (minimax, qwen3, kimi) must not
be misclassified as adaptive by the default-to-modern rule."""
"""Non-Claude Anthropic-Messages models (minimax, qwen3, glm) must not
be misclassified as adaptive by the default-to-modern rule. Kimi is
the deliberate exception — see test_kimi_family_uses_adaptive_path."""
from agent.anthropic_adapter import (
_supports_adaptive_thinking,
_supports_xhigh_effort,
_forbids_sampling_params,
)
for m in ("minimax-m2", "qwen3-max", "moonshotai/kimi-k2.5", "glm-4.6"):
for m in ("minimax-m2", "qwen3-max", "glm-4.6"):
assert _supports_adaptive_thinking(m) is False, m
assert _supports_xhigh_effort(m) is False, m
assert _forbids_sampling_params(m) is False, m
def test_kimi_family_uses_adaptive_path(self):
"""Kimi / Moonshot models use adaptive thinking: their
Anthropic-compatible endpoints accept thinking.type="adaptive" +
output_config.effort including xhigh. Sampling params stay untouched
(the 4.7+ sampling ban is a Claude-only contract)."""
from agent.anthropic_adapter import (
_supports_adaptive_thinking,
_supports_xhigh_effort,
_forbids_sampling_params,
)
for m in ("moonshotai/kimi-k2.5", "kimi-0714-preview", "k2-thinking"):
assert _supports_adaptive_thinking(m) is True, m
assert _supports_xhigh_effort(m) is True, m
assert _forbids_sampling_params(m) is False, m
def test_fast_mode_omitted_for_unsupported_model(self):
"""fast_mode=True on Opus 4.7 must NOT inject speed=fast (API 400s)."""
kwargs = build_anthropic_kwargs(

View file

@ -1,22 +1,20 @@
"""Regression guard: don't send Anthropic ``thinking`` to Kimi's /coding endpoint.
"""Kimi / Moonshot thinking behavior on the Anthropic-Messages wire.
Kimi's ``api.kimi.com/coding`` endpoint speaks the Anthropic Messages protocol
but has its own thinking semantics. When ``thinking.enabled`` is present in
the request, Kimi validates the message history and requires every prior
assistant tool-call message to carry OpenAI-style ``reasoning_content``.
Contract (changed from the original #13848 mitigation):
The Anthropic path never populates that field, and
``convert_messages_to_anthropic`` strips Anthropic thinking blocks on
third-party endpoints — so after one turn with tool calls the next request
fails with HTTP 400::
- Kimi-family endpoints receive ``thinking`` in **adaptive** form
(``thinking.type="adaptive"`` + ``output_config.effort``) — never manual
``budget_tokens``. Their Anthropic-compatible endpoints
(``api.moonshot.cn/anthropic``, ``api.kimi.com/coding``) accept the
field set, and the replay-validation 400s that originally motivated
dropping the parameter (#13848) no longer occur.
thinking is enabled but reasoning_content is missing in assistant
tool call message at index N
- ``convert_messages_to_anthropic`` still preserves unsigned
reasoning_content-derived thinking blocks on replay for this family, so
multi-turn tool-call history round-trips.
Kimi on the chat_completions route handles ``thinking`` via ``extra_body`` in
``ChatCompletionsTransport`` (#13503). On the Anthropic route the right
thing to do is drop the parameter entirely and let Kimi drive reasoning
server-side.
Kimi on the chat_completions route handles ``thinking`` via ``extra_body``
in ``ChatCompletionsTransport`` (#13503).
"""
from __future__ import annotations
@ -24,36 +22,10 @@ from __future__ import annotations
import pytest
class TestKimiCodingSkipsAnthropicThinking:
"""build_anthropic_kwargs must not inject ``thinking`` for Kimi /coding."""
class TestKimiCodingAnthropicThinking:
"""Kimi-family thinking on the Anthropic wire (incl. /coding)."""
@pytest.mark.parametrize(
"base_url",
[
"https://api.kimi.com/coding",
"https://api.kimi.com/coding/v1",
"https://api.kimi.com/coding/anthropic",
"https://api.kimi.com/coding/",
],
)
def test_kimi_coding_endpoint_omits_thinking(self, base_url: str) -> None:
from agent.anthropic_adapter import build_anthropic_kwargs
kwargs = build_anthropic_kwargs(
model="kimi-k2.5",
messages=[{"role": "user", "content": "hello"}],
tools=None,
max_tokens=4096,
reasoning_config={"enabled": True, "effort": "medium"},
base_url=base_url,
)
assert "thinking" not in kwargs, (
"Anthropic thinking must not be sent to Kimi /coding — "
"endpoint requires reasoning_content on history we don't preserve."
)
assert "output_config" not in kwargs
def test_kimi_coding_with_explicit_disabled_also_omits(self) -> None:
def test_kimi_coding_with_explicit_disabled_omits_thinking(self) -> None:
from agent.anthropic_adapter import build_anthropic_kwargs
kwargs = build_anthropic_kwargs(
@ -94,48 +66,29 @@ class TestKimiCodingSkipsAnthropicThinking:
)
assert "thinking" in kwargs
def test_kimi_root_endpoint_via_anthropic_transport_omits_thinking(self) -> None:
"""Plain ``api.kimi.com`` hit via the Anthropic transport also omits thinking.
Auto-detection routes ``api.kimi.com/v1`` to ``chat_completions`` by
default, but users can explicitly configure
``api_mode: anthropic_messages`` against any Kimi host. The upstream
validation (reasoning_content required on replayed tool-call
messages) is the same regardless of URL path, so the thinking
suppression must apply to every Kimi host, not just ``/coding``.
See #17057.
"""
from agent.anthropic_adapter import build_anthropic_kwargs
class TestKimiFamilyGetsAdaptiveThinking:
"""Kimi-family endpoints get adaptive thinking + output_config.effort."""
kwargs = build_anthropic_kwargs(
model="kimi-k2.5",
messages=[{"role": "user", "content": "hello"}],
tools=None,
max_tokens=4096,
reasoning_config={"enabled": True, "effort": "medium"},
base_url="https://api.kimi.com/v1",
)
assert "thinking" not in kwargs
# ── #17057: custom / proxied Kimi-compatible endpoints ──────────
@pytest.mark.parametrize(
"base_url,model",
[
# Custom host with Kimi-family model — the reporter's case
("http://my-kimi-proxy.internal", "kimi-2.6"),
("https://llm.example.com/anthropic", "kimi-k2.5"),
("https://llm.example.com/anthropic", "moonshot-v1-8k"),
("https://llm.example.com/anthropic", "kimi_thinking"),
("https://llm.example.com/anthropic", "moonshotai/kimi-k2.5"),
# Official Moonshot host (previously uncovered)
# Official Kimi / Moonshot hosts (all URL shapes)
("https://api.kimi.com/coding", "kimi-k2.5"),
("https://api.kimi.com/coding/v1", "kimi-k2.5"),
("https://api.kimi.com/coding/anthropic", "kimi-k2.5"),
("https://api.kimi.com/v1", "kimi-k2.5"),
("https://api.moonshot.ai/anthropic", "moonshot-v1-32k"),
("https://api.moonshot.cn/anthropic", "moonshot-v1-32k"),
("https://api.moonshot.cn/anthropic/v1", "kimi-0714-preview"),
# Custom / proxied hosts with a Kimi-family model (#17057)
("http://my-kimi-proxy.internal", "kimi-2.6"),
("https://llm.example.com/anthropic", "moonshotai/kimi-k2.5"),
],
)
def test_kimi_family_custom_endpoint_omits_thinking(
def test_kimi_family_endpoint_gets_adaptive_thinking(
self, base_url: str, model: str
) -> None:
"""Custom / proxied Kimi endpoints must also strip Anthropic thinking."""
from agent.anthropic_adapter import build_anthropic_kwargs
kwargs = build_anthropic_kwargs(
@ -143,21 +96,65 @@ class TestKimiCodingSkipsAnthropicThinking:
messages=[{"role": "user", "content": "hello"}],
tools=None,
max_tokens=4096,
reasoning_config={"enabled": True, "effort": "medium"},
reasoning_config={"enabled": True, "effort": "high"},
base_url=base_url,
)
assert "thinking" not in kwargs, (
f"Kimi-family endpoint ({base_url}, {model}) must not receive "
f"Anthropic thinking — upstream validates reasoning_content on "
f"replayed tool-call history we don't preserve."
assert kwargs.get("thinking", {}).get("type") == "adaptive", (
f"Kimi-family endpoint ({base_url}, {model}) must receive "
f"adaptive thinking, got {kwargs.get('thinking')!r}"
)
assert "budget_tokens" not in kwargs["thinking"]
assert kwargs["output_config"] == {"effort": "high"}
# Adaptive mode must not force temperature or inflate max_tokens
# (those are manual-budget-mode side effects).
assert "temperature" not in kwargs
assert kwargs["max_tokens"] == 4096
@pytest.mark.parametrize(
"hermes_effort,wire_effort",
[
("minimal", "low"),
("low", "low"),
("medium", "medium"),
("high", "high"),
("xhigh", "xhigh"),
("max", "max"),
("ultra", "max"),
],
)
def test_kimi_effort_mapping(self, hermes_effort: str, wire_effort: str) -> None:
from agent.anthropic_adapter import build_anthropic_kwargs
kwargs = build_anthropic_kwargs(
model="kimi-0714-preview",
messages=[{"role": "user", "content": "hello"}],
tools=None,
max_tokens=4096,
reasoning_config={"enabled": True, "effort": hermes_effort},
base_url="https://api.moonshot.cn/anthropic/v1",
)
assert kwargs["thinking"] == {"type": "adaptive", "display": "summarized"}
assert kwargs["output_config"] == {"effort": wire_effort}
def test_kimi_thinking_disabled_omits_parameter(self) -> None:
from agent.anthropic_adapter import build_anthropic_kwargs
kwargs = build_anthropic_kwargs(
model="kimi-0714-preview",
messages=[{"role": "user", "content": "hello"}],
tools=None,
max_tokens=4096,
reasoning_config={"enabled": False},
base_url="https://api.moonshot.cn/anthropic/v1",
)
assert "thinking" not in kwargs
assert "output_config" not in kwargs
def test_custom_endpoint_non_kimi_model_keeps_thinking(self) -> None:
"""Custom endpoint with a non-Kimi model must keep thinking intact.
Guards against over-broad model-family matching — only model names
starting with a Kimi/Moonshot prefix should trigger suppression.
starting with a Kimi/Moonshot prefix should route to adaptive.
"""
from agent.anthropic_adapter import build_anthropic_kwargs