This skill helps reduce your OpenClaw API costs by 70-97% through intelligent model routing, session management, and response efficiency.
New to this skill? Read
GUIDE.mdfor installation instructions, requirements, example outputs from every script, and common workflows.
CategoryFilesPurposeAgent instructionsSKILL.md (this file)13 chapters of cost optimization logicUser guideGUIDE.mdRequirements, installation, example outputs, workflowsReferencesreferences/ (2 files)Model pricing card, config templatesScriptsscripts/ (29 files)Audit, monitor, backup, health check, reportingPresetspresets/ (5 files)Ready-to-apply configs: solo-coder, writer, researcher, zero-budget, agency-teamMetadataVERSION, CHANGELOG.mdVersion tracking and update history
text
# Install
cd ~/.openclaw/workspace/skills/
unzip cost-optimizer.zip
chmod +x cost-optimizer/scripts/*.sh
# Audit current costs
bash cost-optimizer/scripts/cost-audit.sh
# Interactive setup
Tell your agent: /cost-setup
When this skill is first activated or user says "/cost-setup", walk through these steps. Ask permission at each step before making changes:
Step 1: Budget Target Ask: "What's your monthly budget target? Options: Ultra-low ($0-5/mo), Low ($5-30/mo), Medium ($30-100/mo), Flexible (no hard limit but minimize waste)" Save their answer to memory/cost-preferences.md
Step 2: Free Models Ask: "Want me to add free OpenRouter models to your config? These cost $0.00 per request and handle 60-80% of simple tasks well. I'll add: DeepSeek V3 Free, Llama 4 Scout Free, Qwen 3 Free, Gemma 3 Free, Mistral Small Free. Approve? (yes/no)" If yes: add the free models to config with aliases
Step 3: Default Model Ask: "Your current default model is [current model]. Want me to switch your default to MiniMax M2.5 ($0.04/request) or DeepSeek V3.2 ($0.04/request)? This alone saves 73-94% vs Opus/Sonnet. Options: minimax / deepseek / keep current" If they choose: update model.primary
Step 4: Heartbeat Optimization Ask: "Heartbeats keep your agent alive but cost money on expensive models. Want me to route heartbeats to a free model at 55-minute intervals? This saves $7-562/month depending on your current setup. Approve? (yes/no)" If yes: set heartbeat model to free, interval 55m
Step 5: Session Management Ask: "Want me to enable aggressive memory flush before compaction? This prevents context bloat and saves 10-30% on long sessions. Approve? (yes/no)" If yes: enable memoryFlush with threshold 3000
Step 6: Response Style Ask: "In cost-conscious mode, should I: (a) Always be concise to save tokens, (b) Be concise by default but go detailed when you ask, or (c) Keep my normal response style?" Save preference to memory/cost-preferences.md
After setup, confirm: "Cost optimizer configured. Here's your estimated monthly cost: ~$X based on [usage estimate]. Use /cost-status anytime to check, /cost-setup to reconfigure."
When this skill is active and user hasn't overridden with [name], suggest the cheapest adequate model for each task.
Every OpenClaw request sends approximately 140,000 tokens of fixed overhead (system prompt, tool schemas, context). This overhead is the dominant cost. What it costs depends entirely on which model processes it:
Model TierOverhead CostPer RequestMonthly (50 q/day)Free models$0.00$0.00$0.00Budget (MiniMax/DeepSeek)$0.04$0.04~$60Mid (Haiku)$0.14$0.15~$225Quality (Sonnet)$0.42$0.43~$645Premium (Opus)$0.70$0.71~$1,065
A simple question costs $0.71 on Opus and $0.00 on a free model. The answer quality for simple factual questions is nearly identical. Model selection is the single biggest cost lever.
These are your first choice for tasks that don't need premium quality:
AliasModelContextGood Fordeepseek-freeDeepSeek V3 Free164KBest free model overall. Coding, reasoning, general tasks.llama-freeLlama 4 Scout Free512KLargest context window. Research, long docs.qwen-freeQwen 3 235B Free40KMultilingual and translation tasks.mistral-freeMistral Small 3.1 Free96KQuick short answers. Classification.gemma-freeGemma 3 27B Free96KReliable fallback.
If one free model is rate-limited, try the next: deepseek-free, llama-free, qwen-free, mistral-free, gemma-free
AliasModelCost/reqGood FornanoGPT-5 Nano~$0.01Simplest tasks when free models are downflashliteGemini Flash-Lite~$0.01Cron jobs, heartbeatsdeepseekDeepSeek V3.2~$0.04Coding daily driverminimaxMiniMax M2.5~$0.04General daily driver (recommended default)kimiKimi K2.5~$0.07Long sessions — auto-caching drops to $0.02 after warmupglmGLM-5$0.14Complex architecture-level coding
AliasModelCost/reqGood ForhaikuClaude Haiku 4.5~$0.15Mid-tier quality worksonnetClaude Sonnet 4.6~$0.53Quality writing, code review, final polish
AliasModelCost/reqGood ForopusClaude Opus 4.6~$0.71Maximum reasoning powergpt5GPT-5~$0.44Complex multi-domain tasks
Use premium only when user explicitly requests or task genuinely requires it.
When this skill is active, use this decision process to suggest the best model for each task:
Simple tasks — try free first: Factual questions, brainstorming, lists, first drafts, explanations, summaries, simple code, formatting, translations, yes/no questions, code scaffolds Suggest: "I can handle this on [free model] at $0.00. Want me to proceed?" If user hasn't set a preference yet, ask the first time. After that, follow their preference from setup.
Standard work — use budget models: General questions needing reliable quality, coding tasks, analysis Use the configured default (minimax or deepseek at ~$0.04)
Long reasoning sessions: Multi-turn analysis, complex problem-solving Suggest kimi ($0.07 first request, ~$0.02 after due to auto-caching)
Complex coding: Systems architecture, difficult debugging Suggest glm ($0.14) — only when task is genuinely complex
Quality output for external sharing: Final versions of writing, thorough code reviews, research synthesis Suggest doing research/gathering on budget model first, then switching to sonnet ($0.53) for the final output only. Ask: "Draft complete. Want me to polish on Sonnet (~$0.53) or is this good enough?"
Premium reasoning: Never auto-select opus. Instead ask: "This seems to need deep reasoning. Want me to use Opus ($0.71/request) or try Sonnet first ($0.53)?"
User override: If user says /model [alias], use that model. No questions. Resume smart routing after /reset or /model auto.
When the user chose concise mode during setup, follow these guidelines to reduce output tokens:
Task TypeTarget LengthExampleYes/No questions1-2 sentencesDirect answer with brief reasonFactual lookups1-3 sentencesThe answer, sourced if relevantSimple Q&AShort paragraphAnswer first, brief contextExplanations2-3 paragraphsStructured, no paddingCode snippetsCode + 1-line commentNo narration unless askedFull functionsCode + minimal commentsExplain only tricky partsAnalysisStructured bulletsKey findings, not essays
Reducing average response from 800 tokens to 300 tokens saves:
Long sessions cost more because every old message gets re-sent with each new request on top of the 140K base overhead.
Session LengthExtra ContextExtra Cost per Request (MiniMax)Extra Cost per Request (Sonnet)5 exchanges2,500 tokens+$0.001+$0.00810 exchanges5,000 tokens+$0.002+$0.01520 exchanges15,000 tokens+$0.005+$0.04550 exchanges50,000 tokens+$0.015+$0.150100 exchanges~150,000 tokens+$0.045+$0.450
At 100 exchanges, every request costs roughly triple its base price.
Before every reset, provide a brief summary so nothing is lost:
"Session summary:
To slow context growth within a session:
For important facts that should persist across sessions:
Each tool call triggers a full model roundtrip with the entire context window. On MiniMax that costs ~$0.04+ per call. On Sonnet it costs ~$0.43+ per call.
Before making any tool call, consider:
Can I answer from existing knowledge? Many questions don't need a tool call. If you're 90%+ confident in the answer, provide it and offer to verify: "I believe X is the case. Want me to confirm with a lookup?"
Did I already retrieve this data? If the same or similar data was fetched earlier in the session, use the cached result instead of re-fetching.
Can I batch this with other calls? If multiple pieces of related data are needed, try to get them in fewer calls rather than one call per data point.
Will the user need follow-up data? If so, fetch slightly broader data now to avoid additional calls later.
Is there a lighter tool option? Use the simplest tool that gets the job done.
Raw tool output is often thousands of tokens. Always compress it:
Each subagent spawns a separate request that carries the full system prompt overhead.
ConfigurationBase Overhead Cost (MiniMax)Main agent only~$0.04Main + 1 subagent~$0.08Main + 2 subagents~$0.12Main + 4 subagents~$0.20
The ~140K base overhead per request is partially reducible. Small reductions compound significantly over hundreds of daily requests.
Unused tools (highest impact): Each tool schema adds approximately 200 tokens to every request. If you have 20 tools but only use 10, the other 10 waste ~2,000 tokens per request.
Instructions that belong in skills: Content in system.md loads on every single request. Skills only load when activated. If you have instructions that are only relevant sometimes (code review guidelines, writing style rules, specific workflows), moving them to skills reduces base overhead.
Verbose tool descriptions: Many tool descriptions are unnecessarily long. Compressing them saves tokens on every request. Before: "This tool searches the web using the Google Custom Search API and returns results in JSON format including titles, URLs, snippets, and metadata" After: "Web search. Returns title, URL, snippet per result." Savings: ~30 tokens per tool x number of verbose tools
Personality file trimming: If personality instructions are long (2000+ tokens), consider trimming to essentials. The personality is sent with every request.
If the user asks to optimize their system prompt, offer to:
Always ask permission before making any changes to system.md or tool configuration.
For complex tasks that involve multiple steps, using cheaper models for early phases and reserving expensive models for the final output saves significantly.
PhaseSuggested ModelCostWeb searches and data gatheringFree model or minimax$0.00-0.04 per callOrganizing and structuring dataFree model$0.00Writing the synthesisminimax$0.04Final polish (if user wants)sonnet$0.53
Total: $0.04-0.57 compared to doing everything on Sonnet: $2-4+
PhaseSuggested ModelCostScaffolding and boilerplateFree model$0.00Core logic implementationdeepseek or minimax$0.04Debugging and testingdeepseek or minimax$0.04Architecture review (if complex)glm$0.14
Total: $0.04-0.22 compared to doing everything on Sonnet: $1.50-2.50+
PhaseSuggested ModelCostOutline and structureFree model$0.00First draftminimax$0.04Editing and polish (if sharing externally)sonnet$0.53
Total: $0.04-0.57 compared to doing everything on Sonnet: $1-2+
After completing the draft/gathering phase, ask: "Draft complete on [current model]. Want me to polish this on Sonnet (~$0.53) or is this version good enough?"
Let the user decide whether the polish phase is worth the cost.
Prompt caching can dramatically reduce the effective cost of the 140K base overhead.
Anthropic models (Claude): The system prompt and tool schemas are automatically cached. Subsequent requests within the cache window pay only 10% of the normal input price for cached tokens. A heartbeat every 55 minutes keeps this cache warm.
Kimi K2.5 auto-caching: Kimi K2.5 has built-in context caching that drops repeat input costs from $0.50/M to $0.13/M — a 75% discount. This means:
Stay on one model within a session. Switching models invalidates the prompt cache. Every switch means re-paying full price for the 140K base overhead.
Cluster similar work together. Do all coding tasks, then all writing tasks, then all research. This keeps the same model cached throughout each cluster.
Don't re-fetch data. If you retrieved information from a tool, remember it. Re-fetching wastes both the tool call cost and the cache benefit.
For long reasoning sessions, use Kimi. Its auto-caching compounds — the longer you stay, the cheaper each request becomes.
The 55-minute heartbeat matters. It keeps the Anthropic prompt cache warm so your next real request gets the 90% discount on base overhead.
Heartbeats keep the agent session alive. If configured to use an expensive model, they silently drain budget 24/7:
During setup, this skill configures heartbeats to use a free model. If the user reports heartbeats still costing money (known bug in some versions), suggest the cron workaround: "Set up a cron job that pings every 55 minutes with an isolated session instead of using the built-in heartbeat system."
If the user tends to send many simple questions one at a time, suggest batching: "If you have several questions on this topic, listing them all in one message saves money — each separate message pays the full 140K overhead again."
After completing multi-step or expensive operations, briefly note the approximate cost: "Done. Used minimax for research + sonnet for synthesis. Estimated cost: ~$0.57"
Don't announce cost on simple single-request tasks — that would be annoying.
Based on the budget target set during setup:
Watch for these patterns and intervene:
When this skill is active, respond to these commands:
CommandAction/cost-setupRun the full setup flow, asking permission at each step/cost-statusShow current model, session stats, estimated costs/cost-auditAudit current configuration and suggest optimizations/cost-trimAnalyze system prompt and suggest reductions/freeSwitch to free-only mode ($0.00 per request)/free offReturn to normal smart routingResume smart routing after a manual model override/model [alias]Switch to specific model (overrides smart routing until reset)/resetClear session context (provide summary first)
When user asks for cost status, provide:
When user asks for an audit, analyze and report:
When this skill is shared with another OpenClaw user, include these instructions:
Your Current SetupEstimated Monthly CostWith This SkillSavingsOpus for everything~$1,000-2,500~$0-3097-100%Sonnet for everything~$500-800~$0-3094-100%MiniMax default, no free models~$60-80~$0-1575-100%Already optimized~$30-60~$0-1050-100%
When the user asks to run any cost optimization task, use the appropriate script from scripts/. All paths are relative to the skill directory.
scripts/backup-config.sh [config] [label] — Snapshot config before changesscripts/restore-config.sh [backup|"latest"] — Restore from backup, restart gatewayscripts/fallback-validator.sh [config] — Test every model in fallback chain with real API callsscripts/cost-audit.sh [config] — Full config analysis, monthly estimate, recommendationsscripts/heartbeat-cost.sh [log] [days] — Isolate heartbeat spending from real usagescripts/cost-history.sh [log] [days] — Recalculate past usage across all model tiersscripts/session-replay.sh <session|"latest"> [log] — Per-exchange cost breakdownscripts/provider-compare.sh [config] — Detect same model across providers, find cheapestscripts/tool-audit.sh [log] [days] — Find unused tools and duplicate callsscripts/token-counter.sh [workspace] — Count system prompt overhead per filescripts/context-monitor.sh [log] — Track context growth, predict compactionscripts/prompt-tracker.sh [workspace] [--snapshot|--report] — Track prompt size over timescripts/compaction-log.sh [log] [days] — Track compaction and memory flush eventsscripts/dedup-detector.sh [log] [days] — Find redundant requests and tool callsscripts/apply-preset.sh <free|budget|balanced|quality> [--dry-run] — One-command presetsscripts/token-enforcer.sh <config> <strict|moderate|normal|generous|unlimited> [--dry-run] — Set maxTokens limitsscripts/config-diff.sh [config] — Current vs recommended side-by-sidescripts/idle-sleep.sh [log] [idle-hours] [sleep-interval] — Auto-sleep during idle periodsscripts/setup-openrouter.sh <api-key> — Generate OpenRouter provider configscripts/cost-monitor.sh [log] [--live] — Real-time spend trackingscripts/cost-dashboard.js [config] [output.html] — HTML cost dashboardscripts/webhook-report.sh <url> [discord|slack|generic] — Send reports to webhooksscripts/cron-setup.sh — Generate cron job templates for automated monitoringscripts/model-switcher.sh [config] — All models: status + cost + strengthscripts/provider-health.sh [config] — Test all models: UP/DOWN/SLOW + latencyscripts/model-test.sh [config] — Basic reachability testscripts/preset-manager.sh <export|import|list> — Export/import named presetsscripts/multi-instance.sh [instances-config] — Aggregate costs across instancesscripts/parse-config.js <config> <dot.path> [default] — JSON5 config parser (dependency)When running scripts, resolve paths relative to the skill directory:
text
bash /path/to/skills/cost-optimizer/scripts/cost-audit.sh
This skill operates on these principles: