MMX Cost Optimizer

v1.0.0

智能AI成本优化系统,集成Token预算管理、边际收益检测、多维度成本统计。当用户要求优化AI调用成本、控制Token使用、监控预算消耗、生成成本报告、降低API费用时使用。

0· 91·0 current·0 all-time

Install

OpenClaw Prompt Flow

Install with OpenClaw

Best for remote or guided setup. Copy the exact prompt, then paste it into OpenClaw for e2e5g/mmx-cost-optimizer.

Previewing Install & Setup.
Prompt PreviewInstall & Setup
Install the skill "MMX Cost Optimizer" (e2e5g/mmx-cost-optimizer) from ClawHub.
Skill page: https://clawhub.ai/e2e5g/mmx-cost-optimizer
Keep the work scoped to this skill only.
After install, inspect the skill metadata and help me finish setup.
Use only the metadata you can verify from ClawHub; do not invent missing requirements.
Ask before making any broader environment changes.

Command Line

CLI Commands

Use the direct CLI path if you want to install manually and keep every step visible.

OpenClaw CLI

Bare skill slug

openclaw skills install mmx-cost-optimizer

ClawHub CLI

Package manager switcher

npx clawhub@latest install mmx-cost-optimizer
Security Scan
VirusTotalVirusTotal
Benign
View report →
OpenClawOpenClaw
Benign
high confidence
Purpose & Capability
Name/description (AI cost/token optimization) match the content of SKILL.md: budgeting rules, cost formulas, hooks, and suggestion generation. There are no unrelated requirements (no cloud creds, no unrelated binaries).
Instruction Scope
SKILL.md contains only local logic and pseudocode for tracking tokens, computing costs, generating suggestions, and registering hooks. It references platform helper functions (registerHook, saveCurrentProjectConfig, getStoredSessionCosts, logCostEvent) but does not instruct reading arbitrary files, environment variables, or sending data to external endpoints. Note: the instructions assume the platform provides storage/hooks—verify what those platform functions store and where.
Install Mechanism
Instruction-only skill with no install spec and no code files to execute. Lowest-risk installation surface: nothing is downloaded or written by an installer.
Credentials
No environment variables, credentials, or config paths are declared or required. The functions referenced imply saving/restoring session state, which is expected for a budgeting tool and does not demand extra secrets.
Persistence & Privilege
always:false and user-invocable (normal). The skill expects to register hooks and persist session cost data via platform APIs; this is appropriate for its purpose but means it will write/read cost state in whatever storage the platform exposes — verify that storage is limited to the skill's own data and not global secrets.
Assessment
This skill appears coherent for cost and token management and does not ask for secrets or installs. Before installing: (1) confirm the platform APIs referenced (registerHook, saveCurrentProjectConfig, getStoredSessionCosts, logCostEvent) are limited to storing cost/session data and do not expose or modify unrelated configs; (2) prefer installing from a known source (source/homepage are missing here); (3) test in a sandbox project to see exactly what data is persisted and retained; and (4) if you need stronger assurance, ask the author or publisher for a provenance link or repo before trusting it with production data.

Like a lobster shell, security has layers — review code before you run it.

budgetvk97fgvwsw7055xwmhnjamkdn3n843cevcostvk97fgvwsw7055xwmhnjamkdn3n843cevlatestvk97fgvwsw7055xwmhnjamkdn3n843cevoptimizationvk97fgvwsw7055xwmhnjamkdn3n843cevtokenvk97fgvwsw7055xwmhnjamkdn3n843cev
91downloads
0stars
1versions
Updated 3w ago
v1.0.0
MIT-0

Cost Optimizer Pro

智能AI成本优化系统 - Claude Code成本管理核心技能提炼

核心能力

  1. Token预算管理 - 智能追踪、边际收益检测、自动决策
  2. 多维度成本统计 - 输入/输出/缓存/搜索全维度
  3. 实时成本监控 - 每轮显示、累计统计
  4. 优化建议生成 - 基于使用模式自动建议

预算配置

const BUDGET_CONFIG = {
  // 完成阈值
  completionThreshold: 0.9,

  // 边际收益递减检测
  diminishingThreshold: 500,

  // 最大继续次数
  maxContinuations: 10,

  // 警告阈值
  warningThreshold: 0.75,

  // 成本阈值
  costWarningThreshold: 1.00,
  costHardLimit: 10.00
}

决策算法

预算决策流程

检查Token使用
      ↓
是否 < 75% 预算?
  ├─ 是 → 正常继续
  ↓
是否 < 90% 预算?
  ├─ 是 → 继续 + nudgeMessage
  ↓
是否边际递减?
  ├─ 是 → 停止(边际收益递减)
  ↓
之前有继续吗?
  ├─ 是 → 停止(正常完成)
  └─ 否 → 继续等待

边际收益检测

function isDiminishing(tracker, delta): boolean {
  return (
    tracker.continuationCount >= 3 &&
    delta < DIMINISHING_THRESHOLD &&
    tracker.lastDeltaTokens < DIMINISHING_THRESHOLD
  )
}

成本追踪

Token类型

类型典型成本优化潜力
input_tokens$3.5/1M
output_tokens$15/1M
cache_read~10% input自动
cache_creation~30% input一次性
web_search$0.01/次按需

成本计算

costUSD = inputTokens × inputPrice + outputTokens × outputPrice

使用示例

基本使用

import { createBudgetTracker, checkTokenBudget } from './tokenBudget.js'

const tracker = createBudgetTracker()
const budget = 100000

function onAPIResponse(usage) {
  const totalTokens = usage.input_tokens + usage.output_tokens
  const decision = checkTokenBudget(tracker, budget, totalTokens)

  if (decision.action === 'continue') {
    console.log(decision.nudgeMessage)
  } else {
    console.log('停止原因:', decision.completionEvent)
  }
}

成本监控

function formatTotalCost() {
  return `
Total cost:            ${formatCost(getTotalCostUSD())}
Total duration (API):  ${formatDuration(getTotalAPIDuration())}
Total code changes:    ${linesAdded} lines added, ${linesRemoved} removed
Usage by model:
  ${formatModelUsage()}
  `.trim()
}

优化策略

1. 缓存复用

  • 相同上下文用cache_read
  • 成本降低约90%

2. 上下文压缩

  • 减少input_tokens
  • 保留关键信息

3. 输出精简

  • 减少output_tokens
  • 避免冗长回复

4. 批量操作

  • 减少API调用次数
  • 合并相似任务

显示格式

Total cost:            $0.0234
Total duration (API):  45.2s
Total code changes:    127 lines added, 43 lines removed
Usage by model:
  claude-sonnet:  12,500 input, 3,200 output, 89 cache read ($0.0189)
  claude-haiku:   2,000 input, 800 output ($0.0045)

配置选项

参数默认值说明
completionThreshold0.9完成阈值
diminishingThreshold500边际收益阈值
maxContinuations10最大继续次数
warningThreshold0.75警告阈值

集成Hook

// 压缩前Hook
registerHook('pre_compact', async (ctx) => {
  const costSavings = estimateCostSavings(ctx.messages)
  if (costSavings > 0.01) {
    ctx.modifiedStrategy = 'aggressive'
  }
})

// 压缩后Hook
registerHook('post_compact', async (ctx) => {
  logCostEvent('compact', {
    tokensBefore: ctx.tokensBefore,
    tokensAfter: ctx.tokensAfter,
    savings: estimateSavings(ctx)
  })
})

会话恢复

// 保存会话成本
function saveCurrentSessionCosts() {
  saveCurrentProjectConfig(current => ({
    ...current,
    lastCost: getTotalCostUSD(),
    lastAPIDuration: getTotalAPIDuration(),
    lastTotalInputTokens: getTotalInputTokens(),
    lastTotalOutputTokens: getTotalOutputTokens(),
    lastModelUsage: getModelUsage(),
    lastSessionId: getSessionId()
  }))
}

// 恢复会话成本
function restoreCostStateForSession(sessionId) {
  const data = getStoredSessionCosts(sessionId)
  if (data && data.lastSessionId === sessionId) {
    setCostStateForRestore(data)
    return true
  }
  return false
}

优化建议生成

function generateOptimizationSuggestions(usage, cost) {
  const suggestions = []

  // 检查缓存利用率
  const cacheHitRate = usage.cacheReadInputTokens / usage.inputTokens
  if (cacheHitRate < 0.3) {
    suggestions.push({
      type: 'cache',
      priority: 'high',
      message: '缓存命中率较低,考虑复用上下文',
      potential: '可节省30-50%成本'
    })
  }

  // 检查输出长度
  const outputRatio = usage.outputTokens / usage.inputTokens
  if (outputRatio > 0.5) {
    suggestions.push({
      type: 'output',
      priority: 'medium',
      message: '输出长度较高,考虑精简回复',
      potential: '可节省10-20%成本'
    })
  }

  return suggestions
}

Comments

Loading comments...