> For the complete documentation index, see [llms.txt](https://yeasy.gitbook.io/openclaw_guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yeasy.gitbook.io/openclaw_guide/di-si-bu-fen-shi-zhan-yu-you-hua-shen-du-zhi-nan/14_performance_cost/14.3_usage_budget.md).

# 14.3 OpenClaw 的用量观测与预算控制

本节介绍如何通过 OpenClaw 内置命令、Dashboard 的 `Control -> Usage` 页面实现**可刷新/近实时用量观测**，并结合 provider 控制台、外部监控或自定义插件做**预算治理**，防止成本失控。

## 14.3.1 核心观测命令

OpenClaw 提供多个内置命令用于近实时观测与诊断。若你更习惯图形化视图，当前 Dashboard 也提供 `Control -> Usage` 页面，可按时间范围查看 Token、成本与会话分布；该页面通常依赖刷新/缓存重建，短时间内可能显示 stale 或 rebuilding 状态。如果你已经在对话里通过 `/usage cost` 发现异常，再回到 Usage 页做系统级排查通常更高效。

### `/status` 命令

查看当前会话的模型、上下文、最近一次响应用量，以及在可获得价格信息时估算出的最近回复成本。它不是全局日预算报表。

```bash
/status
```

输出示例：

```
Session: main
Model: anthropic/claude-sonnet-4-6
Context: 64K / 1M
Last response: input 12,340 tokens, output 820 tokens
Estimated last-reply cost: $0.049
```

### `/usage cost` 命令

聊天会话内的本地成本摘要，适合快速看最近一段时间的费用分布。若需要 CLI 视角的 transcript-backed session 成本摘要，用 `openclaw gateway usage-cost`；`openclaw status --usage` 更适合查看 provider 配额/窗口快照，不应当成完整成本趋势报表。若需要图形化视图，可对照 Dashboard 的 `Control -> Usage` 页面。

```bash
/usage cost
```

输出示例：

```
💸 Usage cost
Session $0.049 · 13.2K tokens
Today $3.41
Last 30d $57.80
```

### `/compact` 命令

手动触发上下文压缩，回收 Token 预算。

```bash
/compact Focus on the API design decisions and unresolved tasks
```

输出：

```
压缩请求已发送；目标保留窗口请通过 agents.defaults.compaction.keepRecentTokens 调整。
```

## 14.3.2 预算配置与告警

### 全局预算限制

> \[!CAUTION] 下列配置示例反映治理架构，不等于当前 OpenClaw 已公开的 `openclaw.json` schema。生产硬阈值优先放在 provider billing / quota、外部监控或自定义插件里实现。

```json
{
  "budget": {
    "daily": {
      "tokens": 1000000,
      "cost": 500,
      "requests": 100000
    },
    "monthly": {
      "tokens": 30000000,
      "cost": 15000
    }
  },
  "alerts": {
    "enabled": true,
    "thresholds": {
      "dailyTokens": 0.8,
      "dailyCost": 0.9,
      "monthlyTokens": 0.75
    },
    "channels": ["email", "slack"]
  }
}
```

**配置解读**：

* 日预算：100 万 Token 或 $500（先达到的限制）
* 告警触发条件：日 Token 达 80%、日成本达 90%、月 Token 达 75%
* 用 `/status` 与 `/usage cost` 获取当前会话的本地成本摘要；用 `openclaw gateway usage-cost` 查看 transcript-backed CLI 成本摘要；用 `openclaw status --usage` 查看 provider 配额窗口快照。
* 用 provider 自带 quota / billing 控制台设硬预算。
* 用 Prometheus、Grafana、Loki、外部 Webhook 或自定义插件做阈值告警。

### 按 Agent 预算分配

同理，下面更适合表达“按 Agent 做预算配额”的目标，而不是当前实例已验证通过的字段名；若要落地，应由 provider 限额、入口限流、监控告警或插件 hook 执行。

```json
{
  "agents": {
    "support_agent": {
      "budget": {
        "dailyTokens": 500000,
        "dailyCost": 250,
        "enforceLimit": true
      }
    },
    "research_agent": {
      "budget": {
        "dailyTokens": 200000,
        "dailyCost": 100,
        "enforceLimit": false
      }
    }
  }
}
```

## 14.3.3 上下文管理机制

### 自动压缩与清理

```json
{
  "agents": {
    "defaults": {
      "compaction": {
        "mode": "safeguard",
        "keepRecentTokens": 5000,
        "model": "<provider/low-cost-model>",
        "truncateAfterCompaction": true,
        "maxActiveTranscriptBytes": 10485760
      }
    }
  },
  "session": {
    "maintenance": {
      "pruneAfter": "30d"
    }
  }
}
```

参数语义见字段名与本节上下文说明。

### 会话重置与清理

```bash
# 主动重置某个会话（清空上下文，开始新对话）
/new

# 批量清理过期会话
openclaw sessions cleanup --dry-run
# （使用 --dry-run 预览要删除的内容，不实际删除）

# 实际执行清理
openclaw sessions cleanup --enforce
```

## 14.3.4 成本控制的工程策略

### 策略 1：分层模型选择

当前公开配置面不提供 `routing.complexity_detection` 这种通用自动复杂度路由。更稳妥的做法是按入口、agent 或显式子任务目标拆分模型，把低成本与高质量路径变成可审计的配置：

```jsonc
{
  "agents": {
    "list": [
      {
        "id": "support_fast",
        "model": "<provider/low-cost-model>"
      },
      {
        "id": "support_deep",
        "model": "anthropic/claude-sonnet-4-6"
      }
    ]
  }
}
```

入口侧可通过 channel bindings、明确的 agent 选择或业务网关把简单请求送到 `support_fast`，把复杂分析送到 `support_deep`。这样同样能降低平均成本，同时保留可解释的路由证据。

### 策略 2：工具缓存与重复消除

当前没有通用内建 `tools.caching` 配置。对重复工具调用的缓存应放在自定义插件、业务 API 网关或外部缓存层中；同时明确排除发邮件、创建工单等有副作用工具：

```jsonc
{
  "// plugin_cache_policy": "插件内部示意，不是 OpenClaw 内建 tools.caching schema",
  "ttl": 3600,
  "keyStrategy": "hash(tool, args)",
  "excludeTools": ["send_email", "create_ticket"]
}
```

## 14.3.5 成本异常检测与预警

通过日志、会话用量与监控实现异常消费告警。下面是外部监控或插件治理的伪配置示例，不是内置 schema：

```json
{
  "anomalyDetection": {
    "enabled": true,
    "baselines": {
      "averageDailyCost": 500,
      "stdDeviation": 100
    },
    "triggers": [
      {
        "name": "spike_detection",
        "condition": "dailyCost > baseline + 3 * stdDev",
        "action": "alert + pause_non_critical"
      },
      {
        "name": "model_drift",
        "condition": "error_rate > 5%",
        "action": "notify_admin"
      }
    ]
  }
}
```

## 14.3.6 用量观测与预算控制检查清单

部署 OpenClaw 时，确保完成以下配置：

* **可见性**：运行 `/usage cost` 查看会话摘要；用 `/usage full` 或 `/usage tokens` 控制会话页脚；用 `openclaw gateway usage-cost` 查看 CLI 成本摘要；用 `openclaw status --usage` 只检查 provider 配额窗口
* **预算控制**：在 provider 控制台或外部监控里设硬阈值
* **自动压缩**：根据实际模型窗口配置 `agents.defaults.compaction`
* **会话清理**：使用 `openclaw sessions cleanup --dry-run/--enforce` 并配置 `session.maintenance.pruneAfter` / `maxEntries`
* **成本分析**：每周检查 `openclaw gateway usage-cost` 和 Dashboard Usage，并结合会话内 `/usage cost` 样本回看趋势；`status --usage` 用于补充 provider quota/window 证据
* **模型分层**：按 agent / 入口拆分模型，而不是依赖未文档化的自动复杂度路由

完成以上配置，可实现**可观、可控、可优化**的成本管理体系。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yeasy.gitbook.io/openclaw_guide/di-si-bu-fen-shi-zhan-yu-you-hua-shen-du-zhi-nan/14_performance_cost/14.3_usage_budget.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
