CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat: dynamic thinking budget adjustment for max_tokens (#9)
Chrisdd8d05638cb7
diff --git a/cubepi/__init__.py b/cubepi/__init__.pyindex 971a8b1..c9507dd 100644--- a/cubepi/__init__.py+++ b/cubepi/__init__.py@@ -17,11 +17,13 @@ from cubepi.providers import (Provider,StreamEvent,TextContent,+ ThinkingBudgets,ThinkingLevel,ToolCall,ToolDefinition,ToolResultMessage,UserMessage,+ adjust_max_tokens_for_thinking,)__all__ = [@@ -37,11 +39,13 @@ __all__ = ["Provider","StreamEvent","TextContent",+ "ThinkingBudgets","ThinkingLevel","ToolCall","ToolDefinition","ToolResultMessage","UserMessage",+ "adjust_max_tokens_for_thinking","compose_middleware","run_agent_loop","run_agent_loop_continue",diff --git a/cubepi/providers/__init__.py b/cubepi/providers/__init__.pyindex e64e463..2cefe8b 100644--- a/cubepi/providers/__init__.py+++ b/cubepi/providers/__init__.py@@ -9,6 +9,7 @@ from cubepi.providers.base import (Provider,StreamEvent,TextContent,+ ThinkingBudgets,ThinkingContent,ThinkingLevel,ToolCall,@@ -16,6 +17,7 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ adjust_max_tokens_for_thinking,)from cubepi.providers.faux import (FauxProvider,@@ -51,6 +53,7 @@ __all__ = ["Provider","StreamEvent","TextContent",+ "ThinkingBudgets","ThinkingContent","ThinkingLevel","ToolCall",@@ -58,6 +61,7 @@ __all__ = ["ToolResultMessage","Usage","UserMessage",+ "adjust_max_tokens_for_thinking","faux_assistant_message","faux_text","faux_thinking",diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.pyindex ef1d055..11a1d0e 100644--- a/cubepi/providers/anthropic.py+++ b/cubepi/providers/anthropic.py@@ -12,6 +12,7 @@ from cubepi.providers.base import (Model,StreamEvent,TextContent,+ ThinkingBudgets,ThinkingContent,ThinkingLevel,ToolCall,@@ -19,6 +20,7 @@ from cubepi.providers.base import (ToolResultMessage,Usage,UserMessage,+ adjust_max_tokens_for_thinking,)@@ -36,24 +38,34 @@ class AnthropicProvider:system_prompt: str = "",tools: list[ToolDefinition] | None = None,thinking: ThinkingLevel = "off",+ thinking_budgets: ThinkingBudgets | None = None,signal: asyncio.Event | None = None,) -> MessageStream:ms = MessageStream()api_messages = [self._convert_message(m) for m in messages]++ # Adjust max_tokens to accommodate the thinking budget+ max_tokens, thinking_budget = adjust_max_tokens_for_thinking(+ base_max_tokens=model.max_tokens,+ model_max_tokens=model.context_window,+ reasoning_level=thinking,+ custom_budgets=thinking_budgets,+ )+kwargs: dict[str, Any] = {"model": model.id,"messages": api_messages,- "max_tokens": model.max_tokens,+ "max_tokens": max_tokens,}if system_prompt:kwargs["system"] = system_promptif tools:kwargs["tools"] = [self._convert_tool(t) for t in tools]- if thinking != "off":+ if thinking != "off" and thinking_budget > 0:kwargs["thinking"] = {"type": "enabled",- "budget_tokens": self._thinking_budget(thinking, model),+ "budget_tokens": thinking_budget,}async def _produce() -> None:@@ -171,17 +183,6 @@ class AnthropicProvider:"input_schema": td.parameters,}- @staticmethod- def _thinking_budget(level: ThinkingLevel, model: Model) -> int:- budgets = {- "minimal": 1024,- "low": 2048,- "medium": 4096,- "high": 8192,- "xhigh": 16384,- }- return budgets.get(level, 4096)-def _handle_event(self, event: Any, partial: AssistantMessage, ms: MessageStream) -> None:diff --git a/cubepi/providers/base.py b/cubepi/providers/base.pyindex 0f5b024..52195e7 100644--- a/cubepi/providers/base.py+++ b/cubepi/providers/base.py@@ -8,6 +8,49 @@ from pydantic import BaseModelThinkingLevel = Literal["off", "minimal", "low", "medium", "high", "xhigh"]+class ThinkingBudgets(BaseModel):+ """Token budgets for each thinking level."""++ minimal: int = 1024+ low: int = 2048+ medium: int = 8192+ high: int = 16384+++def adjust_max_tokens_for_thinking(+ base_max_tokens: int,+ model_max_tokens: int,+ reasoning_level: ThinkingLevel,+ custom_budgets: ThinkingBudgets | None = None,+) -> tuple[int, int]:+ """Adjust max_tokens to reserve space for a thinking budget.++ Given a base max_tokens (the desired output capacity), increases it to+ accommodate the thinking budget while respecting the model's hard cap.+ If the model cap is too small to fit both, the thinking budget is reduced+ to leave at least ``min_output_tokens`` (1024) for output.++ Returns:+ A ``(max_tokens, thinking_budget)`` tuple.+ """+ if reasoning_level == "off":+ return base_max_tokens, 0++ budgets = custom_budgets or ThinkingBudgets()+ min_output_tokens = 1024++ # Clamp "xhigh" down to "high"+ level = "high" if reasoning_level == "xhigh" else reasoning_level+ thinking_budget: int = getattr(budgets, level)++ max_tokens = min(base_max_tokens + thinking_budget, model_max_tokens)++ if max_tokens <= thinking_budget:+ thinking_budget = max(0, max_tokens - min_output_tokens)++ return max_tokens, thinking_budget++class ModelCost(BaseModel):input: float = 0output: float = 0@@ -150,5 +193,6 @@ class Provider(Protocol):system_prompt: str = "",tools: list[ToolDefinition] | None = None,thinking: ThinkingLevel = "off",+ thinking_budgets: ThinkingBudgets | None = None,signal: asyncio.Event | None = None,) -> MessageStream: ...diff --git a/cubepi/providers/faux.py b/cubepi/providers/faux.pyindex 433f9e2..2cf691c 100644--- a/cubepi/providers/faux.py+++ b/cubepi/providers/faux.py@@ -13,6 +13,7 @@ from cubepi.providers.base import (Model,StreamEvent,TextContent,+ ThinkingBudgets,ThinkingContent,ThinkingLevel,ToolCall,@@ -119,6 +120,7 @@ class FauxProvider:system_prompt: str = "",tools: list[ToolDefinition] | None = None,thinking: ThinkingLevel = "off",+ thinking_budgets: ThinkingBudgets | None = None,signal: asyncio.Event | None = None,) -> MessageStream:ms = MessageStream()diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.pyindex 5794fd4..0645419 100644--- a/cubepi/providers/openai.py+++ b/cubepi/providers/openai.py@@ -14,6 +14,7 @@ from cubepi.providers.base import (Model,StreamEvent,TextContent,+ ThinkingBudgets,ThinkingLevel,ToolCall,ToolDefinition,@@ -44,6 +45,7 @@ class OpenAIProvider:system_prompt: str = "",tools: list[ToolDefinition] | None = None,thinking: ThinkingLevel = "off",+ thinking_budgets: ThinkingBudgets | None = None,signal: asyncio.Event | None = None,) -> MessageStream:ms = MessageStream()diff --git a/tests/providers/test_thinking_budgets.py b/tests/providers/test_thinking_budgets.pynew file mode 100644index 0000000..37be369--- /dev/null+++ b/tests/providers/test_thinking_budgets.py@@ -0,0 +1,150 @@+from cubepi.providers.base import ThinkingBudgets, adjust_max_tokens_for_thinking+++class TestThinkingBudgets:+ def test_defaults(self):+ b = ThinkingBudgets()+ assert b.minimal == 1024+ assert b.low == 2048+ assert b.medium == 8192+ assert b.high == 16384++ def test_custom_values(self):+ b = ThinkingBudgets(minimal=512, low=1024, medium=4096, high=8192)+ assert b.minimal == 512+ assert b.high == 8192+++class TestAdjustMaxTokensForThinking:+ def test_off_returns_base_unchanged(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="off",+ )+ assert max_tokens == 8192+ assert budget == 0++ def test_minimal_adds_1024(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="minimal",+ )+ assert budget == 1024+ assert max_tokens == 8192 + 1024++ def test_low_adds_2048(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="low",+ )+ assert budget == 2048+ assert max_tokens == 8192 + 2048++ def test_medium_adds_8192(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="medium",+ )+ assert budget == 8192+ assert max_tokens == 8192 + 8192++ def test_high_adds_16384(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="high",+ )+ assert budget == 16384+ assert max_tokens == 8192 + 16384++ def test_xhigh_clamps_to_high(self):+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="xhigh",+ )+ # xhigh should be clamped to high (16384)+ assert budget == 16384+ assert max_tokens == 8192 + 16384++ def test_model_cap_limits_max_tokens(self):+ # Model only allows 10000 total, but base + budget = 8192 + 8192 = 16384+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=10000,+ reasoning_level="medium",+ )+ assert max_tokens == 10000+ assert budget == 8192 # budget still fits (10000 > 8192)++ def test_budget_reduced_when_model_too_small(self):+ # Model allows only 2000 total, budget would be 8192 (medium)+ # Since max_tokens(2000) <= budget(8192), budget = max(0, 2000 - 1024) = 976+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=2000,+ reasoning_level="medium",+ )+ assert max_tokens == 2000+ assert budget == 976++ def test_budget_zero_when_model_extremely_small(self):+ # Model allows only 500 total, budget would be 8192+ # max_tokens = min(8192 + 8192, 500) = 500+ # 500 <= 8192 so budget = max(0, 500 - 1024) = 0+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=500,+ reasoning_level="medium",+ )+ assert max_tokens == 500+ assert budget == 0++ def test_custom_budgets_override_defaults(self):+ custom = ThinkingBudgets(minimal=256, low=512, medium=2048, high=4096)+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="medium",+ custom_budgets=custom,+ )+ assert budget == 2048+ assert max_tokens == 8192 + 2048++ def test_custom_budgets_xhigh_uses_custom_high(self):+ custom = ThinkingBudgets(high=4096)+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=128_000,+ reasoning_level="xhigh",+ custom_budgets=custom,+ )+ assert budget == 4096+ assert max_tokens == 8192 + 4096++ def test_exact_model_cap_equals_budget(self):+ # Edge case: model cap exactly equals the budget+ # max_tokens = min(8192 + 1024, 1024) = 1024+ # 1024 <= 1024 so budget = max(0, 1024 - 1024) = 0+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=1024,+ reasoning_level="minimal",+ )+ assert max_tokens == 1024+ assert budget == 0++ def test_model_cap_just_above_budget(self):+ # max_tokens = min(8192 + 1024, 1025) = 1025+ # 1025 > 1024 so budget stays at 1024+ max_tokens, budget = adjust_max_tokens_for_thinking(+ base_max_tokens=8192,+ model_max_tokens=1025,+ reasoning_level="minimal",+ )+ assert max_tokens == 1025+ assert budget == 1024