简介
PaxSwarm 开源的 API 成本守护工具,通过会话级预算追踪与硬限制机制,防止 AI Agent 产生失控的 API 调用费用,为开发者和团队提供可审计的支出管控。
原始描述
API cost guardian for AI agents. Track spending, enforce limits, prevent runaway costs. Essential for any agent making paid API calls.
通过你的 Agent 添加
安装目录:tokenguard/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。
点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。
或者手动安装
包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可;
目录名不用换,也不要把包直接解压到 skills 根目录。
技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。
中文使用说明 来自收录源
核心用法
TokenGuard 是一款专为 AI Agent 设计的本地化 API 成本管控工具。其核心工作流围绕"预算前置检查-执行-成本记录"的闭环展开:用户通过 set 命令设定会话预算上限(默认 $20),在发起昂贵 API 调用前使用 check 命令进行预检,若预算充足则执行调用,完成后通过 log 记录实际支出。系统支持 extend 动态追加预算、、override 单次绕过限制等灵活机制,并提供完整的 history 审计追踪与 JSON 格式 export 导出功能。所有数据持久化于 ~/.tokenguard// 目录,按日自动重置或手动触发 reset。
显著优点
零依赖纯本地架构:无需网络连接、无外部服务依赖,完全基于 Python 标准库实现,部署成本极低。 工程化集成友好:提供标准化退出码(0/1/2)与命令行接口,可无缝嵌入 Shell 脚本或 Python 子进程调用,示例代码即拿即用。 精细化成本感知:内置主流模型(Claude/GPT 系列)的每百万 token 定价参考表,辅助用户快速估算调用成本。 防御性设计:80% 预算阈值预警、硬限制阻断、单次绕过需显式声明,多重机制防止意外超支。 数据主权可控:MIT 开源协议,数据文件为纯 JSON 格式,用户完全掌握审计轨迹。
潜在缺点与局限性
单机会话隔离:预算状态绑定本地文件系统,无法在分布式多机部署的 Agent 集群间同步,多实例场景需自行解决状态一致性。 精度与币种局限:仅支持美元计价,最小单位为分,对需要多币种或更精细计费的场景覆盖不足。 无实时价格同步:内置定价表为静态参考,无法自动跟随厂商调价更新,长期使用可能产生估算偏差。 覆盖机制的信任假设:override 命令虽需显式调用,但若 Agent 本身被恶意控制,仍可能成为绕过成本管控的通道。 缺乏可视化报表:仅提供命令行表格与原始 JSON 导出,无 Web 仪表盘或趋势分析能力。
适合的目标群体
独立开发者与小型团队:预算敏感、需要快速为个人项目或原型系统添加成本护栏。 AI Agent 框架构建者:需要将成本管控作为基础设施组件集成到更复杂的 Agent 编排系统中。 教育与实验场景:教学演示、学生作业、研究原型等需要"保险丝"机制防止意外高额账单的环境。 CI/CD 自动化测试:在持续集成流水线中限制测试用例的 API 调用成本,防止配置错误导致费用失控。
使用风险
数据持久化风险:TOKENGUARD_DIR 环境变量允许自定义存储路径,若指向系统关键目录或共享存储,可能引发权限冲突或数据泄露。 状态丢失风险:会话数据存储于本地 JSON 文件,磁盘损坏、误删除或容器重启(未挂载持久卷)将导致历史记录与预算状态丢失。 估算误差累积:check 命令依赖用户提供的预估成本,若实际调用因 token 消耗超预期而超支,系统仅在 log 阶段发现,此时费用已产生。 并发写入冲突:多进程同时操作同一 session.json 文件时存在竞态条件风险,极端情况下可能导致支出记录丢失或预算计算错误。 覆盖机制滥用:虽然 override 设计为单次有效,但频繁使用或脚本自动化调用可能削弱预算纪律,形成"狼来了"效应。
技能正文
name: tokenguard
version: 1.0.0
description: API cost guardian for AI agents. Track spending, enforce limits, prevent runaway costs. Essential for any agent making paid API calls.
author: PaxSwarm
license: MIT
homepage: https://clawhub.com/skills/tokenguard
keywords: [cost, budget, spending, limit, api, tokens, guard, monitor]
triggers: ["cost limit", "spending limit", "budget", "how much spent", "tokenguard", "api cost"]
🛡️ TokenGuard — API Cost Guardian
Protect your wallet from runaway API costs.
TokenGuard tracks your agent's spending per session, enforces configurable limits, and alerts you before you blow your budget.
Why TokenGuard?
AI agents can rack up serious API costs fast. One runaway loop = hundreds of dollars. TokenGuard gives you:
- Session-based tracking — Costs reset daily (or on demand)
- Hard limits — Actions blocked when budget exceeded
- Pre-flight checks — Verify budget BEFORE expensive calls
- Override controls — Extend limits or bypass when needed
- Full audit trail — Every cost logged with timestamps
Installation
clawhub install tokenguard
clawhub install tokenguard
Or manually:
mkdir -p ~/.openclaw/workspace/skills/tokenguard
# Copy SKILL.md and scripts/tokenguard.py
chmod +x scripts/tokenguard.py
Quick Start
# Check current status
python3 scripts/tokenguard.py status
# Set a $20 limit
python3 scripts/tokenguard.py set 20
# Before an expensive call, check budget
python3 scripts/tokenguard.py check 5.00
# After the call, log actual cost
python3 scripts/tokenguard.py log 4.23 "Claude Sonnet - code review"
# View spending history
python3 scripts/tokenguard.py history
Commands
Command
Description
status
Show current limit, spent, remaining
set <amount>
Set spending limit (e.g., set 50)
check <cost>
Check if estimated cost fits budget
log <amount> [desc]
Log a cost after API call
reset
Clear session spending
history
Show all logged entries
extend <amount>
Add to current limit
override
One-time bypass for next check
export [--full]
Export data as JSON
Exit Codes
0 — Success / within budget
1 — Budget exceeded (check command)
2 — Limit exceeded after logging
# Check current status
python3 scripts/tokenguard.py status
# Set a $20 limit
python3 scripts/tokenguard.py set 20
# Before an expensive call, check budget
python3 scripts/tokenguard.py check 5.00
# After the call, log actual cost
python3 scripts/tokenguard.py log 4.23 "Claude Sonnet - code review"
# View spending history
python3 scripts/tokenguard.py history
| Command | Description |
|---|---|
status |
Show current limit, spent, remaining |
set <amount> |
Set spending limit (e.g., set 50) |
check <cost> |
Check if estimated cost fits budget |
log <amount> [desc] |
Log a cost after API call |
reset |
Clear session spending |
history |
Show all logged entries |
extend <amount> |
Add to current limit |
override |
One-time bypass for next check |
export [--full] |
Export data as JSON |
Exit Codes
0 — Success / within budget
1 — Budget exceeded (check command)
2 — Limit exceeded after logging
0 — Success / within budget1 — Budget exceeded (check command)2 — Limit exceeded after loggingUse exit codes in scripts:
if python3 scripts/tokenguard.py check 10.00; then
# proceed with expensive operation
else
echo "Over budget, skipping"
fi
Budget Exceeded Alert
When a check would exceed your limit:
🚫 BUDGET EXCEEDED
╭──────────────────────────────────────────╮
│ Current spent: $ 4.0000 │
│ This action: $ 10.0000 │
│ Would total: $ 14.0000 │
│ Limit: $ 10.00 │
│ Over by: $ 4.0000 │
╰──────────────────────────────────────────╯
💡 Options:
tokenguard extend 5 # Add to limit
tokenguard set <amt> # Set new limit
tokenguard reset # Clear session
tokenguard override # One-time bypass
Integration Pattern
For agents using paid APIs:
import subprocess
import sys
def check_budget(estimated_cost: float) -> bool:
"""Check if action fits budget."""
result = subprocess.run(
["python3", "scripts/tokenguard.py", "check", str(estimated_cost)],
capture_output=True
)
return result.returncode == 0
def log_cost(amount: float, description: str):
"""Log actual cost after API call."""
subprocess.run([
"python3", "scripts/tokenguard.py", "log",
str(amount), description
])
# Before expensive operation
if not check_budget(5.00):
print("Budget exceeded, asking user...")
sys.exit(1)
# Make API call
response = call_expensive_api()
# Log actual cost
log_cost(4.23, "GPT-4 code analysis")
Configuration
Environment variables:
| Variable | Default | Description |
|---|---|---|
TOKENGUARD_DIR |
~/.tokenguard |
Storage directory |
TOKENGUARD_DEFAULT_LIMIT |
20.0 |
Default limit in USD |
TOKENGUARD_WARNING_PCT |
0.8 |
Warning threshold (0-1) |
Cost Reference
Common API pricing (per 1M tokens):
| Model | Input | Output |
|---|---|---|
| Claude 3.5 Sonnet | $3 | $15 |
| Claude 3 Haiku | $0.25 | $1.25 |
| GPT-4o | $2.50 | $10 |
| GPT-4o-mini | $0.15 | $0.60 |
| GPT-4-turbo | $10 | $30 |
Rule of thumb: 1000 tokens ≈ 750 words
Storage
Data stored in ~/.tokenguard/ (or TOKENGUARD_DIR):
limit.json— Current limit configurationsession.json— Today's spending + entriesoverride.flag— One-time bypass flag
Best Practices
- Set realistic limits — Start with $10-20 for development
- Check before expensive calls — Always
check before big operations
- Log everything — Even small costs add up
- Use extend, not reset — Keep audit trail intact
- Monitor warnings — 80% threshold = time to evaluate
Changelog
v1.0.0
- Initial release
- Core commands: status, set, check, log, reset, history, extend, override
- Environment variable configuration
- JSON export for integrations
- Daily auto-reset
check before big operationsv1.0.0
Built by PaxSwarm — a murmuration-class swarm intelligence
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。