当前位置: 首页 > Skill >

Anthropic Token Optimizer

Anthropic Token Optimizer

Anthropic Token Optimizer

帮助 OpenClaw 代理降低 Anthropic API成本(缓存读取、压缩、上下文膨胀)。适用于用户询问令牌优化、降低 API 费用、缓存等场景。

1.3.0 2026.11.26 530
获取Skill文件查看使用说明
作 者:陆舟 许可证: 更新时间:2026.11.26
本文目录展开

Anthropic Token Optimizer

Minimize Anthropic API costs without sacrificing quality. Focus on cache read reduction — the #1 cost driver for long sessions with Opus.

Anthropic Pricing Reference

Model Input Cache Write Cache Read Output
Haiku $0.80 $1.00 $0.08 $4
Sonnet $3 $3.75 $0.30 $15
Opus $15 $18.75 $1.50 $75

(per MTok — multiply by millions of tokens)

Key insight: Cache read = context_size × num_turns. 200k context × 50 turns on Opus = ~$15 just cache reads.

Part 1: Config Optimizations (openclaw.json)

1. Compaction model — use cheaper model (highest ROI ✅)

"compaction": {
  "mode": "safeguard",
  "model": "anthropic/claude-sonnet-4-20250514"
}

Sonnet summarizes at 5x less cost than Opus. Quality comparable for summaries.

2. Context pruning — trim old tool results

"contextPruning": { "mode": "cache-ttl", "ttl": "1h" }
TTL Behavior Verdict
1h Trims after 1 hour ✅ Best balance
30m Moderate OK for active sessions
5m Aggressive ⚠️ Loses tool results

3. Cache retention — keep "long"

"params": { "cacheRetention": "long", "context1m": true }

"long" = fewer cache writes ($18.75/MTok on Opus!). Don't switch to "default".

4. Cache TTL heartbeat alignment

Anthropic cache expires after ~1h idle. Heartbeat at 55min keeps it warm:

"heartbeat": { "every": "55m" }

Prevents expensive cache re-writes when agent resumes after idle.

5. Bootstrap size limits — cap workspace injection

"bootstrapMaxChars": 8000,
"bootstrapTotalMaxChars": 30000

Check current injection: /context list. Prevents oversized files from inflating every turn.

Part 2: Workspace Hygiene (biggest long-term win)

File budgets

File Target Review cycle
AGENTS.md <500 tokens (~2KB) Monthly
SOUL.md <250 tokens (~1KB) Rarely
TOOLS.md <500 tokens (~2KB) When tools change
MEMORY.md <400 tokens (~1.5KB) Weekly prune
HEARTBEAT.md <400 tokens (~1.5KB) When done
memory/YYYY-MM-DD.md <30 lines Collapse at EOD
Total injected <2,800 tokens

Reduction tactics

  • Merge redundant files (IDENTITY.md + USER.md → SOUL.md)
  • Move non-essential docs to subfolders (docs/, notes/) — not auto-injected
  • Collapse exploration into decisions: keep "what we decided", delete "how we got here"
  • Prune ghost context: references to old paths, removed tools, fixed bugs
  • Deduplicate: info in SOUL.md shouldn't repeat in MEMORY.md or AGENTS.md

Daily memory rules

Write: decisions + why (1 line), new tools/config, lessons, user preferences. Skip: exploration steps, command outputs, things already in MEMORY.md, delivered content. Format: Bullets, not paragraphs. One fact per line.

Part 3: Behavioral Patterns

6. /compact after each topic (most effective manual action)

/compact Focus on [topic summary]

7. /new when switching topics entirely

Context resets to 0. Don't carry 200k into unrelated work.

8. Subagents for tool-heavy work

Spawn subagents (cheaper model) for: codebase grep, reading 5+ files, research/web fetch. Tool results stay isolated.

9. Tool output discipline

  • Truncate: | head -20, | jq '.key'
  • Request only needed fields from APIs
  • Never paste full JSON when you need one value
  • Output >50 lines → summarize, don't quote

10. File loading discipline

  • Startup: only today + yesterday memory files
  • Read SKILL.md only when task needs that skill
  • Don't re-read files already in context

Part 4: Context Budgeting

Information partitioning

Budget Content
10% Task instructions + constraints
40% Recent 5-10 turns of dialogue
20% Decision logs ("tried X, failed because Y")
20% High-relevance MEMORY.md snippets
10% Tool schemas + system prompt

Compaction survival

Before compaction hits, critical state must be captured:

  1. WAL Protocol: On corrections, decisions, specific values → write to SESSION-STATE.md before responding
  2. Working buffer: At 60%+ context → append exchange summaries to memory/working-buffer.md
  3. Recovery: After compaction, read buffer + session state first. Never ask "where were we?"

Session lifespan

After 85% context or 3+ compactions → start fresh with /new. Good MEMORY.md means minimal context loss.

Part 5: Codebase Map Caching (Atris Pattern)

Problem: Every code review or exploration session re-reads the same files, burning tokens on repeated grep/read calls. A 500-file project can cost 50k+ tokens just for navigation.

Solution: Generate a persistent codebase map (atris/MAP.md) once, reuse across sessions.

Setup (one-time per project)

# Install atris skill
npx clawhub@latest install atris

# Or manually: create atris/ folder in project root, then scan
rg "^(export|function|class|const|def |async def |router.|app.)" 
  --line-number -g "!node_modules" -g "!.git" -g "!dist" -g "!.env*"

MAP.md structure

# MAP.md — [Project] Navigation Guide
> Last updated: YYYY-MM-DD

## Quick Reference
- `src/index.ts:1` — App entry point
- `src/routes/auth.ts:15` — POST /login handler
- `src/models/user.ts:8` — User schema

### Feature: Authentication
- **Entry:** `src/auth/login.ts:45-89` (handleLogin)
- **Validation:** `src/auth/validate.ts:12` (validateToken)
- **Routes:** `src/routes/auth.ts:5-28`

### Feature: Billing
- **Controller:** `src/controllers/billing.ts:20`
- **Service:** `src/services/stripe.ts:1-45`

MAP-first rule

Before searching codebase:

  1. Read atris/MAP.md — found? Go directly to file:line
  2. Not found? Search with rg, then add result to MAP.md

Map gets smarter every session. Never let a discovery go unrecorded.

Keeping fresh

  • New file → add to relevant section
  • Deleted file → remove from map
  • Major refactor → regenerate affected sections only
  • Small updates, not full regeneration

Token savings

Codebase Without map With map Savings
Small (50 files) ~5k tokens/explore ~1k 80%
Medium (200 files) ~20k tokens/explore ~3k 85%
Large (500+ files) ~50k tokens/explore ~5k 90%

Diagnostics

/context list    → token count per injected file
/context detail  → full breakdown (tools, skills, system)
/usage tokens    → append token count to every reply
/usage cost      → cumulative cost summary
/status          → model, context %, cost estimate

Decision Matrix

Situation Action
Session >100k context /compact immediately
Switching topics /new or /compact
Reading 5+ files Spawn subagent
Compaction cost high Set compaction model to Sonnet
Daily cost >$10 Audit session count, compact more
Cache writes spiking Heartbeat ≤55min, keep cacheRetention: long
Workspace injection >20KB Merge/move files, set bootstrapMaxChars
Context >85% /new — start fresh

Impact Summary

Technique Savings UX Impact
Compaction model = Sonnet ~80% compaction cost None
Workspace file budgets ~30-50% base cost None
/compact after topics ~40-60% cache read Manual step
Cache TTL heartbeat (55m) ~20-30% cache writes None
Bootstrap size limits ~20-30% base cost None
Subagent delegation ~30% cache read Better (parallel)
Tool output discipline ~10-20% per turn Requires habit
/new for new topics ~100% (reset) Lose old context
Codebase map (Atris) ~80-90% code exploration One-time setup

Credits

Incorporates ideas from: openclaw-token-optimizer, context-slimmer, context-budgeting, compaction-survival, context-hygiene, atris (codebase map caching).

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,037
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,020
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,015
Skill 文件
  • SKILL.md
    • Anthropic Token Optimizer
    • Anthropic Pricing Reference
    • Part 1: Config Optimizations (openclaw.json)
      • 1. Compaction model — use cheaper model (highest ROI ✅)
      • 2. Context pruning — trim old tool results
      • 3. Cache retention — keep "long"
      • 4. Cache TTL heartbeat alignment
      • 5. Bootstrap size limits — cap workspace injection
    • Part 2: Workspace Hygiene (biggest long-term win)
      • File budgets
      • Reduction tactics
      • Daily memory rules
    • Part 3: Behavioral Patterns
      • 6. /compact after each topic (most effective manual action)
      • 7. /new when switching topics entirely
      • 8. Subagents for tool-heavy work
      • 9. Tool output discipline
      • 10. File loading discipline
    • Part 4: Context Budgeting
      • Information partitioning
      • Compaction survival
      • Session lifespan
    • Part 5: Codebase Map Caching (Atris Pattern)
      • Setup (one-time per project)
      • MAP.md structure
      • MAP-first rule
      • Keeping fresh
      • Token savings
    • Diagnostics
    • Decision Matrix
    • Impact Summary
    • Credits
  • 项目或源文件

相关 Skill

更多
Gemini Worker Gemini Worker 将 Gemini CLI 作为无头工作代理运行,用于长时间运行或可并行处理的任务。使用场景:(1) Anthropic API 超载/不可用(529错误)且...
Tamp Tamp 为 OpenClaw 配置 Tamp 令牌压缩代理,降低 Anthropic API 输入令牌费用。用于用户请求节省令牌、降低 API 成本或进行相应设置的场景。
safeTok ↔ OpenClaw Bridge safeTok ↔ OpenClaw Bridge 将 safeTok Nostr DMs 连接到 OpenClaw 代理,使用 Claude OAuth,无需 Anthropic API 密钥,通过 safeTok NIP‑44 加密的 DMs 进行通讯。
claude-config-帮助配置技能 claude-config-帮助配置技能 Configure Claude Code to use any Anthropic-compatible API endpoint with custom models. Use when setting up Claude Code with a non-Anthropic API provider, or when Claude Code rejects a model with "There's an issue with the selected model". 用任何ai读取这个技能, 就能帮你配置好在国内使用第三方api的claude
anthropic api anthropic api 集成Anthropic Claude API,实现聊天、工具、视觉、文档分析与代码生成,兼顾成本控制和错误处理。