Skip to main content

Cost tracking

Cost tracking answers one question for every request that passes through the gateway: what did it cost, and who should it be charged to. The gateway reads the token counts in the provider response, multiplies them by the model's prices and writes the result to the spend log together with the key, user, team, organization, end user, tags and metadata of the request. Budgets, spend reports, alerts, cost exports and invoices all build on that one number, so you never have to reconcile provider bills by hand to know what a team or a feature is costing you.

A real-world scenario​

A company runs a customer support bot on the gateway. Finance wants to know what the bot costs per month and per customer, and the platform team wants to be warned before any single team spends more than it should. Each request from the bot carries the bot team's virtual key, the customer id in user and the tag support-bot. The gateway prices every call, records it, and the Usage page shows the month's spend by team, by customer and by tag without anyone touching a provider dashboard. When the bot team later adds a self-hosted model, they give it a price in the config and it shows up in the same reports.

Set up cost tracking for a request​

  1. Confirm the model has a price. In the Admin UI open Settings, then Cost Tracking, and in Pricing Calculator pick the model under Model. A row that says no pricing data was found needs a price, see custom pricing. Models from the bundled price map are priced already.

  2. Send a request with attribution. The key supplies the team, user and organization. Put the end user of your application in user and the feature or project in the x-spanway-tags header, and ask curl to show the response headers:

    curl -i http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -H "x-spanway-tags: support-bot" \
    -d '{"model": "claude-sonnet-5-5", "user": "customer-42", "messages": [{"role": "user", "content": "Where is my order?"}]}'

    Expected result: the response carries the header x-spanway-response-cost: 0.0042 (your number differs), which is the cost the gateway recorded for this call.

  3. Read the spend log row. In the Admin UI open Logs and click the request, the drawer shows the cost, tokens, model, team, end user and tags. With the API:

    curl "http://localhost:4000/spend/logs/v2?start_date=2026-10-14&end_date=2026-10-14&end_user=customer-42&page_size=5" \
    -H "Authorization: Bearer $SPANWAY_API_KEY"

    Expected result:

    {
    "data": [
    {
    "request_id": "chatcmpl-6dcb2540-d3d7-4e49-bb27-291f863f112e",
    "spend": 0.0042,
    "prompt_tokens": 1200,
    "completion_tokens": 200,
    "model": "claude-sonnet-5-5",
    "team_id": "team-nlp",
    "end_user": "customer-42",
    "request_tags": ["support-bot"]
    }
    ],
    "total": 1,
    "page": 1,
    "page_size": 5,
    "total_pages": 1
    }
  4. See the totals. In the Admin UI open Usage. The Spend tile on the Overview tab totals the range, Team Usage breaks it down by team, Customer Usage by end user and Tag Usage by tag. The same numbers are available through the daily activity export and the spend reports.

How cost is calculated​

For token priced models, cost is input tokens times input_cost_per_token plus output tokens times output_cost_per_token, with separate prices where they apply for cached input tokens, cache writes, reasoning tokens, audio tokens and images. Other models are priced per image, per second of audio or video, per character, per query or per page. Prices come from the price map bundled with the gateway. At startup the gateway can fetch a newer copy of the map, and SPANWAY_LOCAL_MODEL_COST_MAP=True makes it use only the bundled copy, which is the right choice for air-gapped deployments. Any price can be overridden per deployment, see custom pricing.

To attribute spend toSend
A key, user, team, organizationNothing extra, it comes from the virtual key.
An end user of your applicationuser in the request body.
A feature or projectx-spanway-tags header or metadata.tags.
Anything elseFields in metadata, recorded in the spend log.

Each spend log row holds the request id, call type, model and model group, provider, prompt and completion tokens, spend, start and end time, cache hit flag, the identity fields and the metadata. Request and response bodies are stored only when general_settings.store_prompts_in_spend_logs is on. Daily totals per user, team, organization, end user, tag and key are kept in separate tables and power the Usage page and the /user/daily/activity family of endpoints, so reports stay fast however large the spend log grows.

Zero-completion insurance​

With zero-completion insurance on, a request whose model produced nothing is not charged for its tokens. A chat completion or Responses API call is insured when it returned zero completion tokens without a finish reason (for the Responses API, a status of incomplete or failed with zero output tokens), or when the provider ended it with the finish reason error. Its token cost is set to 0, so the spend log, the key, team and organization budgets and Spanway Cloud credits all see 0. Any additional_response_cost set by a callback is still charged. The waived amount is kept as insured_cost in the spend log's cost_breakdown and as insured_cost_usd in its metadata, and the request drawer on the Logs page marks the request as Insured. For a streamed response the decision uses the finish reason and usage of the final chunk.

Chat completions fill in stop when a provider sends no finish reason, so a chat response cannot tell a missing finish reason apart from a stop that came with an empty message. Both are insured when the response has zero completion tokens and no content, tool call or function call. A finish reason the provider sent in its own words, such as end_turn or length, is never treated as missing.

It is off by default on a self-hosted gateway and on by default in Spanway Cloud. Turn it on in the config file, or as a proxy admin with the zero_completion_insurance switch on Router Settings, General tab in the Admin UI. A saved change applies without a restart.

general_settings:
zero_completion_insurance: true

Spend tracking for Azure OpenAI models​

Azure OpenAI deployments have names you choose, such as prod-gpt, so the gateway cannot always tell which OpenAI model is behind them. Without that information it cannot look up prices or context windows. Set base_model in model_info to the model the Azure deployment runs.

model_list:
- model_name: gpt-6.1-sol
spanway_params:
model: azure/prod-gpt
api_base: os.environ/AZURE_API_BASE
api_key: os.environ/AZURE_API_KEY
api_version: os.environ/AZURE_API_VERSION
model_info:
base_model: azure/gpt-6.1-sol

When the deployment name cannot be resolved, the gateway logs a warning asking you to set base_model. The same setting fixes context window checks for Azure deployments.

Spend endpoints​

MethodPathSummary
POST/spend/logs/ui/{request_id}/revealReveal hidden fields of one request log
GET/spend/tagsSpend per request tag
GET/spend/capture_rateCompare captured spend with the provider bill
GET/global/spend/reportGateway-wide spend report per day
GET/global/spend/tagsSpend per tag over a date range
POST/spend/calculateCalculate the cost of a request or a response
GET/spend/logs/uiPage through spend logs with session totals for the Admin UI
GET/spend/logs/v2Page through spend logs
GET/spend/logsSpend logs or daily totals, unpaginated
POST/global/spend/resetReset the spend counters of every key and team

POST /spend/calculate returns the cost of a request or a response without making a call, which is the quickest way to check that a price is picked up. It follows a model group or alias to its deployment and reads the deployment's prices from model_info or spanway_params and its base_model, the way a real request is priced:

curl -X POST http://localhost:4000/spend/calculate \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Where is my order?"}]}'

Expected result: {"cost": 0.0042}. A model with no price answers 400 This model isn't mapped yet. instead of a cost.

Errors​

What you seeMeaningFix
A spend log row with a cost of 0 labelled unpriced on the Logs page, and the warning model_not_priced in the gateway log.The model has no price in the price map or in its deployment's model_info. The request went through and totals still add up.Add a price with custom pricing, or set base_model.
403 with the type model_cost_map_missing naming the model on a chat request.block_requests_for_models_without_pricing or block_unpriced_models_when_budgeted is on and the model has no price.Add a price, or turn the switch off on the Cost Tracking page.
400 This model isn't mapped yet. model=<model>, ... from POST /spend/calculate.The model has no price.Add a price with custom pricing.
Warning asking you to set base_model for an Azure deployment.The gateway cannot map the Azure deployment name to a model, so it cannot price it.Add model_info.base_model as shown above.
400 or 500 No connected db from a spend endpoint.The gateway runs without a database, so there is no spend log to read.Set DATABASE_URL. Spend tracking needs Postgres.
x-spanway-response-cost is missing from a response.The call went through a pass-through route that does not price responses, or the response was an error.Use the native routes, or give the pass-through endpoint a cost_per_request.

Logs​

LevelMessageMeaningAction
WARNINGBillable request has no price and is logged as unpriced (...). Counted in spanway_zero_cost_requests_total{reason="model_not_priced"}A request reached a model with no price, so its spend log row is 0 and budgets do not count it.Add a price, see custom pricing.
WARNINGModel=<name> not found in completion cost map. Setting 'response_cost' to NoneThe same case, logged while the response is priced.The same.
WARNINGA line asking you to set base_model for an Azure deploymentThe deployment name does not map to a priced model.Add model_info.base_model.

The log reference lists every gateway log line.