Skip to content

About

A filter plugin for Open WebUI that shows detailed token, context, timing and cost statistics below each AI response: token counts (input/output/total, reasoning, cached, audio), context-window utilization, generation time, tokens/second and message/chat cost.

Resources

Contributing

Stars

44 stars

Watchers

2 watching

Forks

Repository files navigation

Token Usage & Cost Display

CI Open WebUI 0.9.0+ License: MIT

A filter plugin for Open WebUI that shows detailed token, context, timing and cost statistics below each AI response - token counts (input/output/total, running chat total, reasoning, cached, audio), context-window utilization, generation time, tokens/second and message/chat cost.

Recommended in the official Open WebUI documentation - see the Community Plugins catalog. Install it from the community store post or straight from this repo.

Token usage & cost stats line under an Open WebUI response

⬆︎ 8,204 · ⬇︎ 586 · Σ 8,790 · 🧮 31,460 · 🧠 412 · 💾 4,096 · 📐 8.8k/200k (4%) · ⏱ 3.1s · ⚡ 189.0 t/s · 💰 $0.0284 · 💰Σ $0.1120

Each metric only appears when it has a value, so the line stays clean for models that don't report detailed breakdowns.

Installation

  1. In Open WebUI, open Admin Panel → Functions (or Workspace → Functions).
  2. Click + to add a new function.
  3. Copy the entire contents of usage_display.py and paste it in.
  4. Save, then enable the filter for the models you want it on.

No pip install, no dependencies to add. tiktoken is optional - it's only used to estimate tokens when a provider reports no usage; the plugin loads fine without it.

Works on Open WebUI 0.9.0+. It's built for the 0.10.x data model (structured output + normalized usage) but degrades gracefully on 0.9.x - the only limitation there is provider-reported cost in auto mode, which needs 0.10.0+ (use estimate on older versions).

What it displays

  • Input / output / total token counts. Marked ≈ when Open WebUI (0.12.5+) reports that a request of the turn sent no token count, so the real numbers are higher
  • Running chat token total (🧮) - the sum of every response's Σ in the chat, the token twin of 💰Σ (handy for local/free models with no cost). The model re-reads the history each turn, so it counts processed tokens and grows much faster than the context window
  • Reasoning / thinking tokens - OpenAI o3/o4-mini & GPT-5, Gemini thinking, DeepSeek R1, Claude thinking, etc. (read from both the Chat Completions and the newer Responses API shapes)
  • Cached prompt tokens - OpenAI prompt cache and Anthropic cache_read / cache_creation (Anthropic cache is correctly counted as additional to input)
  • Context-window utilization - how much of the model's window you've used, e.g. 8.8k/200k (4%); the icon turns 🟠 at 30% and 🔴 at 70% by default (configurable). On a response with tool calls (several requests to the model) it shows the last request, while ⬆︎/Σ/cost add up all of them - so ⬆︎ can be far larger than 📐 (Open WebUI 0.11+; on 0.10.x 📐 is the sum too). Marked ≈ when it is an estimate (see Notes & limitations). This is the model's real window, not Open WebUI's own context indicator, which divides by its compaction threshold (80k by default) and leaves Anthropic cache out, so the two percentages differ by design
  • Generation time and tokens/second
  • Native prefill speed (⏩ prefill … t/s) for prompt processing, separately from output speed
  • Truncation marker (✂️ truncated, next to ⬇︎) - shown only when the model stopped because it hit its output-token limit, so a cut-off answer is not mistaken for a complete one. Needs Open WebUI 0.12.0+ and a Chat Completions (OpenAI-compatible) or Ollama model, or a pipe that passes such a response through. For the Responses API it needs Open WebUI 0.13.0+ (non-streaming) or 0.13.1+ (streaming); a Responses stream that stopped on a content filter or failed is flagged too, because Open WebUI reports all three the same way
  • Cost - the provider's own reported cost when available (OpenRouter, LiteLLM, ...), or an optional estimate from models.dev prices (always marked ≈); shown per message (💰) and as a running chat total (💰Σ)
  • OpenRouter balance (💳, off by default) - what is left on your OpenRouter account, asked from OpenRouter after each response; see OpenRouter balance
  • Audio tokens (off by default) and the base model name for workspace models

How it works

The filter reads Open WebUI's normalized usage attached to the response, so it works consistently across providers and response types:

  • Providers: OpenAI (Chat Completions and Responses API), Anthropic, Google Gemini, Ollama, llama.cpp, and any OpenAI-compatible endpoint.
  • Token counts come straight from the reported usage. When a provider reports no usage, the plugin falls back to tiktoken estimation over the response text.
  • Timing / tokens-per-second prefer the provider's own numbers where available (Ollama eval_duration, llama.cpp timings). Otherwise a wall-clock measurement is shown, prefixed with ~ to indicate it's approximate. On Open WebUI 0.11.2+ it starts at the first request to the model, so time spent on RAG and web search before it is left out; tools that run between requests are counted. Older versions start it when the message is sent.

Prompt-processing speed (prefill)

When native prompt timing is available, the filter shows a separate field such as ⏩ prefill 3,056 t/s. Toggle it with show_prefill_tokens_per_second (on by default) and reorder it with the prefill key in display_order.

  • llama.cpp: reads prompt_n / prompt_ms, or prompt_per_second.
  • vLLM streamed Chat Completions: start vLLM with --enable-per-request-metrics --enable-prompt-tokens-details and enable the model's Usage capability in Open WebUI. The stream hook captures its native timing in per-request metadata before Open WebUI drops the top-level metrics object; response chunks and usage stay untouched. The tested vLLM version reports prefill as scheduling-to-first-token time, excluding queue wait. The token count excludes cache hits.

This is a per-call measurement, not the server's interval-averaged prompt throughput. For a turn with tools, it describes the last model call, using that call's token count and duration together. Missing/invalid timing, unknown vLLM cache counts, and fully cached prompts hide the field. The request hook clears timing before each model call, including calls that send no usage at all. Input counts are never divided by full response wall time to invent a prefill rate. vLLM non-streaming responses currently do not preserve their top-level metrics into outlet usage, so that path does not show prefill speed. Other providers continue to show their existing statistics unchanged. Ollama prefill is deliberately hidden: its prompt count includes cached tokens, but Open WebUI omits the separate cached count and computes its own inflated prompt_token/s. That numerator cannot safely be paired with the duration for newly processed tokens. Ollama output-speed and other statistics remain unchanged.

prefill_min_tokens defaults to 64 newly processed tokens: smaller prefills mostly measure fixed overhead. Set it to 0 to disable the threshold. A native rate-only report without a token count is unaffected. Rates at or above 1000 t/s omit decimal places; smaller rates keep one. The metadata and stream ordering were verified against Open WebUI 0.13.0 and 0.13.3; native vLLM timing semantics were checked with 0.33.0rc1. Older supported versions still load the filter; without the shared hook metadata, vLLM prefill stays hidden.

Context-window detection

The context window size is resolved in this order:

  1. Manual override valve (if set)
  2. num_ctx captured from the request (Ollama / local models)
  3. Your context_size_map - an explicit user override, so it wins over the automatic sources below
  4. The running window, asked through the model's own Open WebUI connection - automatic, for llama-swap and a llama.cpp router only (detected from the model listing, so cloud providers are never asked). The plugin reuses that connection's URL, API key and prefix - nothing to configure. llama-swap: /running must show the model loaded, then /props?model= reports the real window, including one picked by llama.cpp's --fit; llama.cpp router: /props?model=&autoload=false. A model that is not loaded is never asked, so a probe cannot trigger a model swap
  5. What the serving backend reports for the model - automatic, no network: llama.cpp (builds since May 2026) and llama-swap (with capabilities.context set) list the running window as meta.n_ctx in /v1/models, vLLM as max_model_len, and Open WebUI hands that listing to the plugin. This is your server's real --ctx-size, not the model's trained maximum
  6. llama.cpp / llama-swap probe - optional, opt-in via URL valves, for backends not reached through an Open WebUI connection; asks llama.cpp /v1/models (then /props on older builds) or llama-swap /running (then /props?model= for a loaded model), and wins over the tables only when the row matches the called model's id
  7. Live models.dev lookup - optional, opt-in; fetches current sizes and caches them (default off)
  8. Built-in table - from models.dev, refreshed before every release, covering the popular OpenAI / Anthropic / Gemini / Llama / DeepSeek / Grok / Mistral / Qwen / Kimi / GLM / MiniMax / Cohere families
  9. A probed backend's only running model, when its id differs from the called one (an alias) - last, because with a cloud model called it would be another model's window

Workspace models resolve via their base model. For a custom model / "agent" built on a base model, matching (context size and cost) uses the model's base_model_id - the real underlying LLM - not your custom model id. So a single context_size_map entry keyed on the base model covers every agent built on it.

Cost

Cost has three modes, set by the cost_mode valve:

  1. auto (default) - show cost only when your provider or proxy reports it in the usage payload (e.g. OpenRouter's usage.cost, a LiteLLM proxy). Nothing is fetched or estimated - this is always the real, billed number.
  2. estimate - additionally approximate the cost from models.dev prices whenever the provider reports none. Estimates are always marked ≈.
  3. off - never show, compute or fetch anything cost-related.

In estimate mode the price is resolved as: your manual price_map valve → live models.dev api.json (per-provider prices, cached ~24h) → a built-in offline price table. Cached and reasoning tokens are priced correctly.

  • price_map matches any part of the model id ({"deepseek": {...}} prices every DeepSeek model).
  • models.dev and the built-in table match only the model's own id, also behind a provider prefix (openai/gpt-6.1-terra, a connection prefix openai.gpt-6.1-terra, au.anthropic.claude-opus-4-8). A related model is a different price, so an id they don't list (a dated snapshot such as gpt-6.1-terra-2026-10-01, a -fast variant) gets no estimate rather than its neighbour's price - add it to price_map.
  • The built-in table is rebuilt from models.dev before every release and holds only the models the vendors themselves sell that came out in the last 4 months. It is there for when models.dev cannot be reached; older models are priced by models.dev or your price_map.
  • If a chat has a response the plugin could not price, the chat total 💰Σ is marked ≈: it is too low.

Estimates are approximate on purpose. models.dev lists published per-provider prices; your real bill can differ, sometimes by a large multiple (gateways route the same model id to different upstream providers at different prices, apply cache/tier/long-context adjustments a static table can't see). When you need the exact figure, use a provider/proxy that reports cost in usage - auto mode is then the authoritative billed number.

Does the cost include tool / function / MCP calls?

Yes - for the tools Open WebUI runs itself. A tool / function / MCP call is just extra tokens across several LLM round-trips, and Open WebUI sums the reported cost across every round of a multi-round tool turn. What no client-side display can capture is a surcharge the provider charges on top of tokens and does not put into usage.cost - e.g. a gateway's own server-side web search, or a BYOK engine billed outside the generation. Turn on debug_mode to see a web_search hint and the provider's cost_details split.

OpenRouter balance

Turn on show_balance to see the remaining OpenRouter account balance (💳 $17.05, or -$3.10 when the account is below zero) right after the chat cost. It is the account's total_credits - total_usage from OpenRouter's GET /api/v1/credits.

  • No key to configure for a model served through an Open WebUI connection to openrouter.ai: the plugin reuses that connection's key and sends it to https://openrouter.ai/api/v1/credits and nowhere else. Models on other connections are never asked about. Only a bearer-auth connection has a key to reuse; for a session/OAuth one, set openrouter_api_key.
  • openrouter_api_key - an optional key that replaces the connection's. An ordinary API key is enough: OpenRouter's docs say a management key is required, but any key of the account gets the same numbers (checked 2026-11-03). Don't use a management key - it can create and delete every key on the account. Valves are not a safe place for a key: the field is masked on screen, but every Open WebUI admin can read it back and any other function or tool on the server can read it. Use it at your own risk.
  • Admins only by default. It is the account owner's money, and the stats line stays in the chat history and in shared chats. balance_for_all_users shows it to everyone.
  • OpenRouter behind a proxy (e.g. LiteLLM): the connection is not openrouter.ai, so set openrouter_api_key and balance_on_every_model - the balance then appears under every model's responses.
  • Asked on every response, not cached, so consecutive messages never show a frozen number. The stats line waits for the answer (up to 2 s). OpenRouter settles a charge shortly after a response ends, so the balance may not include the message it is shown under yet.

Configuration

  • Every metric can be toggled on/off via admin Valves; users can disable the whole display via UserValves.
  • Metric order is configurable via the admin display_order valve (comma-separated keys).
  • Line appearance is configurable: separator, icon_style (emoji / simple monochrome / off bare values), and compact_numbers (abbreviate token counters as k/M).
  • Context detection: manual size override, a custom {"model-substring": tokens} map, the live models.dev fetch toggle, and optional llama.cpp / llama-swap URLs (the size a backend advertises is read automatically).
  • Cost: cost_mode, a running chat-total toggle, a cost_min_display threshold, a manual price_map, and the live models.dev price-fetch toggle.
  • OpenRouter balance: show_balance, openrouter_api_key, balance_for_all_users, balance_on_every_model.

Troubleshooting

Turn on the debug_mode valve and open the "Token Usage & Cost Display - Debug info" source under the message (also mirrored to the server log). Its cost_debug, context_debug, model and valves blocks name the exact broken link.

  • Nothing shows at all, and debug_mode prints nothing to the server log either. The filter never ran. Check that the function is enabled and either global or attached to the model, and that Functions are not switched off for the whole server: ENABLE_FUNCTIONS=false (Open WebUI 0.12.0+) or the master switch ENABLE_PLUGINS=false turns every filter off.
  • Nothing shows below the response, but debug_mode prints a full payload with correct tokens to the server log. The plugin ran fine - Open WebUI is hiding the line. Its frontend renders the status line only when the model's Status Updates capability is on, and the debug panel only when Citations is on (Workspace → Models → your model → Capabilities). This hits workspace/"agent" models, which store an explicit capability set; plain connection models default to on. The debug payload's model.capabilities shows the model's status_updates, citations and usage switches (null = not set, Open WebUI's default applies).
  • The line shows, then another one replaces it (or it vanishes). Open WebUI shows only the latest status of a message. Another filter with a higher priority that sends its own status after this one - even a hidden one - takes that place. Raise this plugin's priority valve above it.
  • Nothing shows below the response (no tokens). The provider returned no usage. In streaming, most OpenAI-compatible endpoints only send a usage chunk when asked - enable the model's Usage capability (Workspace → Models → your model → Capabilities → Usage). Behind LiteLLM, set general_settings: { always_include_stream_usage: true }.
  • Tokens show but cost is blank in auto mode. In auto, cost appears only when the provider/proxy reports it inside the response body usage. OpenAI, Anthropic and Google never do on a direct connection - use cost_mode: estimate for them. A LiteLLM proxy returns cost in the x-litellm-response-cost HTTP header by default, which Open WebUI does not read - move it into the body with litellm_settings: { include_cost_in_streaming_usage: true }, or switch to cost_mode: estimate.
  • Context shows the model's maximum (e.g. 131.1k for Qwen3), not your llama.cpp --ctx-size. context_debug.source is static_table or modelsdev: the backend did not advertise its window. Behind llama-swap or a llama.cpp router the connection probe needs the model listed through Open WebUI's connection to it (a connection restricted to hand-typed model ids has no listing to detect it from) and bearer or no auth. Otherwise update llama.cpp (the meta.n_ctx field in /v1/models appeared in May 2026) and refresh Open WebUI's model list, set capabilities.context in llama-swap, set the llamacpp_url / llama_swap_url valve, or add a context_size_map entry. model.backend_context in the debug payload shows the running (n_ctx) and trained (n_ctx_train) windows the listing carries.
  • show_balance is on but no 💳. The debug payload's balance.status says why: admins_only (you are not an admin), not_openrouter (the model's connection is not openrouter.ai - see the proxy setup above), no_key (the connection has no bearer key and openrouter_api_key is empty), or OpenRouter's own refusal as error <code>: <message>. balance.key_source shows whether the connection's key or the valve was used; the key itself is never in the payload.
  • estimate cost is blank / context % missing. The model id matched no price/context entry (common when Open WebUI exposes a display name like Anthropic - Opus). Add a price_map / context_size_map keyed to a substring of the id, or use a canonical id. For a workspace model, key the map on the base model. cost_debug.price.source: none with cost_debug.modelsdev.status other than ok means the models.dev download failed (http 503, error: TimeoutError, aiohttp_unavailable): check that the server can reach https://models.dev. context_debug.modelsdev does the same for the context lookup.

Notes & limitations

  • For providers that don't report a generation duration (OpenAI, Anthropic), time and t/s are wall-clock, marked ~; local providers (Ollama, llama.cpp) report real generation time.
  • The chat totals (🧮, 💰Σ) are summed from each past response's stored usage. Temporary chats, side chats (/side, /btw, Open WebUI 0.13.0+) and API requests without a chat id don't pass that history usage to filters, so there both totals equal the current message and are hidden.
  • Open WebUI 0.13.0 can compact a long chat more cheaply by replaying it to the provider's prompt cache, but only for models with no filter function attached. On a model with this plugin (or any other filter) compaction works as in 0.12.x. Open WebUI decides this, the plugin cannot change it.
  • When Open WebUI (0.12.5+) reports that a request of the turn sent no token count (incomplete in the usage), every token number of that response is marked ≈ (⬆︎, ⬇︎, Σ, 📐, and 🧮 for the rest of the chat): the real counts are higher.
  • On Open WebUI 0.12.5+, a response with tool calls whose usage comes in Anthropic's own format (from a pipe or a proxy that passes it through; LiteLLM and OpenRouter convert it) gets its cache summed over all requests of the turn, and no per-request value is left. 📐 then adds the average cache per request and is marked ≈; it runs a little low, as later requests read a longer cached prefix. Open WebUI older than 0.11.2 gives no request count, so there 📐 keeps the sum (too high) with ≈.
  • In multi-round tool turns, Open WebUI only carries the last round's timing fields (Ollama, llama.cpp), so those can reflect the final round rather than the whole turn. The same holds for the truncation marker: it reflects the last request of the turn.
  • With debug_mode on, the debug source (valves snapshot with secrets masked, balance) is sent to everyone in a shared chat and kept in share links, like the stats line itself. Open WebUI's source window cuts text above 10,000 characters behind a "Show all" button (large price_map / context_size_map can get there); the server log copy is always complete.
  • In a Realtime voice call (Open WebUI 0.12.0+), the replies the voice model speaks on its own never pass through filters, so they get no stats line; the questions it hands to the chat model are ordinary responses and do.
  • Estimated cost (≈) is a ballpark from published models.dev prices, not your invoice. Provider-reported cost (auto mode) is exact.

Links

Contributing

See CONTRIBUTING.md. In short: install uv, run make install-dev, then make pre-commit (ruff + mypy strict + pytest, coverage ≥ 95%).

License

MIT

About

A filter plugin for Open WebUI that shows detailed token, context, timing and cost statistics below each AI response: token counts (input/output/total, reasoning, cached, audio), context-window utilization, generation time, tokens/second and message/chat cost.

Resources

Contributing

Stars

44 stars

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages