Skip to main content

#!/usr/bin/env python3 """ Thinking Budget Calculator

Calculate optimal thinking budgets for Claude Opus 4.5 tasks. Estimates costs and recommends thinking tiers based on task analysis.

Usage: python thinking-budget-calculator.py "task description" python thinking-budget-calculator.py --tier DEEP --interleaved python thinking-budget-calculator.py --cost-table python thinking-budget-calculator.py --batch tasks.txt """

import argparse import json import sys from dataclasses import dataclass from enum import Enum from typing import Optional, List, Dict, Any

class ThinkingTier(Enum): """Thinking budget tiers for Claude Opus 4.5""" NONE = 0 QUICK = 1024 STANDARD = 4096 DEEP = 16000 EXTENDED = 32000 MAXIMUM = 64000

Cost per 1K thinking tokens

THINKING_COST_PER_1K = 0.005 # $5 per million

Accuracy improvement estimates (vs no thinking)

ACCURACY_IMPROVEMENTS = { ThinkingTier.NONE: 0, ThinkingTier.QUICK: 5, ThinkingTier.STANDARD: 10, ThinkingTier.DEEP: 15, ThinkingTier.EXTENDED: 18, ThinkingTier.MAXIMUM: 20, }

Task type to complexity mapping

TASK_COMPLEXITY = { "format": 0.1, "extract": 0.2, "classify": 0.3, "generate": 0.4, "analyze": 0.5, "debug": 0.6, "design": 0.7, "research": 0.8, "architect": 0.9, }

@dataclass class ThinkingEstimate: """Result of thinking budget estimation""" tier: ThinkingTier budget_tokens: int estimated_cost: float accuracy_improvement: int interleaved_recommended: bool rationale: str

def estimate_complexity(task_description: str) -> float: """Estimate task complexity from description (0.0-1.0)""" task_lower = task_description.lower()

# Check for complexity indicators
complexity = 0.5 # Base complexity

# High complexity indicators
high_indicators = [
"debug", "investigate", "research", "analyze", "design",
"architect", "complex", "difficult", "comprehensive",
"multi-step", "autonomous", "long-running"
]
for indicator in high_indicators:
if indicator in task_lower:
complexity += 0.1

# Low complexity indicators
low_indicators = [
"simple", "format", "extract", "list", "convert",
"rename", "quick", "basic"
]
for indicator in low_indicators:
if indicator in task_lower:
complexity -= 0.1

# Tool indicators (suggest interleaved thinking)
tool_indicators = ["file", "search", "read", "write", "api", "database"]
tool_count = sum(1 for ind in tool_indicators if ind in task_lower)

return min(max(complexity, 0.0), 1.0), tool_count

def select_tier(complexity: float) -> ThinkingTier: """Select appropriate tier based on complexity""" if complexity < 0.2: return ThinkingTier.NONE elif complexity < 0.35: return ThinkingTier.QUICK elif complexity < 0.5: return ThinkingTier.STANDARD elif complexity < 0.7: return ThinkingTier.DEEP elif complexity < 0.85: return ThinkingTier.EXTENDED else: return ThinkingTier.MAXIMUM

def calculate_cost(tier: ThinkingTier) -> float: """Calculate cost in dollars for thinking tier""" return (tier.value / 1000) * THINKING_COST_PER_1K

def estimate_thinking_budget(task_description: str) -> ThinkingEstimate: """Estimate optimal thinking budget for a task""" complexity, tool_count = estimate_complexity(task_description) tier = select_tier(complexity)

return ThinkingEstimate(
tier=tier,
budget_tokens=tier.value,
estimated_cost=calculate_cost(tier),
accuracy_improvement=ACCURACY_IMPROVEMENTS[tier],
interleaved_recommended=tool_count > 1,
rationale=f"Complexity {complexity:.2f}, {tool_count} tool indicators"
)

def get_api_config( tier: ThinkingTier, interleaved: bool = False ) -> Dict[str, Any]: """Generate API configuration for given tier""" config = { "model": "claude-opus-4-5-20251101", "max_tokens": min(tier.value * 2, 32000), }

if tier != ThinkingTier.NONE:
config["thinking"] = {
"type": "enabled",
"budget_tokens": tier.value
}

if interleaved:
config["betas"] = ["interleaved-thinking-2025-05-14"]

return config

def print_cost_table(): """Print thinking tier cost table""" print("\nThinking Budget Cost Table") print("=" * 60) print(f"{'Tier':<12} {'Budget':>8} {'Cost':>10} {'Accuracy':>10}") print("-" * 60)

for tier in ThinkingTier:
cost = calculate_cost(tier)
accuracy = ACCURACY_IMPROVEMENTS[tier]
print(f"{tier.name:<12} {tier.value:>8} ${cost:>9.3f} +{accuracy:>8}%")

print("-" * 60)
print("Cost based on $5/million thinking tokens")
print("Accuracy improvement vs no thinking (approximate)")

def process_batch(filepath: str) -> List[ThinkingEstimate]: """Process batch of tasks from file""" results = [] with open(filepath, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#'): estimate = estimate_thinking_budget(line) results.append((line, estimate))

return results

def main(): parser = argparse.ArgumentParser( description="Calculate thinking budgets for Opus 4.5" ) parser.add_argument( "task", nargs="?", help="Task description to analyze" ) parser.add_argument( "--tier", choices=[t.name for t in ThinkingTier], help="Specify tier directly" ) parser.add_argument( "--interleaved", action="store_true", help="Include interleaved thinking config" ) parser.add_argument( "--api-config", action="store_true", help="Output API configuration JSON" ) parser.add_argument( "--cost-table", action="store_true", help="Show cost table for all tiers" ) parser.add_argument( "--batch", type=str, help="Process batch of tasks from file" ) parser.add_argument( "--json", action="store_true", help="Output as JSON" )

args = parser.parse_args()

# Show cost table
if args.cost_table:
print_cost_table()
return

# Process batch
if args.batch:
results = process_batch(args.batch)
print(f"\nBatch Analysis: {len(results)} tasks")
print("=" * 70)
for task, estimate in results:
print(f"\nTask: {task[:50]}...")
print(f" Tier: {estimate.tier.name} ({estimate.budget_tokens} tokens)")
print(f" Cost: ${estimate.estimated_cost:.3f}")
print(f" Interleaved: {'Yes' if estimate.interleaved_recommended else 'No'}")
return

# Direct tier specification
if args.tier:
tier = ThinkingTier[args.tier]
if args.api_config:
config = get_api_config(tier, args.interleaved)
print(json.dumps(config, indent=2))
else:
print(f"\nTier: {tier.name}")
print(f"Budget: {tier.value} tokens")
print(f"Cost: ${calculate_cost(tier):.3f}")
print(f"Accuracy: +{ACCURACY_IMPROVEMENTS[tier]}%")
return

# Task analysis
if args.task:
estimate = estimate_thinking_budget(args.task)

if args.json:
output = {
"tier": estimate.tier.name,
"budget_tokens": estimate.budget_tokens,
"estimated_cost": estimate.estimated_cost,
"accuracy_improvement": estimate.accuracy_improvement,
"interleaved_recommended": estimate.interleaved_recommended,
"rationale": estimate.rationale
}
if args.api_config:
output["api_config"] = get_api_config(
estimate.tier,
estimate.interleaved_recommended
)
print(json.dumps(output, indent=2))
else:
print(f"\nTask Analysis")
print("=" * 50)
print(f"Task: {args.task}")
print(f"\nRecommendation")
print("-" * 50)
print(f"Tier: {estimate.tier.name}")
print(f"Budget: {estimate.budget_tokens} tokens")
print(f"Est. Cost: ${estimate.estimated_cost:.3f}")
print(f"Accuracy Boost: +{estimate.accuracy_improvement}%")
print(f"Interleaved: {'Yes' if estimate.interleaved_recommended else 'No'}")
print(f"Rationale: {estimate.rationale}")

if args.api_config:
print(f"\nAPI Configuration:")
config = get_api_config(
estimate.tier,
estimate.interleaved_recommended
)
print(json.dumps(config, indent=2))
return

# No input - show help
parser.print_help()

if name == "main": main()