Skip to content

hidearmoon/openclaw-meter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ClawMeter 🦞📊

OpenClaw Token Usage Analytics & Cost Control Platform OpenClaw Token 用量分析与成本控制平台

PyPI version Python 3.10+ License: MIT CI OpenClaw


ClawMeter connects to your OpenClaw Gateway, captures every token consumed across all sessions, and turns that data into actionable cost intelligence — before your cloud bill surprises you.

ClawMeter 接入你的 OpenClaw Gateway,实时捕获所有会话的 Token 消耗,并将数据转化为可操作的成本洞察 —— 在账单让你惊讶之前。


✨ Features / 核心功能

Feature Description
Real-time collection WebSocket streaming from OpenClaw Gateway
Multi-dimensional analytics Break down spend by model, channel, session, time period
Cost optimization engine Auto-detect model downgrade opportunities, unused caching, anomalous channels
Budget alerts Daily/monthly limits with configurable warning thresholds
Log file parser Fallback ingestion from OpenClaw verbose logs
Built-in pricing 2026 rates for Claude 4/3.x, GPT-4.1/4o, Gemini 2.0, DeepSeek, and more
Beautiful CLI Rich tables, cost trends, per-model breakdown at a glance
Zero-dependency server Single SQLite file — no Postgres, Redis, or external services

🚀 Quick Start / 快速开始 (30 seconds)

# 1. Install / 安装
pip install clawmeter

# 2. Initialise config / 初始化配置
clawmeter init

# 3. Start background daemon / 启动后台采集
clawmeter start

# 4. Generate a report / 查看用量报告
clawmeter report

# 5. See cost breakdown + optimization tips / 查看成本分析与优化建议
clawmeter cost

Prerequisite: A running OpenClaw instance reachable at ws://127.0.0.1:18789. 前置条件: 一个运行中的 OpenClaw 实例,默认监听 ws://127.0.0.1:18789


📦 Installation / 安装

From PyPI (recommended)

pip install clawmeter

From source / 源码安装

git clone https://github.com/hidearmoon/openclaw-meter
cd openclaw-meter
pip install -e ".[dev]"

Requirements / 环境要求

  • Python 3.10+
  • A running OpenClaw instance
  • No additional services needed / 无需其他服务

⚙️ Configuration / 配置

Run clawmeter init to generate ~/.clawmeter/config.yaml:

# OpenClaw Gateway connection / 网关连接
gateway_url: ws://127.0.0.1:18789
# gateway_token: your_token_here   # if auth is required / 如需认证

# Polling interval (seconds) / 采集间隔(秒)
poll_interval: 30

# Optional log file fallback / 可选日志文件补充数据源
# log_path: ~/.openclaw/logs/openclaw.log

# Storage / 存储路径
database_path: ~/.clawmeter/data.db

# Budget limits / 预算限额
budget:
  monthly_limit_usd: 100.0
  alert_threshold_pct: 80.0   # alert at 80% of limit / 达到 80% 时告警

# Override model pricing (USD per 1M tokens) / 覆盖模型定价(美元/百万 Token)
# model_pricing:
#   my-custom-model:
#     input: 1.0
#     output: 4.0
#     cache_read: 0.1
#     cache_write: 0.0

Environment variable / 环境变量

export CLAWMETER_CONFIG=/path/to/custom/config.yaml

🖥️ CLI Reference / 命令参考

Daemon / 守护进程

clawmeter start          # Start background collection daemon / 启动后台采集守护进程
clawmeter stop           # Stop the daemon / 停止守护进程
clawmeter status         # Show live usage summary + budget health / 实时用量摘要与预算状态

Data collection / 数据采集

clawmeter collect        # Continuous polling (Ctrl-C to stop) / 持续轮询(Ctrl-C 停止)
clawmeter collect --once # Single pass / 单次采集
clawmeter check          # Test gateway connectivity / 测试网关连通性

Reports / 报告

# Usage report / 用量报告
clawmeter report                          # Current month (default) / 本月(默认)
clawmeter report --period daily           # Today / 今天
clawmeter report --period last7           # Last 7 days / 最近 7 天
clawmeter report --date 2026-02           # Specific month / 指定月份
clawmeter report --format json            # Machine-readable / JSON 格式
clawmeter report --format csv             # Spreadsheet-ready / CSV 格式

# Cost breakdown + optimization suggestions / 成本分析与优化建议
clawmeter cost                            # Current month
clawmeter cost --period today             # Today's spend / 今日花费
clawmeter cost --period last30            # Last 30 days / 最近 30 天

# Top-N sessions by spend / 消耗最多的会话 Top N
clawmeter top                             # Top 10 this month
clawmeter top --limit 20 --period week    # Top 20 this week / 本周 Top 20

Budget management / 预算管理

# Add a $100/month global budget / 添加 $100/月 全局预算
clawmeter budget add global --limit 100 --period monthly

# Add a $5/day budget scoped to Claude Opus / Claude Opus 专属 $5/天
clawmeter budget add opus-daily --limit 5 --period daily --model claude-opus-4-6

# List all budgets / 列出所有预算
clawmeter budget list

Sessions & alerts / 会话与告警

clawmeter sessions          # List recently tracked sessions / 最近跟踪的会话
clawmeter alerts            # View unacknowledged alerts / 查看未确认告警
clawmeter alerts --all      # Include acknowledged / 包含已确认

Database maintenance / 数据库维护

clawmeter db info                    # File size + record counts / 文件大小与记录数
clawmeter db prune --keep-days 60    # Delete records older than 60 days / 删除 60 天前的记录

Other / 其他

clawmeter init             # Create default config / 生成默认配置
clawmeter config           # Show / edit config / 查看或编辑配置
clawmeter serve            # Web Dashboard (Phase 2) / Web 面板(Phase 2 占位)
clawmeter --version        # Show version / 显示版本

📊 Sample Output / 输出示例

╭──────────────────────────────────────────────────────────────╮
│                    ClawMeter Status                          │
│  Gateway: ws://127.0.0.1:18789                               │
│  Database: ~/.clawmeter/data.db                              │
╰──────────────────────────────────────────────────────────────╯

                      Usage Summary
╭──────────────┬───────────┬──────────┬────────┬─────────────╮
│ Period       │     Input │   Output │ Cached │  Cost (USD) │
├──────────────┼───────────┼──────────┼────────┼─────────────┤
│ Today        │    45,230 │   12,891 │  8,100 │     $0.5672 │
│ This Month   │   892,441 │  241,320 │ 63,200 │    $12.4481 │
╰──────────────┴───────────┴──────────┴────────┴─────────────╯

                Cost Analysis — by Model
╭──────────────────────┬──────────┬────────────┬─────────────┬──────────╮
│ Model                │ Requests │ Avg Output │  Cost (USD) │  % Total │
├──────────────────────┼──────────┼────────────┼─────────────┼──────────┤
│ claude-sonnet-4-6    │    1,241 │        312 │     $8.1234 │    65.2% │
│ claude-haiku-4-5     │    3,891 │         88 │     $2.9871 │    24.0% │
│ gpt-4o-mini          │      876 │        201 │     $1.3376 │    10.7% │
╰──────────────────────┴──────────┴────────────┴─────────────┴──────────╯

╭──────────────────────────────────────────────────────────────╮
│  💡 Cost Optimization Suggestions — 2 found                  │
│  Potential savings up to $6.50                               │
╰──────────────────────────────────────────────────────────────╯

  1. Downgrade claude-sonnet-4-6 → claude-haiku-4-5
  ┌──────────────────────────────────────────────────────────┐
  │ 1,241 requests average only 88 output tokens — short     │
  │ tasks rarely require frontier-tier reasoning.            │
  │ Estimated savings: ~$6.50   Confidence: high             │
  └──────────────────────────────────────────────────────────┘

🏗️ Architecture / 架构

clawmeter/
├── collector/
│   ├── gateway.py     # WebSocket client — GatewayClient + ReconnectingGatewayClient
│   ├── parser.py      # Usage extraction from messages + log files
│   └── poller.py      # Orchestration (one-shot + continuous modes)
├── storage/
│   ├── schema.py      # SQLite DDL (WAL mode, idempotent migrations)
│   ├── models.py      # Dataclass row models
│   └── repository.py  # Async Repository (ClawMeterDB)
├── analyzer/
│   └── __init__.py    # Multi-dimensional aggregation + cost optimization engine
├── config.py          # YAML config + built-in model pricing (50+ models)
└── cli/
    └── main.py        # Click CLI with rich output (14+ commands)

Data flow / 数据流

OpenClaw Gateway ──WS──► GatewayClient
                               │  sessions/list + sessions/history
                               ▼
                         parser.py ──► UsageRecord (with cost estimate)
                               │
                               ▼
                        ClawMeterDB (SQLite / WAL)
                               │
               ┌───────────────┼───────────────┐
               ▼               ▼               ▼
          analyzer/        Budget check     CLI output
          ModelStats        → Alert          (rich tables,
          ChannelStats        insert          JSON, CSV)
          TimeSeries
          Suggestions

OpenClaw Gateway integration

ClawMeter uses the OpenClaw WebSocket JSON-RPC API:

Method Purpose
sessions/list Enumerate active/recent sessions
sessions/history Per-session message history with responseUsage
ping Connectivity check

Note: ClawMeter handles multiple responseUsage formats for maximum compatibility with different OpenClaw versions.


💰 Built-in Model Pricing / 内置模型定价 (March 2026)

Provider Model Input $/1M Output $/1M Cache Read
Anthropic claude-opus-4-6 $15.00 $75.00 $1.50
Anthropic claude-sonnet-4-6 $3.00 $15.00 $0.30
Anthropic claude-haiku-4-5 $0.80 $4.00 $0.08
OpenAI gpt-4.1 $2.00 $8.00 $0.50
OpenAI gpt-4o $2.50 $10.00 $1.25
OpenAI gpt-4o-mini $0.15 $0.60 $0.075
OpenAI o3 $10.00 $40.00 $2.50
Google gemini-2.0-flash $0.10 $0.40 $0.025
Google gemini-2.0-pro $1.25 $5.00 $0.31
DeepSeek deepseek-chat $0.27 $1.10 $0.07

Override any price in config.yamlmodel_pricing. / 在 config.yamlmodel_pricing 段覆盖任意价格。


🧠 Cost Optimization Engine / 成本优化引擎

The clawmeter cost command runs an automated analysis and surfaces actionable suggestions:

clawmeter cost 命令自动分析用量模式,输出可操作的优化建议:

Rule Trigger Example suggestion
Model downgrade Premium model, avg output < 500 tokens "Switch claude-opus → claude-sonnet, save ~$XX/month"
Prompt caching >50K input tokens, zero cache hits "Enable caching for system prompts, save ~$XX"
Channel anomaly One channel > 3× mean spend "Channel X is 5× average — check for runaway agents"
Wasted cache writes Cache write/read ratio < 10% "Cache entries expire before reuse — group similar prompts"

🗺️ Roadmap / 路线图

Version Status What's included
v0.1 ✅ Released Core pipeline: collector → storage → analyzer → CLI
v0.2 🔜 Planned Webhook/email alert delivery (Slack, Feishu, SMTP)
v0.2 🔜 Planned Web Dashboard (FastAPI + Chart.js, real-time)
v0.3 📋 Backlog Multi-instance monitoring (multiple OpenClaw deployments)
v0.3 📋 Backlog Session-level budget enforcement hooks
v0.4 📋 Backlog Prometheus /metrics endpoint

🤝 Contributing / 贡献指南

Pull requests are welcome! / 欢迎提交 PR!

# Setup dev environment / 设置开发环境
git clone https://github.com/hidearmoon/openclaw-meter
cd openclaw-meter
pip install -e ".[dev]"

# Run tests / 运行测试
pytest tests/ -v

# Lint / 代码检查
ruff check src/ tests/

Please:

  1. Fork the repo and create a feature branch
  2. Keep code ruff-clean and fully type-hinted
  3. Add/update tests for any changed logic
  4. Update CHANGELOG.md

⚠️ Known Limitations / 已知限制

  • No direct rate-limiting: OpenClaw has no external control API. ClawMeter alerts on overages but cannot automatically throttle sessions. 无直接限流能力: OpenClaw 暂无外部控制 API,ClawMeter 能告警但不能自动限流。
  • Gateway API compatibility: Tested against OpenClaw WebSocket conventions as of Q1 2026. Please open an issue if you hit a parsing error. 网关 API 兼容性: 基于 2026 年 Q1 观察到的协议约定测试,如遇解析错误请提 issue。
  • Single-instance: v0.1 assumes one OpenClaw instance. Multi-instance support is planned for v0.3. 单实例: v0.1 仅支持单个 OpenClaw 实例,v0.3 计划支持多实例。

📄 License / 许可证

MIT © OpenClaw Labs


GitHub Topics

openclaw · token-usage · cost-optimization · llm-monitoring · ai-cost-control

About

OpenClaw Token Usage Analytics & Cost Control Platform — real-time spend tracking, budget alerts, and cost optimization for OpenClaw users

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages