Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(providers): preserve on_payload in legacy Responses; clamp Anthropic budget

xf gong36c27954a859
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index 7bdbdcc..c714671 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -206,6 +206,20 @@ class AnthropicProvider(BaseProvider):
budget = thinking_block.get("budget_tokens", 0) or 0
kwargs["max_tokens"] = min(model.max_tokens + budget, model.context_window)
+ # If context_window clipped max_tokens such that the budget no
+ # longer fits, reduce the budget in place. Anthropic rejects when
+ # budget_tokens >= max_tokens; reserve at least 1024 output tokens
+ # to mirror adjust_max_tokens_for_thinking's legacy policy.
+ min_output_tokens = 1024
+ if budget > 0 and kwargs["max_tokens"] - budget < min_output_tokens:
+ new_budget = max(0, kwargs["max_tokens"] - min_output_tokens)
+ if isinstance(thinking_block, dict):
+ if new_budget > 0:
+ thinking_block["budget_tokens"] = new_budget
+ else:
+ # Budget reduced to 0 — disable thinking entirely.
+ kwargs["thinking"] = {"type": "disabled"}
+
async def _produce() -> None:
body: dict | None = None
exc: BaseException | None = None
diff --git a/cubepi/providers/openai_responses.py b/cubepi/providers/openai_responses.py
index c20a348..49e938a 100644
--- a/cubepi/providers/openai_responses.py
+++ b/cubepi/providers/openai_responses.py
@@ -157,21 +157,26 @@ class OpenAIResponsesProvider(BaseProvider):
)
else:
# Legacy path: configure reasoning effort via the inline map.
+ # Use setdefault to preserve on_payload-set fields, matching
+ # the capability path's ordering semantics.
effort = _THINKING_TO_EFFORT.get(opts.thinking)
if model.reasoning and effort is not None:
- kwargs["reasoning"] = {
- "effort": effort,
- "summary": "auto",
- }
- kwargs["include"] = ["reasoning.encrypted_content"]
+ kwargs.setdefault(
+ "reasoning",
+ {
+ "effort": effort,
+ "summary": "auto",
+ },
+ )
+ kwargs.setdefault("include", ["reasoning.encrypted_content"])
if model.max_tokens:
- kwargs["max_output_tokens"] = model.max_tokens
+ kwargs.setdefault("max_output_tokens", model.max_tokens)
# Forward temperature for non-reasoning models; reasoning
# models don't support temperature on the Responses API.
if not model.reasoning:
- kwargs["temperature"] = model.temperature
+ kwargs.setdefault("temperature", model.temperature)
await _fire_request_listeners(self._request_listeners, kwargs, model)
diff --git a/tests/providers/test_anthropic_capability.py b/tests/providers/test_anthropic_capability.py
index 9a5425c..e57c198 100644
--- a/tests/providers/test_anthropic_capability.py
+++ b/tests/providers/test_anthropic_capability.py
@@ -176,3 +176,82 @@ async def test_custom_high_budget_capability_bumps_max_tokens():
# max_tokens must be at least budget + something (model.max_tokens=8192,
# so min(8192+50000, 200000) = 58192). Anthropic rejects budget>=max_tokens.
assert payload["max_tokens"] >= 50000 + 1
+
+
+async def test_capability_clamps_budget_when_context_too_small() -> None:
+ """Regression: when context_window can't fit max_tokens + budget,
+ budget is reduced to fit. Anthropic rejects budget >= max_tokens."""
+ custom = CapabilityDescriptor(
+ reasoning_on_payload={"thinking": {"type": "enabled"}},
+ reasoning_level=ReasoningLevelSpec(
+ path="thinking.budget_tokens",
+ kind="int_budget",
+ level_budgets={"high": 16384},
+ ),
+ )
+ p = AnthropicProvider(api_key="x", capability=custom)
+ # Tight model: context_window only 10000, max_tokens 8192.
+ m = Model(
+ id="claude-tight-test",
+ provider="anthropic",
+ context_window=10000,
+ max_tokens=8192,
+ reasoning=True,
+ temperature=1.0,
+ )
+ captured: dict[str, Any] = {}
+
+ async def listener(kw: dict[str, Any], model: Model) -> None:
+ captured.update(kw)
+
+ p._request_listeners.append(listener)
+
+ class _FakeStream:
+ response = None
+
+ async def __aenter__(self) -> "_FakeStream":
+ return self
+
+ async def __aexit__(self, *a: Any) -> bool:
+ return False
+
+ def __aiter__(self) -> Any:
+ async def gen() -> Any:
+ return
+ yield # pragma: no cover - generator marker
+
+ return gen()
+
+ async def get_final_message(self) -> Any:
+ from anthropic.types import Message
+
+ return Message.model_construct(
+ id="m_test",
+ model="claude-tight-test",
+ role="assistant",
+ content=[],
+ stop_reason="end_turn",
+ stop_sequence=None,
+ type="message",
+ usage={"input_tokens": 1, "output_tokens": 1},
+ )
+
+ def fake_stream(**kw: Any) -> _FakeStream:
+ return _FakeStream()
+
+ p._client.messages.stream = fake_stream # type: ignore[attr-defined]
+
+ s = await p.stream(
+ model=m,
+ messages=[UserMessage(content=[TextContent(text="hi")])],
+ options=StreamOptions(thinking="high"),
+ )
+ async for _ in s:
+ pass
+ await s.result()
+
+ # Either budget was reduced below max_tokens, or thinking was disabled.
+ thinking_block = captured.get("thinking", {})
+ if thinking_block.get("type") == "enabled":
+ assert thinking_block["budget_tokens"] < captured["max_tokens"]
diff --git a/tests/providers/test_openai_responses_capability.py b/tests/providers/test_openai_responses_capability.py
index 0a8bf37..09efbfc 100644
--- a/tests/providers/test_openai_responses_capability.py
+++ b/tests/providers/test_openai_responses_capability.py
@@ -267,3 +267,18 @@ async def test_capability_on_payload_overrides_max_output_tokens():
p, _model(), thinking="off", on_payload=set_max
)
assert payload["max_output_tokens"] == 1234
+
+
+async def test_legacy_no_capability_preserves_on_payload_max_output_tokens():
+ """Regression: when on_payload sets max_output_tokens, legacy path preserves it."""
+ p = OpenAIResponsesProvider(api_key="x") # legacy, no capability
+
+ async def set_max(kwargs, model):
+ kwargs["max_output_tokens"] = 999
+ return kwargs
+
+ payload = await _capture_payload_responses(
+ p, _model(), thinking="off", on_payload=set_max
+ )
+ assert payload["max_output_tokens"] == 999