Skip to main content

Cost Tracking API

This page documents the 8 gateway endpoints tagged Cost Tracking in the gateway's OpenAPI document. Every example targets a gateway on http://localhost:4000 and authenticates with the SPANWAY_API_KEY environment variable, which holds the master key or a virtual key that has access to the route. Request and response fields are taken from the schema the running gateway publishes at /openapi.json, and the same document is bundled with this site as openapi.json.

MethodPathSummary
POST/cost/predict-cachePredict the prompt cache cost of staying on or switching a deployment
GET/config/cost_discount_configShow the provider discounts
PATCH/config/cost_discount_configSet the provider discounts
GET/config/cost_margin_configShow the provider margins
PATCH/config/cost_margin_configSet the provider margins
GET/config/block_requests_for_models_without_pricingShow whether unpriced models are refused
PATCH/config/block_requests_for_models_without_pricingRefuse or allow requests for unpriced models
POST/cost/estimateEstimate the cost of expected traffic

Endpoints​

POST /cost/predict-cache​

Predict the prompt cache cost of staying on or switching a deployment

Compare the next native Anthropic request on two configured deployment IDs.

Use it before moving traffic from one deployment to another, because a long prompt that is already cached on the current deployment can cost far more on a deployment where the cache is cold. Send the two deployment ids and the exact Anthropic Messages body you are about to send. Any key that may call both deployments can ask, and the answer shows the input cost of staying (stay), of switching (switch), the difference (switch_delta) and the cost of rebuilding the cache after a switch (cache_rebuild_penalty). Nothing is changed and no tokens are generated.

Estimates use provider token counting and recent successful cache telemetry for this key. Unknown cache state uses the cold scenario when prices/counts are available. Cache observations do not guarantee retention. v0 supports one message-content breakpoint, text and client tools; system/tool-only breakpoints, thinking, images, nondefault Anthropic versions, beta headers and request transforms are unknown. Each provider count consumes one RPM unit and holds concurrency capacity; a comparison uses up to four counts. The legacy rate limiter returns unknown without contacting the provider. This endpoint does not generate tokens, prewarm caches, choose a model or alter routing.

Request body (application/json, schema CachePredictionRequest):

FieldTypeRequiredDescription
current_deployment_idstringYesThe deployment id the traffic uses today
candidate_deployment_idstringYesThe deployment id you are thinking of switching to
requestobjectYesThe Anthropic Messages body you are about to send

Example request:

curl -X POST "http://localhost:4000/cost/predict-cache" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"current_deployment_id": "deployment-claude-primary",
"candidate_deployment_id": "deployment-claude-backup",
"request": {
"model": "claude-sonnet",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here is our product manual ...",
"cache_control": {
"type": "ephemeral"
}
},
{
"type": "text",
"text": "How do I reset the device?"
}
]
}
]
}
}'

Responses:

StatusDescriptionBody
200The estimate for both deploymentsapplication/json CachePredictionResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
404Either deployment id is unknown or not visible to the key's teamapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError
503The gateway has no model router loaded yetapplication/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
stayCachePredictionArmYesThe estimate for sending the request to the current deployment
switchCachePredictionArmYesThe estimate for sending the request to the candidate deployment
switch_deltanumber or nullYesSwitch input cost minus stay input cost, null when either is unknown
cache_rebuild_penaltynumber or nullYesExtra input cost of a cold cache on the candidate, null when unknown
pricing_basis"input_before_discounts_and_margins"NoPricing Basis
cache_guaranteefalseNoCache Guarantee

GET /config/cost_discount_config​

Show the provider discounts

Return cost_discount_config from spanway_settings, the discount applied to every request of each provider.

An empty values object means no discount is set. Proxy admins and admin viewers only, nothing is changed.

Docs

Example request:

curl -X GET "http://localhost:4000/config/cost_discount_config" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The discount per provider as a fraction, 0.05 for 5 percent offapplication/json object
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keys or Failed to read cost discount config: <reason>application/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
valuesobjectNo

PATCH /config/cost_discount_config​

Set the provider discounts

Replace cost_discount_config in spanway_settings with the object sent, keyed by provider.

Each value is a fraction between 0 and 1, so 0.05 takes 5 percent off every request to that provider from now on. An unknown provider name or a value outside 0 to 1 is a 400. Saving needs a database and STORE_MODEL_IN_DB=True. Proxy admins only, and the change is written to the audit log.

Docs

Request body (application/json, object):

Example request:

curl -X PATCH "http://localhost:4000/config/cost_discount_config" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"anthropic": 0.05,
"openai": 0.01
}'

Responses:

StatusDescriptionBody
200The saved discountsapplication/json object
400Invalid provider(s): open_ai. Must be valid Spanway providers. See https://docs.spanway.ai/docs/providers for the full list. or Discount for openai must be a number or Discount for openai must be between 0 and 1 (0% to 100%)application/json ErrorDetail
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError
403An admin viewer tried to change something, and admin viewers can only readapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keys or Set 'STORE_MODEL_IN_DB='True' in your env to enable this feature. or Failed to update cost discount config: <reason>application/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
messagestringNo
statusstringNo
valuesobjectNo

GET /config/cost_margin_config​

Show the provider margins

Return cost_margin_config from spanway_settings, the fee added on top of provider cost.

global applies to every provider. An empty values object means no margin is set. Proxy admins and admin viewers only, nothing is changed.

Docs

Example request:

curl -X GET "http://localhost:4000/config/cost_margin_config" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200The margin per provider, a fraction or an object with percentage and fixed_amountapplication/json object
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keys or Failed to read cost margin config: <reason>application/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
valuesobjectNo

PATCH /config/cost_margin_config​

Set the provider margins

Replace cost_margin_config in spanway_settings with the object sent, keyed by provider or global.

A margin is added to the recorded cost of every request to that provider. A percentage is a fraction between 0 and 10 (0.1 adds 10 percent), a fixed amount is US dollars per request, and both can be combined. A value outside those ranges is a 400. Saving needs a database and STORE_MODEL_IN_DB=True. Proxy admins only, and the change is written to the audit log.

Docs

Margins can be:

  • Percentage: {"openai": 0.10} = 10% margin
  • Fixed amount: {"openai": {"fixed_amount": 0.001}} = $0.001 per request
  • Combined: {"vertex_ai": {"percentage": 0.08, "fixed_amount": 0.0005}}
  • Global: {"global": 0.05} = 5% global margin on all providers

Example:

{
"global": 0.05,
"openai": 0.10,
"anthropic": {"fixed_amount": 0.001},
"vertex_ai": {"percentage": 0.08, "fixed_amount": 0.0005}
}

Request body (application/json, object):

Example request:

curl -X PATCH "http://localhost:4000/config/cost_margin_config" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"global": 0.05,
"openai": 0.1,
"anthropic": {
"fixed_amount": 0.001
}
}'

Responses:

StatusDescriptionBody
200The saved marginsapplication/json object
400Invalid provider(s): open_ai. Must be valid Spanway providers or 'global'. See https://docs.spanway.ai/docs/providers for the full list. or Margin percentage for openai must be between 0 and 10 (0% to 1000%) or Margin percentage for openai must be a number or Fixed margin amount for openai must be a number or Fixed margin amount for openai must be non-negative or Margin config for openai cannot be empty. Must include 'percentage' and/or 'fixed_amount' or Margin for openai must be a number (percentage) or dict with 'percentage' and/or 'fixed_amount'application/json ErrorDetail
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError
403An admin viewer tried to change something, and admin viewers can only readapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keys or Set 'STORE_MODEL_IN_DB='True' in your env to enable this feature. or Failed to update cost margin config: <reason>application/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
messagestringNo
statusstringNo
valuesobjectNo

GET /config/block_requests_for_models_without_pricing​

Show whether unpriced models are refused

Tell whether requests for a model without a price are refused (enabled: true) or recorded as unpriced. Proxy admins and admin viewers may call it. Nothing is changed.

Docs

Example request:

curl -X GET "http://localhost:4000/config/block_requests_for_models_without_pricing" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Responses:

StatusDescriptionBody
200Successful Responseapplication/json BlockUnpricedModelsResponse
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
enabledbooleanYesEnabled

PATCH /config/block_requests_for_models_without_pricing​

Refuse or allow requests for unpriced models

Turn block_requests_for_models_without_pricing on or off and save it to the database config.

When on, a request whose model has no price in the price map or its deployment's model_info is refused with a 403 instead of being logged with a cost of 0. The change applies at once and is written to the audit log. Saving needs a database and STORE_MODEL_IN_DB=True. Proxy admins only.

Docs

Request body (application/json, schema BlockUnpricedModelsRequest):

FieldTypeRequiredDescription
enabledbooleanYesEnabled

Example request:

curl -X PATCH "http://localhost:4000/config/block_requests_for_models_without_pricing" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"enabled": true
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json BlockUnpricedModelsResponse
401No valid key was sent, or the key belongs to someone who is not a proxy adminapplication/json ProxyError
403An admin viewer tried to change something, and admin viewers can only readapplication/json ProxyError
422Validation Errorapplication/json HTTPValidationError
500DB not connected. This endpoint needs a database; set DATABASE_URL to a PostgreSQL connection string (postgresql://...) to enable it. See https://docs.spanway.ai/docs/proxy/virtual_keys or Set 'STORE_MODEL_IN_DB='True' in your env to enable this feature. or Failed to update setting: <reason>application/json ErrorDetail

Response fields (200):

FieldTypeRequiredDescription
enabledbooleanYesEnabled

POST /cost/estimate​

Estimate the cost of expected traffic

Estimate what a model costs per request, per day and per month for the token counts you expect.

The estimate uses the prices, discounts and margins the gateway applies to real requests, so it matches what the spend log would record. This is the query behind the pricing calculator on the Cost Tracking page.

Send the model name as callers use it (a model group or alias is resolved to its deployment) and the tokens you expect per request. Cache and reasoning tokens are counted inside input_tokens and output_tokens. Daily and monthly totals are filled in only when you send num_requests_per_day or num_requests_per_month. A model the gateway cannot price answers 404.

Any valid key may call it. Nothing is called or changed, so it costs nothing.

Docs

Request body (application/json, schema CostEstimateRequest):

FieldTypeRequiredDescription
modelstringYesModel name (from /model_group/info)
input_tokensintegerYesExpected input tokens per request
output_tokensintegerYesExpected output tokens per request
cache_read_input_tokensintegerNoInput tokens read from the prompt cache; counted within input_tokens
cache_creation_input_tokensintegerNoInput tokens written to the prompt cache; counted within input_tokens
reasoning_tokensintegerNoReasoning tokens the model emits; counted within output_tokens
num_requests_per_dayinteger or nullNoNumber of requests per day
num_requests_per_monthinteger or nullNoNumber of requests per month

Example request:

curl -X POST "http://localhost:4000/cost/estimate" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"input_tokens": 1000,
"output_tokens": 500,
"num_requests_per_month": 100000
}'

Responses:

StatusDescriptionBody
200Successful Responseapplication/json CostEstimateResponse
401No valid key or Admin UI session was presentedapplication/json ProxyError
404Could not calculate cost for model 'my-unpriced-model' (resolved to 'openai/my-unpriced-model'): This model isn't mapped yet. model=openai/my-unpriced-model, custom_llm_provider=openai. Add it here - https://docs.spanway.ai/docs/proxy/custom_pricingapplication/json ErrorDetail
422Validation Errorapplication/json HTTPValidationError

Response fields (200):

FieldTypeRequiredDescription
modelstringYesModel
input_tokensintegerYesInput Tokens
output_tokensintegerYesOutput Tokens
cache_read_input_tokensintegerNoCache Read Input Tokens
cache_creation_input_tokensintegerNoCache Creation Input Tokens
reasoning_tokensintegerNoReasoning Tokens
num_requests_per_dayinteger or nullNoNum Requests Per Day
num_requests_per_monthinteger or nullNoNum Requests Per Month
cost_per_requestnumberYesTotal cost per request (includes margin)
input_cost_per_requestnumberYesInput token cost per request (before margin)
output_cost_per_requestnumberYesOutput token cost per request (before margin)
margin_cost_per_requestnumberNoMargin/fee added per request
cache_read_cost_per_requestnumberNoCache-read share of input_cost_per_request
cache_creation_cost_per_requestnumberNoCache-write share of input_cost_per_request
reasoning_cost_per_requestnumberNoReasoning share of output_cost_per_request
daily_costnumber or nullNoTotal daily cost (includes margin)
daily_input_costnumber or nullNoDaily input token cost
daily_output_costnumber or nullNoDaily output token cost
daily_margin_costnumber or nullNoDaily margin/fee
daily_cache_read_costnumber or nullNoCache-read share of daily_input_cost
daily_cache_creation_costnumber or nullNoCache-write share of daily_input_cost
daily_reasoning_costnumber or nullNoReasoning share of daily_output_cost
monthly_costnumber or nullNoTotal monthly cost (includes margin)
monthly_input_costnumber or nullNoMonthly input token cost
monthly_output_costnumber or nullNoMonthly output token cost
monthly_margin_costnumber or nullNoMonthly margin/fee
monthly_cache_read_costnumber or nullNoCache-read share of monthly_input_cost
monthly_cache_creation_costnumber or nullNoCache-write share of monthly_input_cost
monthly_reasoning_costnumber or nullNoReasoning share of monthly_output_cost
input_cost_per_tokennumber or nullNoRate billed per input token
output_cost_per_tokennumber or nullNoRate billed per output token
cache_read_input_token_costnumber or nullNoRate billed per cache-read token
cache_creation_input_token_costnumber or nullNoRate billed per cache-write token
output_cost_per_reasoning_tokennumber or nullNoRate billed per reasoning token
providerstring or nullNoProvider