Agent skill

Token Optimizer

by LeoYeAI in LeoYeAI/openclaw-master-skills

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…

MITAuto-check passedAI & LLM Engineering

Install Token Optimizer

skills CLI
$ npx skills add LeoYeAI/openclaw-master-skills --skill token-optimizer -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install LeoYeAI/openclaw-master-skills token-optimizer --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/openclaw-token-optimizer .claude/skills/token-optimizer && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
token-optimizer
GitHub stars
2.2k
Token cost
~5.2k tokens
SKILL.md length
1,434 words
Files
11 (incl. scripts)
Skills in repo
1,215
Repo updated
First seen
Licence
MIT

At a glance

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…

  • Works in 7 steps: Lazy Skill Loading (NEW in v3.0 —… → Context Optimization (NEW!) → Smart Model Routing (ENHANCED!) → …
  • Token costs are high
  • SKILL.md covers Quick Start, Core Capabilities, Configuration Patches and Native OpenClaw Diagnostics…, plus 7 more sections
  • Runs Python and Shell scripts from its folder; calls python3 and jq

What it does

Token Optimizer is an agent skill from LeoYeAI/openclaw-master-skills. 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 (contextoptimizer, modelrouter, heartbeatoptimizer, tokentracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md…

Its SKILL.md is about 5.2k tokens, which your agent loads only when the skill is triggered. The skill folder holds 11 other files, including scripts (for example `CHANGELOG.md`, `README.md` and `SECURITY.md`).

It sits in AI & LLM Engineering, covering Model routing and gateways, LLM cost and token optimization and Rate limiting. The repository describes itself as: 🧠 Curated collection of 1209+ best OpenClaw skills — weekly updated by MyClaw.ai. The licence is MIT.

When your agent uses it

  • Token costs are high
  • API rate limits are being hit
  • Hosting multiple agents at scale

Example prompts

  • “/token-optimizer”

Requirements

  • Python 3
  • A Bash shell

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. Lazy Skill Loading (NEW in v3.0 — BIGGEST WIN!)
  2. Context Optimization (NEW!)
  3. Smart Model Routing (ENHANCED!)
  4. Heartbeat Optimization
  5. Cronjob Optimization (NEW!)
  6. Token Budget Tracking
  7. Multi-Provider Strategy

What it can do on your machine

Read from SKILL.md and the folder at commit e5199b5. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 5 files in scripts/ (Python and Shell), which the agent can run.

    Shell commands in SKILL.md call:

    • python3
    • jq

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Token Optimizer loads about 5.2k tokens when it runs. Until then it costs about 177 tokens; SKILL.md has 1,434 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~177
When it runs · the whole SKILL.md, loaded when a task matches
~5.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from LeoYeAI/openclaw-master-skills at commit e5199b5, republished under its MIT licence (© LeoYeAI). 1,434 words, ~5,158 tokens.

Download SKILL.mdSave it as .claude/skills/token-optimizer/SKILL.md (or your agent's skills folder). This skill also uses 10 other files; get the full folder from GitHub.
name
token-optimizer
description
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.
version
3.0.0
homepage
https://github.com/Asif2BD/OpenClaw-Token-Optimizer
source
https://github.com/Asif2BD/OpenClaw-Token-Optimizer
author
Asif2BD
security.verified
true
security.auditor
Oracle (Matrix Zion)
security.audit_date
2026-02-18
security.scripts_no_network
true
security.scripts_no_code_execution
true
security.scripts_no_subprocess
true

Token Optimizer

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):

  1. Generate optimized AGENTS.md (BIGGEST WIN!):

    bash
    python3 scripts/context_optimizer.py generate-agents
    # Creates AGENTS.md.optimized — review and replace your current AGENTS.md
  2. Check what context you ACTUALLY need:

    bash
    python3 scripts/context_optimizer.py recommend "hi, how are you?"
    # Shows: Only 2 files needed (not 50+!)
  3. Install optimized heartbeat:

    bash
    cp assets/HEARTBEAT.template.md ~/.openclaw/workspace/HEARTBEAT.md
  4. Enforce cheaper models for casual chat:

    bash
    python3 scripts/model_router.py "thanks!"
    # Single-provider Anthropic setup: Use Sonnet, not Opus
    # Multi-provider setup (OpenRouter/Together): Use Haiku for max savings
  5. Check current token budget:

    bash
    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

0. Lazy Skill Loading (NEW in v3.0 — BIGGEST WIN!)

The single highest-impact optimization available. Most agents burn 3,000–15,000 tokens per session loading skill files they never use. Stop that first.

The pattern:

  1. Create a lightweight SKILLS.md catalog in your workspace (~300 tokens — list of skills + when to load them)
  2. Only load individual SKILL.md files when a task actually needs them
  3. Apply the same logic to memory files — load MEMORY.md at startup, daily logs only on demand

Token savings:

Library sizeBefore (eager)After (lazy)Savings
5 skills~3,000 tokens~600 tokens80%
10 skills~6,500 tokens~750 tokens88%
20 skills~13,000 tokens~900 tokens93%

Quick implementation in AGENTS.md:

markdown
## Skills

At session start: Read SKILLS.md (the index only — ~300 tokens).
Load individual skill files ONLY when a task requires them.
Never load all skills upfront.

Full implementation (with catalog template + optimizer script):

bash
clawhub install openclaw-skill-lazy-loader

The companion skill openclaw-skill-lazy-loader includes a SKILLS.md.template, an AGENTS.md.template lazy-loading section, and a context_optimizer.py CLI that recommends exactly which skills to load for any given task.

Lazy loading handles context loading costs. The remaining capabilities below handle runtime costs. Together they cover the full token lifecycle.


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.

Usage:

bash
python3 scripts/context_optimizer.py recommend "<user prompt>"

Examples:

bash
# Simple greeting → minimal context (2 files only!)
context_optimizer.py recommend "hi"
→ Load: SOUL.md, IDENTITY.md
→ Skip: Everything else
→ Savings: ~80% of context

# Standard work → selective loading
context_optimizer.py recommend "write a function"
→ Load: SOUL.md, IDENTITY.md, memory/TODAY.md
→ Skip: docs, old memory, knowledge base
→ Savings: ~50% of context

# Complex task → full context
context_optimizer.py recommend "analyze our entire architecture"
→ Load: SOUL.md, IDENTITY.md, MEMORY.md, memory/TODAY+YESTERDAY.md
→ Conditionally load: Relevant docs only
→ Savings: ~30% of context

Output format:

json
{
  "complexity": "simple",
  "context_level": "minimal",
  "recommended_files": ["SOUL.md", "IDENTITY.md"],
  "file_count": 2,
  "savings_percent": 80,
  "skip_patterns": ["docs/**/*.md", "memory/20*.md"]
}

Integration pattern: Before loading context for a new session:

python
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:

bash
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"!

Usage:

bash
python3 scripts/model_router.py "<user prompt>" [current_model] [force_tier]

Examples:

bash
# Communication (NEW!) → ALWAYS Haiku
python3 scripts/model_router.py "thanks!"
python3 scripts/model_router.py "hi"
python3 scripts/model_router.py "ok got it"
→ Enforced: Haiku (NEVER Sonnet/Opus for casual chat)

# Simple task → suggests Haiku
python3 scripts/model_router.py "read the log file"

# Medium task → suggests Sonnet
python3 scripts/model_router.py "write a function to parse JSON"

# Complex task → suggests Opus
python3 scripts/model_router.py "design a microservices architecture"

Patterns enforced to Haiku (NEVER Sonnet/Opus):

Communication:

  • Greetings: hi, hey, hello, yo
  • Thanks: thanks, thank you, thx
  • Acknowledgments: ok, sure, got it, understood
  • Short responses: yes, no, yep, nope
  • Single words or very short phrases

Background tasks:

  • Heartbeat checks: "check email", "monitor servers"
  • Cronjobs: "scheduled task", "periodic check", "reminder"
  • Document parsing: "parse CSV", "extract data from log", "read JSON"
  • Log scanning: "scan error logs", "process logs"

Integration pattern:

python
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:

bash
# Copy template to workspace
cp assets/HEARTBEAT.template.md ~/.openclaw/workspace/HEARTBEAT.md

# Plan which checks should run
python3 scripts/heartbeat_optimizer.py plan

Commands:

bash
# 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:

markdown
## 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.

Quick reference:

Task TypeModelExample
Monitoring/alertsHaikuCheck server health, disk space
Data parsingHaikuExtract CSV/JSON/logs
RemindersHaikuDaily standup, backup reminders
Simple reportsHaikuStatus summaries
Content generationSonnetBlog summaries (quality matters)
Deep analysisSonnetWeekly insights
Complex reasoningNever use Opus for cronjobs

Example (good):

bash
# Parse daily logs with Haiku
cron add --schedule "0 2 * * *" \
  --payload '{
    "kind":"agentTurn",
    "message":"Parse yesterday error logs and summarize",
    "model":"anthropic/claude-haiku-4"
  }' \
  --sessionTarget isolated

Example (bad):

bash
# ❌ Using Opus for simple check (60x more expensive!)
cron add --schedule "*/15 * * * *" \
  --payload '{
    "kind":"agentTurn",
    "message":"Check email",
    "model":"anthropic/claude-opus-4"
  }' \
  --sessionTarget isolated

Savings: Using Haiku instead of Opus for 10 daily cronjobs = $17.70/month saved per agent.

Integration with model_router:

bash
# Test if your cronjob should use Haiku
model_router.py "parse daily error logs"
# → Output: Haiku (background task pattern detected)
5. Token Budget Tracking

Monitor usage and alert when approaching limits:

Setup:

bash
# Check current daily usage
python3 scripts/token_tracker.py check

# Get model suggestions
python3 scripts/token_tracker.py suggest general

# Reset daily tracking
python3 scripts/token_tracker.py reset

Output format:

json
{
  "date": "2026-02-06",
  "cost": 2.50,
  "tokens": 50000,
  "limit": 5.00,
  "percent_used": 50,
  "status": "ok",
  "alert": null
}

Status levels:

  • ok: Below 80% of daily limit
  • warning: 80-99% of daily limit
  • exceeded: Over daily limit

Integration pattern: Before starting expensive operations, check budget:

python
import json
import subprocess

result = subprocess.run(
    ["python3", "scripts/token_tracker.py", "check"],
    capture_output=True, text=True
)
budget = json.loads(result.stdout)

if budget["status"] == "exceeded":
    # Switch to cheaper model or defer non-urgent work
    use_model = "anthropic/claude-haiku-4"
elif budget["status"] == "warning":
    # Use balanced model
    use_model = "anthropic/claude-sonnet-4-5"

Customization: Edit daily_limit_usd and warn_threshold parameters in function calls.

6. Multi-Provider Strategy

See references/PROVIDERS.md for comprehensive guide on:

  • Alternative providers (OpenRouter, Together.ai, Google AI Studio)
  • Cost comparison tables
  • Routing strategies by task complexity
  • Fallback chains for rate-limited scenarios
  • API key management

Quick reference:

ProviderModelCost/MTokUse Case
AnthropicHaiku 4$0.25Simple tasks
AnthropicSonnet 4.5$3.00Balanced default
AnthropicOpus 4$15.00Complex reasoning
OpenRouterGemini 2.5 Flash$0.075Bulk operations
Google AIGemini 2.0 Flash ExpFREEDev/testing
TogetherLlama 3.3 70B$0.18Open alternative

Configuration Patches

See assets/config-patches.json for advanced optimizations:

Implemented by this skill:

  • ✅ Heartbeat optimization (fully functional)
  • ✅ Token budget tracking (fully functional)
  • ✅ Model routing logic (fully functional)

Native OpenClaw 2026.2.15 — apply directly:

  • ✅ Session pruning (contextPruning: cache-ttl) — auto-trims old tool results after Anthropic cache TTL expires
  • ✅ Bootstrap size limits (bootstrapMaxChars / bootstrapTotalMaxChars) — caps workspace file injection size
  • ✅ Cache retention long (cacheRetention: "long" for Opus) — amortizes cache write costs

Requires OpenClaw core support:

  • ⏳ Prompt caching (Anthropic API feature — verify current status)
  • ⏳ Lazy context loading (use context_optimizer.py script today)
  • ⏳ Multi-provider fallback (partially supported)

Apply config patches:

bash
# Example: Enable multi-provider fallback
gateway config.patch --patch '{"providers": [...]}'
Show full SKILL.md (595 more words)Show less

Native OpenClaw Diagnostics (2026.2.15+)

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

Combine with token_tracker.py — /usage cost gives session totals; token_tracker.py tracks daily budget.

Session status
/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.

bash
# 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

Apply to your OpenClaw config:

json
{
  "agents": {
    "defaults": {
      "heartbeat": {
        "every": "55m"
      }
    }
  }
}

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
  1. Install optimized HEARTBEAT.md
  2. Run budget checks before expensive operations
  3. Manually route complex tasks to Opus only when needed

Expected savings: 20-30%

For Managed Hosting (xCloud, etc.)
  1. Default all agents to Haiku
  2. Route user interactions to Sonnet
  3. Reserve Opus for explicitly complex requests
  4. Use Gemini Flash for background operations
  5. Implement daily budget caps per customer

Expected savings: 40-60%

For High-Volume Deployments
  1. Use multi-provider fallback (OpenRouter + Together.ai)
  2. Implement aggressive routing (80% Gemini, 15% Haiku, 5% Sonnet)
  3. Deploy local Ollama for offline/cheap operations
  4. Batch heartbeat checks (every 2-4 hours, not 30 min)

Expected savings: 70-90%

Integration Examples

Workflow: Smart Task Handling
bash
# 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
markdown
## 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.

Maintenance

Daily:

  • Check budget status: token_tracker.py check

Weekly:

  • Review routing accuracy (are suggestions correct?)
  • Adjust heartbeat intervals based on activity

Monthly:

  • Compare costs before/after optimization
  • Review and update PROVIDERS.md with new options

Cost Estimation

Example: 100K tokens/day workload

Without skill:

  • 50K context tokens + 50K conversation tokens = 100K total
  • All Sonnet: 100K × $3/MTok = $0.30/day = $9/month
StrategyContextModelDaily CostMonthlySavings
Baseline (no optimization)50KSonnet$0.30$9.000%
Context opt only10K (-80%)Sonnet$0.18$5.4040%
Model routing only50KMixed$0.18$5.4040%
Both (this skill)10KMixed$0.09$2.7070%
Aggressive + Gemini10KGemini$0.03$0.9090%

Key insight: Context optimization (50K → 10K tokens) saves MORE than model routing!

xCloud hosting scenario (100 customers, 50K tokens/customer/day):

  • Baseline (all Sonnet, full context): $450/month
  • With token-optimizer: $135/month
  • Savings: $315/month per 100 customers (70%)

Resources

Scripts (4 total)
  • context_optimizer.py — Context loading optimization and lazy loading (NEW!)
  • model_router.py — Task classification, model suggestions, and communication enforcement (ENHANCED!)
  • heartbeat_optimizer.py — Interval management and check scheduling
  • token_tracker.py — Budget monitoring and alerts
References
  • PROVIDERS.md — Alternative AI providers, pricing, and routing strategies
Assets (3 total)
  • HEARTBEAT.template.md — Drop-in optimized heartbeat template with Haiku enforcement (ENHANCED!)
  • cronjob-model-guide.md — Complete guide for choosing models in cronjobs (NEW!)
  • config-patches.json — Advanced configuration examples

Future Enhancements

Ideas for extending this skill:

  1. Auto-routing integration — Hook into OpenClaw message pipeline
  2. Real-time usage tracking — Parse session_status automatically
  3. Cost forecasting — Predict monthly spend based on recent usage
  4. Provider health monitoring — Track API latency and failures
  5. A/B testing — Compare quality across different routing strategies

© LeoYeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 10 other files (scripts) in skills/openclaw-token-optimizer of LeoYeAI/openclaw-master-skills.

  • SKILL.md
  • .clawhubsafe
  • CHANGELOG.md
  • README.md
  • SECURITY.md
  • _meta.json
  • scripts/context_optimizer.py
  • scripts/heartbeat_optimizer.py
  • scripts/model_router.py
  • scripts/optimize.sh
  • scripts/token_tracker.py

Open the folder on GitHubat commit e5199b5

Compare with similar skills

Token Optimizer next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Token Optimizer compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Token Optimizer this skillLeoYeAI/openclaw-master-skills2.2k—~5.2kAutomated safety check: PassMIT
LLM Gatewaysickn33/agentic-awesome-skills47k1 repos~2.1kAutomated safety check: PassMIT
Cost TrackingHabitat-Thinking/ai-literacy-superpowers114—~1.7kAutomated safety check: PassCustom licence
Agents WorkflowsVectorSpaceLab/AREX-Skill328—~500Automated safety check: PassApache-2.0
Cost Aware LLM Pipelinemajiayu000/claude-skill-registry6666 repos~1.4kAutomated safety check: PassMIT
LLM Routercuriositech/some_claude_skills2431 repos~1.7kAutomated safety check: PassMIT

Similar skills

  • LLM Gateway

    sickn33/agentic-awesome-skills

    Deploy an API gateway for LLM traffic with load balancing, rate limiting, key management, semantic caching, fallback routing, and cost tracking.

    47k GitHub starsUsed in 1 repo~2.1k tokens
    Backend & APIsAuto-check passed
  • Cost Tracking

    Habitat-Thinking/ai-literacy-superpowers

    A skill your agent uses when the user wants to capture AI tool costs, review spending trends, set cost budgets, or integrate cost data into health snapshots — guides quarterly cost capture, records…

    114 GitHub stars~1.7k tokensUpdated 16 days ago
    AI & LLM EngineeringAuto-check passed
  • Agents Workflows

    VectorSpaceLab/AREX-Skill

    A skill your agent uses for giskard.agents async chat workflows, tools, prompt templates, structured outputs, retries, rate limiting, embeddings, and optional LiteLLM backend.

    328 GitHub stars~500 tokensUpdated 1 mo ago
    AI & LLM EngineeringAuto-check passed
  • Cost Aware LLM Pipeline

    majiayu000/claude-skill-registry

    Cost optimization patterns for LLM API usage — model routing by task complexity, budget tracking, retry logic, and prompt caching.

    666 GitHub starsUsed in 6 repos~1.4k tokens
    AI & LLM EngineeringAuto-check passed
  • LLM Router

    curiositech/some_claude_skills

    Selects the optimal LLM model and provider for each task based on complexity, cost budget, and capability requirements.

    243 GitHub starsUsed in 1 repo~1.7k tokens
    AI & LLM EngineeringAuto-check passed
  • Pp Groq

    mvanhorn/printing-press-library

    Every Groq endpoint in your terminal, plus a local ledger that tracks token cost and rate-limit budget.

    2.1k GitHub stars~7.9k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check: notes

More from LeoYeAI/openclaw-master-skills

All 1,215 skills in this repo
  • DevOps Pipeline Management

    LeoYeAI/openclaw-master-skills

    Manages pipelines on a DevOps quality and efficiency platform through its OpenAPI: list workspaces and templates, create, update, run and cancel pipelines, and read run records.

    2.2k GitHub stars~4.2k tokensUpdated 2 mo ago
    Auto-check: notes
  • Feishu Document Collaboration

    LeoYeAI/openclaw-master-skills

    Patches OpenClaw's Feishu extension so an edited document triggers an isolated agent session that reads the doc and replies inline, turning it into a live chat space.

    2.2k GitHub stars~2k tokensUpdated 2 mo ago
    Auto-check passed
  • Files Memory System

    LeoYeAI/openclaw-master-skills

    Multi-context memory management system for OpenClaw agents with group-isolated storage, global shared memory, workspace organization, and group-specific skills isolation.

    2.2k GitHub stars~3.8k tokensUpdated 2 mo ago
    Auto-check passed
  • GEO-Claw AI Visibility Agent

    LeoYeAI/openclaw-master-skills

    Runs a brand's AI-search visibility work end to end: diagnosing how AI platforms represent it, repositioning it, producing AI-optimized content and monitoring ongoing mentions.

    2.2k GitHub stars~4.7k tokensUpdated 2 mo ago
    Auto-check passed
  • Google Workspace CLI

    LeoYeAI/openclaw-master-skills

    Installs and authenticates the gws CLI, then automates Gmail, Drive, Sheets, Calendar, Docs, Chat and Tasks with ready-made recipes, persona bundles and security audits.

    2.2k GitHub stars~2.6k tokensUpdated 2 mo ago
    Auto-check: notes
  • HealthFit Health Advisors

    LeoYeAI/openclaw-master-skills

    Runs four advisor roles, a fitness coach, nutritionist, data analyst and TCM practitioner, to build a health profile and track workouts, diet and wellness over time.

    2.2k GitHub stars~4.4k tokensUpdated 2 mo ago
    Auto-check passed

Questions about Token Optimizer

What does Token Optimizer do?

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…. Token Optimizer is an agent skill from LeoYeAI/openclaw-master-skills.15 features (session pruning, bootstrap size limits, cache TTL alignment).

When should I use Token Optimizer?

Token Optimizer fits situations like: token costs are high; API rate limits are being hit; hosting multiple agents at scale.

How do I install Token Optimizer in Claude Code?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill token-optimizer -a claude-code`. Or copy the skill folder (skills/openclaw-token-optimizer in LeoYeAI/openclaw-master-skills) into .claude/skills/token-optimizer in your project. Claude Code loads it when a task matches its description.

How do I install Token Optimizer in Codex?

Run `npx skills add LeoYeAI/openclaw-master-skills --skill token-optimizer -a codex`. Or copy the skill folder (skills/openclaw-token-optimizer in LeoYeAI/openclaw-master-skills) into .agents/skills/token-optimizer in your project. Codex loads it when a task matches its description.

Can I use Token Optimizer in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add LeoYeAI/openclaw-master-skills --skill token-optimizer -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/token-optimizer, .gemini/skills/token-optimizer, .github/skills/token-optimizer and .opencode/skills/token-optimizer in your project.

What does Token Optimizer need to run?

Going by SKILL.md and its folder, Token Optimizer needs Python and a shell for the scripts in its folder and the command-line tools its instructions call (python3 and jq). Our summary lists: Python 3; A Bash shell.

Does Token Optimizer access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Token Optimizer safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Token Optimizer use?

Token Optimizer is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Token Optimizer use?

About 5.2k tokens (SKILL.md is roughly 21k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Token Optimizer?

Skills that share tags, products or a category with Token Optimizer: LLM Gateway (sickn33/agentic-awesome-skills, 47k stars), Cost Tracking (Habitat-Thinking/ai-literacy-superpowers, 114 stars), Agents Workflows (VectorSpaceLab/AREX-Skill, 328 stars) and Cost Aware LLM Pipeline (majiayu000/claude-skill-registry, 666 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Token Optimizer?

LeoYeAI (a GitHub user) maintains it in LeoYeAI/openclaw-master-skills, which has 2,158 GitHub stars. The repository holds 1,215 skills in this directory. The repository was last updated on July 20, 2026.

Source: LeoYeAI/openclaw-master-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.