Token Use and Costs in OpenClaw

Learn how OpenClaw measures token usage and builds its system prompt. Essential for developers managing API costs and optimizing prompt efficiency.

Read this when

  • Explaining token usage, costs, or context windows
  • Debugging context growth or compaction behavior

OpenClaw measures usage in tokens, not characters. Although tokenization varies by model, most OpenAI style models average roughly 4 characters per token for English text.

How the system prompt is built

Every time it runs, OpenClaw builds its own system prompt. That prompt includes:

  • A tool list with short descriptions
  • A skills list (metadata only; instructions load on demand using read). Native Codex turns receive the compact skills block as turn scoped collaboration developer instructions; other harnesses get it in the normal prompt surface. Bounded by skills.limits.maxSkillsPromptChars, with an optional per agent override at agents.entries.*.skillsLimits.maxSkillsPromptChars.
  • Self update instructions
  • Workspace and bootstrap files (AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, HEARTBEAT.md, BOOTSTRAP.md when new, plus MEMORY.md when present). Large injected files are truncated by agents.defaults.bootstrapMaxChars (default: 20000); total bootstrap injection is limited by agents.defaults.bootstrapTotalMaxChars (default: 60000).
    • Native Codex turns do not paste raw MEMORY.md when memory tools exist for that workspace; instead they receive a small memory pointer in turn scoped collaboration developer instructions and use memory tools as needed. If tools are disabled, memory search is unavailable, or the active workspace differs from the agent memory workspace, MEMORY.md falls back to the normal bounded turn context path.
    • Lowercase root memory.md is never injected. It serves as legacy repair input for openclaw doctor --fix, which migrates it into MEMORY.md.
    • memory/*.md daily files are not part of the normal bootstrap prompt; they remain available on demand through memory tools during ordinary turns. Reset or startup model runs can prepend a one shot startup context block with recent daily memory for that first turn, controlled by agents.defaults.startupContext. Bare chat /new and /reset are acknowledged without invoking the model.
    • Post compaction AGENTS.md excerpts require explicit agents.defaults.compaction.postCompactionSections opt in; plugins can add other context through before_prompt_build.
  • Time (UTC plus user timezone)
  • Reply tags and heartbeat behavior
  • Runtime metadata (host, OS, model, thinking)

See the complete breakdown in System Prompt.

When documenting credentials or auth snippets, follow the Secret Placeholder Conventions to prevent secret scanner false positives in docs only changes.

What counts in the context window

Everything sent to the model counts toward the context limit:

  • System prompt (all sections above)
  • Conversation history (user and assistant messages)
  • Tool calls and their results
  • Attachments and transcripts (images, audio, files)
  • Compaction summaries and pruning artifacts
  • Provider wrappers or safety headers (invisible but still counted)

Runtime heavy surfaces have their own explicit caps under agents.defaults.contextLimits (per agent overrides under agents.entries.*.contextLimits):

KeyPurpose
memoryGetMaxCharsMaximum characters memory_get returns before truncation.
postCompactionMaxCharsMaximum characters retained from AGENTS.md during post compaction refresh.

These are bounded runtime excerpts and injected runtime owned blocks, separate from bootstrap limits, startup context limits, and skills prompt limits.

OpenClaw calculates the live tool result cap from the effective model context window: 16000 chars below 100K tokens, 32000 chars at 100K+ tokens, 64000 chars at 200K+ tokens. The runtime context share guard also limits a single tool result to 30% of the context window.

Large provider windows are not enabled automatically when they materially change cost or latency. For instance, direct OpenAI GPT-5.5 and GPT-5.6 models advertise a 1050000 token total window, but OpenClaw defaults their active runtime budget to 272000 tokens. The opt in 922000 input budget reserves the full 128000 output allowance, and OpenAI applies higher long context pricing to the entire request once input exceeds 272000 tokens. Refer to OpenAI context window defaults.

For images, OpenClaw downscales transcript and tool image payloads before provider calls. Adjust with agents.defaults.imageMaxDimensionPx (default: 1200):

  • Lower values reduce vision token usage and payload size.
  • Higher values preserve more visual detail for OCR and UI heavy screenshots.

For a practical breakdown (per injected file, tools, skills, and system prompt size), use /context list or /context detail. See Context.

How to see current token usage

In chat:

  • /status -> an emoji-enhanced status card that displays the session model, context usage, last response input and output tokens, and an estimated cost when local pricing has been set for the currently active model.
  • /usage off|tokens|full -> attaches a usage footer to every response. This setting persists per session and is stored as responseUsage.
    • /usage reset (also known as inherit, clear, default) removes the session override so it reverts to the configured default.
    • /usage tokens reveals turn token and cache specifics.
    • /usage full shows a compact summary of model, context, and cost details; the estimated cost is only shown when OpenClaw possesses usage metadata and local pricing for the active model. Custom messages.usageTemplate layouts can incorporate token and cache fields.
  • /usage cost -> a local cost summary derived from OpenClaw session logs.

Additional interfaces:

  • TUI/Web TUI: Both /status and /usage are supported.
  • CLI: openclaw status --usage and openclaw channels list display normalized provider quota windows (X% left, not per-response costs). Providers currently using usage windows include Claude (Anthropic), ClawRouter, Copilot (GitHub), DeepSeek, Gemini (Google Gemini CLI), MiniMax, OpenAI, Xiaomi, Xiaomi Token Plan, and z.ai.

Before display, usage surfaces normalize common provider-native field aliases. For OpenAI-family Responses traffic, this includes both input_tokens/output_tokens and prompt_tokens/completion_tokens, so transport-specific field names do not alter /status, /usage, or session summaries. Gemini CLI usage is also normalized: the default stream-json parser reads assistant message events, and stats.cached maps to cacheRead, with stats.input_tokens - stats.cached used when the CLI omits an explicit stats.input field. Legacy JSON overrides still extract reply text from response.

For native OpenAI-family Responses traffic, WebSocket/SSE usage aliases normalize identically, and totals fall back to normalized input plus output when total_tokens is missing or 0.

When the current session snapshot is sparse, /status and session_status can retrieve token and cache counters along with the active runtime model label from the most recent transcript usage log. Existing nonzero live values still take priority over transcript fallback values, and larger prompt-oriented transcript totals can prevail when stored totals are absent or smaller.

Usage authentication for provider quota windows is handled first by provider-specific hooks; if a provider lacks a hook (or the hook cannot resolve a token), OpenClaw falls back to matching OAuth or API-key credentials from auth profiles, environment variables, or configuration.

Assistant transcript entries preserve the same normalized usage shape, including usage.cost when the active model has pricing configured and the provider returns usage metadata. This provides /usage cost and transcript-backed session status with a stable source even after the live runtime state is gone.

OpenClaw maintains provider usage accounting separately from the current context snapshot. Provider usage.total can include cached input, output, and multiple tool-loop model calls, making it useful for cost and telemetry but potentially overstating the live context window. Context displays and diagnostics use the latest prompt snapshot (promptTokens, or the last model call when no prompt snapshot is available) for context.used.

Cost estimation (when shown)

Cost estimates come from your model pricing configuration:

models.providers.<provider>.models[].cost

These figures are in USD per 1M tokens for input, output, cacheRead, and cacheWrite. If pricing is absent, /usage full omits the cost; use /usage tokens or a custom messages.usageTemplate when token and cache details are needed in every reply. Cost display is not restricted to API-key authentication: non-API-key providers like aws-sdk can show estimated costs when their configured model entry includes local pricing and the provider returns usage metadata.

Once sidecars and channels reach the Gateway ready path, OpenClaw starts an optional background pricing bootstrap for configured model references that lack local pricing. This bootstrap retrieves remote OpenRouter and LiteLLM pricing catalogs. Set models.pricing.enabled: false to skip these catalog fetches on offline or restricted networks; explicit models.providers.*.models[].cost entries still drive local cost estimates.

Cache TTL and pruning impact

Provider prompt caching applies only within the cache TTL window. OpenClaw can optionally perform cache-ttl pruning: it prunes the session once the cache TTL expires, then resets the cache window so subsequent requests reuse the freshly cached context instead of recaching the full history. This reduces cache write costs when a session becomes idle beyond the TTL.

Configure this in Gateway configuration and review the behavior details in Session pruning.

Heartbeat can keep the cache warm across idle periods. If your model cache TTL is 1h, setting the heartbeat interval just below that (for example, 55m) can prevent recaching the full prompt, lowering cache write costs.

In multi-agent setups, you can maintain one shared model configuration and adjust cache behavior per agent using agents.entries.*.params.cacheRetention.

For a complete knob-by-knob guide, see Prompt Caching.

With Anthropic API pricing, cache reads are significantly cheaper than input tokens, while cache writes are billed at a higher multiplier. Refer to Anthropic's prompt caching pricing for the latest rates and TTL multipliers: https://docs.anthropic.com/docs/build-with-claude/prompt-caching

Example: keep 1h cache warm with heartbeat

agents:
  defaults:
    model:
      primary: "anthropic/claude-opus-4-6"
    models:
      "anthropic/claude-opus-4-6":
        params:
          cacheRetention: "long"
    heartbeat:
      every: "55m"

Example: mixed traffic with per-agent cache strategy

agents:
  defaults:
    model:
      primary: "anthropic/claude-opus-4-6"
    models:
      "anthropic/claude-opus-4-6":
        params:
          cacheRetention: "long" # default baseline for most agents
  list:
    - id: "research"
      default: true
      heartbeat:
        every: "55m" # keep long cache warm for deep sessions
    - id: "alerts"
      params:
        cacheRetention: "none" # avoid cache writes for bursty notifications

You can override only cacheRetention and keep the rest of the model's defaults unchanged, because agents.entries.*.params is applied on top of the selected model's params.

Anthropic 1M context

Anthropic's 1M context window is used by OpenClaw to size GA-capable Claude 4.x models like Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6. For those models, params.context1m: true is not required.

agents:
  defaults:
    models:
      "anthropic/claude-opus-4-6":
        alias: opus

While older configurations can retain context1m: true, OpenClaw no longer sends Anthropic's retired context-1m-2025-08-07 beta header for this setting, and unsupported older Claude models are not expanded to 1M.

A credential must be eligible for long-context usage. If it is not, Anthropic returns a provider-side rate limit error for that request.

When you authenticate with OAuth or subscription tokens (sk-ant-oat-*), OpenClaw keeps the OAuth-required Anthropic beta headers while removing the retired context-1m-* beta header if it still exists in an older configuration.

Tips for reducing token pressure

  • Long sessions should be summarized using /compact.
  • Trim large tool outputs in your workflows.
  • For screenshot-heavy sessions, lower agents.defaults.imageMaxDimensionPx.
  • Keep skill descriptions short (the skill list is injected into the prompt).
  • For verbose, exploratory work, prefer smaller models.

See Skills for the exact skill list overhead formula.