Reduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Reduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
Comprehensive toolkit for reducing token usage and API costs in OpenClaw deployments. Combines smart model routing, optimized heartbeat intervals, usage tracking, and multi-provider strategies.
Quick Start
Immediate actions (no config changes needed):
Generate optimized AGENTS.md (BIGGEST WIN!):
python3 scripts/context_optimizer.py generate-agents
# Creates AGENTS.md.optimized — review and replace your current AGENTS.md
Check what context you ACTUALLY need:
python3 scripts/context_optimizer.py recommend "hi, how are you?"# Shows: Only 2 files needed (not 50+!)
python3 scripts/model_router.py "thanks!"# Single-provider Anthropic setup: Use Sonnet, not Opus# Multi-provider setup (OpenRouter/Together): Use Haiku for max savings
Check current token budget:
python3 scripts/token_tracker.py check
Expected savings: 50-80% reduction in token costs for typical workloads (context optimization is the biggest factor!).
Core Capabilities
1. Context Optimization (NEW!)
Biggest token saver — Only load files you actually need, not everything upfront.
Problem: Default OpenClaw loads ALL context files every session:
SOUL.md, AGENTS.md, USER.md, TOOLS.md, MEMORY.md
docs/**/*.md (hundreds of files)
memory/2026-*.md (daily logs)
Total: Often 50K+ tokens before user even speaks!
Solution: Lazy loading based on prompt complexity.
Integration pattern:
Before loading context for a new session:
from context_optimizer import recommend_context_bundle
user_prompt = "thanks for your help"
recommendation = recommend_context_bundle(user_prompt)
if recommendation["context_level"] == "minimal":
# Load only SOUL.md + IDENTITY.md# Skip everything else# Save ~80% tokens!
Generate optimized AGENTS.md:
context_optimizer.py generate-agents
# Creates AGENTS.md.optimized with lazy loading instructions# Review and replace your current AGENTS.md
Expected savings: 50-80% reduction in context tokens.
2. Smart Model Routing (ENHANCED!)
Automatically classify tasks and route to appropriate model tiers.
NEW: Communication pattern enforcement — Never waste Opus tokens on "hi" or "thanks"!
Document parsing: "parse CSV", "extract data from log", "read JSON"
Log scanning: "scan error logs", "process logs"
Integration pattern:
from model_router import route_task
user_prompt = "show me the config"
routing = route_task(user_prompt)
if routing["should_switch"]:
# Use routing["recommended_model"]# Save routing["cost_savings_percent"]
Customization:
Edit ROUTING_RULES or COMMUNICATION_PATTERNS in scripts/model_router.py to adjust patterns and keywords.
3. Heartbeat Optimization
Reduce API calls from heartbeat polling with smart interval tracking:
Setup:
# Copy template to workspacecp assets/HEARTBEAT.template.md ~/.openclaw/workspace/HEARTBEAT.md
# Plan which checks should run
python3 scripts/heartbeat_optimizer.py plan
Commands:
# Check if specific type should run now
heartbeat_optimizer.py check email
heartbeat_optimizer.py check calendar
# Record that a check was performed
heartbeat_optimizer.py record email
# Update check interval (seconds)
heartbeat_optimizer.py interval email 7200 # 2 hours# Reset state
heartbeat_optimizer.py reset
How it works:
Tracks last check time for each type (email, calendar, weather, etc.)
Enforces minimum intervals before re-checking
Respects quiet hours (23:00-08:00) — skips all checks
Returns HEARTBEAT_OK when nothing needs attention (saves tokens)
Default intervals:
Email: 60 minutes
Calendar: 2 hours
Weather: 4 hours
Social: 2 hours
Monitoring: 30 minutes
Integration in HEARTBEAT.md:
## Email Check
Run only if: `heartbeat_optimizer.py check email` → `should_check: true`
After checking: `heartbeat_optimizer.py record email`
Expected savings: 50% reduction in heartbeat API calls.
Model enforcement: Heartbeat should ALWAYS use Haiku — see updated HEARTBEAT.template.md for model override instructions.
4. Cronjob Optimization (NEW!)
Problem: Cronjobs often default to expensive models (Sonnet/Opus) even for routine tasks.
Solution: Always specify Haiku for 90% of scheduled tasks.
See:assets/cronjob-model-guide.md for comprehensive guide with examples.
OpenClaw 2026.2.15 added built-in commands that complement this skill's Python scripts. Use these first for quick diagnostics before reaching for the scripts.
Context breakdown
/context list → token count per injected file (shows exactly what's eating your prompt)
/context detail → full breakdown including tools, skills, and system prompt sections
Use before applying bootstrap_size_limits — see which files are oversized, then set bootstrapMaxChars accordingly.
Per-response usage tracking
/usage tokens → append token count to every reply
/usage full → append tokens + cost estimate to every reply
/usage cost → show cumulative cost summary from session logs
/usage off → disable usage footer
/status → model, context %, last response tokens, estimated cost
Cache TTL Heartbeat Alignment (NEW in v1.4.0)
The problem: Anthropic charges ~3.75x more for cache writes than cache reads. If your agent goes idle and the 1h cache TTL expires, the next request re-writes the entire prompt cache — expensive.
The fix: Set heartbeat interval to 55min (just under the 1h TTL). The heartbeat keeps the cache warm, so every subsequent request pays cache-read rates instead.
# Get optimal interval for your cache TTL
python3 scripts/heartbeat_optimizer.py cache-ttl
# → recommended_interval: 55min (3300s)# → explanation: keeps 1h Anthropic cache warm# Custom TTL (e.g., if you've configured 2h cache)
python3 scripts/heartbeat_optimizer.py cache-ttl 7200
# → recommended_interval: 115min
Who benefits: Anthropic API key users only. OAuth profiles already default to 1h heartbeat (OpenClaw smart default). API key profiles default to 30min — bumping to 55min is both cheaper (fewer calls) and cache-warm.
Deployment Patterns
For Personal Use
Install optimized HEARTBEAT.md
Run budget checks before expensive operations
Manually route complex tasks to Opus only when needed
Expected savings: 20-30%
For Managed Hosting (xCloud, etc.)
Default all agents to Haiku
Route user interactions to Sonnet
Reserve Opus for explicitly complex requests
Use Gemini Flash for background operations
Implement daily budget caps per customer
Expected savings: 40-60%
For High-Volume Deployments
Use multi-provider fallback (OpenRouter + Together.ai)
Batch heartbeat checks (every 2-4 hours, not 30 min)
Expected savings: 70-90%
Integration Examples
Workflow: Smart Task Handling
# 1. User sends message
user_msg="debug this error in the logs"# 2. Route to appropriate model
routing=$(python3 scripts/model_router.py "$user_msg")
model=$(echo$routing | jq -r .recommended_model)
# 3. Check budget before proceeding
budget=$(python3 scripts/token_tracker.py check)
status=$(echo$budget | jq -r .status)
if [ "$status" = "exceeded" ]; then# Use cheapest model regardless of routing
model="anthropic/claude-haiku-4"fi# 4. Process with selected model# (OpenClaw handles this via config or override)
Workflow: Optimized Heartbeat
## HEARTBEAT.md# Plan what to check
result=$(python3 scripts/heartbeat_optimizer.py plan)
should_run=$(echo $result | jq -r .should_run)
if [ "$should_run" = "false" ]; then
echo "HEARTBEAT_OK"
exit 0
fi
# Run only planned checks
planned=$(echo $result | jq -r '.planned[].type')
for check in $planned; do
case $check in
email) check_email ;;
calendar) check_calendar ;;
esac
python3 scripts/heartbeat_optimizer.py record $check
done
Troubleshooting
Issue: Scripts fail with "module not found"
Fix: Ensure Python 3.7+ is installed. Scripts use only stdlib.
Issue: State files not persisting
Fix: Check that ~/.openclaw/workspace/memory/ directory exists and is writable.
Issue: Budget tracking shows $0.00
Fix:token_tracker.py needs integration with OpenClaw's session_status tool. Currently tracks manually recorded usage.
Issue: Routing suggests wrong model tier
Fix: Customize ROUTING_RULES in model_router.py for your specific patterns.