diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 4a9c01fe3c..ded523b90d 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -5231,7 +5231,7 @@ devops ai cost set-price | Argument | Type | Required | Description | |---|---|---|---| -| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | +| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). When a gateway reply names its deployment model, such as 'openai/gpt-4o', that model is the target, not the route name. A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | | `` | `float` | Yes | Prompt token cost in USD per 1,000,000 tokens. | | `` | `float` | Yes | Completion token cost in USD per 1,000,000 tokens. | @@ -5361,7 +5361,7 @@ devops ai spend set-price | Argument | Type | Required | Description | |---|---|---|---| -| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | +| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). When a gateway reply names its deployment model, such as 'openai/gpt-4o', that model is the target, not the route name. A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | | `` | `float` | Yes | Prompt token cost in USD per 1,000,000 tokens. | | `` | `float` | Yes | Completion token cost in USD per 1,000,000 tokens. | diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index ac24d6f564..4abe8b289d 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -37,7 +37,7 @@ native histogram under the instrument's own name, with no `_bucket`, `_sum` or | `devops_cli_findings_total` | Counter | `1` | Review findings, by producer, severity and status. | | `devops_cli_ai_requests_total` | Counter | `1` | LLM calls and embedding requests, by operation (chat or embeddings), provider, model, server, serving backend and whether the cache answered. | | `devops_cli_ai_tokens_total` | Counter | `1` | LLM and embedding tokens, by operation (chat or embeddings), type (prompt or completion), provider, model, server, backend and local: true when a local model ran them. The AI spend dashboard prices local tokens as savings at the reference price that the Prometheus recording rule devops_cli:ai_reference_price_usd_per_token holds for their operation and type. | -| `devops_cli_ai_spend_usd_total` | Counter | `USD` | Approximate LLM and embedding spend, by operation, provider, model, server and backend. Each request that a model answers adds to it, and a local request adds 0. | +| `devops_cli_ai_spend_usd_total` | Counter | `USD` | Approximate LLM and embedding spend, by operation, provider, model, server and backend. Each request that a model answers adds to it, and a local request adds 0. A hosted gateway call is priced at the deployment model that the gateway names, and its model label is the model that the client asked for, such as the route name. | | `devops_cli_ai_json_repairs_total` | Counter | `1` | LLM JSON replies repaired after strict parsing failed, by entry point source. | | `devops_cli_ai_gateway_slot_wait_seconds` | Histogram | `s` | Time a chat call to the LLM gateway waited in this process for one of the gateway's backend slots, by outcome: ok once it held one, or timeout. | | `devops_cli_rag_query_duration_ms` | Histogram | `ms` | RAG retrieval time, by stage: embedding, search, ranking, or total for the whole query. | diff --git a/docs/commands/ai.md b/docs/commands/ai.md index b764a94738..be7c5695ca 100644 --- a/docs/commands/ai.md +++ b/docs/commands/ai.md @@ -1998,7 +1998,7 @@ devops ai cost set-price | Argument | Type | Required | Description | |---|---|---|---| -| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | +| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). When a gateway reply names its deployment model, such as 'openai/gpt-4o', that model is the target, not the route name. A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | | `` | `float` | Yes | Prompt token cost in USD per 1,000,000 tokens. | | `` | `float` | Yes | Completion token cost in USD per 1,000,000 tokens. | @@ -2130,7 +2130,7 @@ devops ai spend set-price | Argument | Type | Required | Description | |---|---|---|---| -| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | +| `` | `string` | Yes | Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). When a gateway reply names its deployment model, such as 'openai/gpt-4o', that model is the target, not the route name. A local call costs nothing, also when it has a custom price. Its tokens count in local savings. | | `` | `float` | Yes | Prompt token cost in USD per 1,000,000 tokens. | | `` | `float` | Yes | Completion token cost in USD per 1,000,000 tokens. | diff --git a/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/.openspec.yaml b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/.openspec.yaml new file mode 100644 index 0000000000..1f5d28041e --- /dev/null +++ b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-24 diff --git a/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/design.md b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/design.md new file mode 100644 index 0000000000..699d58209c --- /dev/null +++ b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/design.md @@ -0,0 +1,38 @@ +# Design + +## Context + +`track_request_spend` in `src/devops_cli/ai/spend/ledger.py` prices each call with `PricingRegistry.calculate_request_cost`, at the model that the client asked for. For a gateway call, this model is the route name, such as `devops-chat`. A reply of the LiteLLM gateway names the backend in `x-litellm-model-api-base`, which decides if the call is local or hosted (#1631). It names the deployment model in `x-litellm-model-name`. See proposal.md for the evidence. + +## Goals / Non-Goals + +**Goals:** + +- A hosted gateway call is priced at the deployment model that served it, for a blocking chat call, a streamed chat call and an embedding request. +- The spend ledger, the metrics and `devops ai cost` keep the model that the client asked for. + +**Non-Goals:** + +- A metric label for the deployment model. The ledger holds it. +- The `gen_ai.response.model` attribute of the inference span. It keeps the model of the reply body. +- A change to the reference prices that price the local tokens on the dashboard (#1672). See the record below. + +## Decisions + +- **genai-prices reads the deployment model as a LiteLLM model reference.** The registry gives genai-prices the provider ID `litellm` (`CONST_GENAI_PRICES_LITELLM_PROVIDER`), and genai-prices takes the provider from the prefix. Rejected: price the deployment model under the request provider, `gateway`, and then with no provider, as the registry does for other models. genai-prices knows no provider `gateway`. With no provider, it gave `LookupError` for `text-embedding-3-small`, because no provider has a `model_match` for this model. Rejected: a table from LiteLLM prefixes to genai-prices providers. genai-prices already holds this map in `provider_match`. +- **The deployment model is the target of a price override.** When the reply names a deployment model, the override of that model applies, and the override of the route name does not. A route can send calls to a local deployment and to a hosted deployment, and the price belongs to the deployment. The help of `devops ai cost set-price` says this. Rejected: the override of the route name first. It gives one price to each hosted deployment of the route. +- **The local check comes first.** The backend that served the call decides if it is local before the registry reads the deployment model. Thus a local deployment, such as `ollama_chat/qwen3.8:27b`, stays local and costs nothing. +- **The route name stays the model of the row and of the metrics.** The issue asks for this, and the dashboards and `devops ai cost --by model` group by it. Rejected: write the deployment model in `model`. A route then has one series for each deployment, and the request counts do not show what the clients asked for. +- **The ledger stores the deployment model in `served_model`.** A row that `genai_prices:openai` priced then shows the model that set its price. Rejected: no column. The row then shows only `devops-chat` and `genai_prices:openai`, and a person cannot see which model priced it. +- **No metric label for the deployment model.** No dashboard reads it, and each deployment adds series. The ledger holds it. +- **Only `config/constants.py` and `ai/client/network.py` name a gateway reply header.** `extract_served_model` reads the header in `network.py`, next to `extract_served_by`. A streamed reply keeps the deployment model in the context variable `stream_served_model`, as it keeps the backend. `tests/test_url_credential_masking.py` checks the rule for the two headers. + +## Record: the reference models of the dashboard + +On 2026-10-24 the owner confirmed that the AI spend dashboard prices local tokens at the default reference models: `gpt-4o-mini` for chat and `text-embedding-3-small` for embeddings. This answers the "Pending a person" bullet about the reference models in `openspec/changes/archive/2026-10-24-1672-local-savings-reference-prices/tasks.md`. + +## Risks / Trade-offs + +- [A gateway does not send `x-litellm-model-name`] → The call is priced at the route name, as before. Its source is `unknown`, and the registry logs one warning that names the route name. +- [genai-prices does not know a deployment model] → The call costs $0 with the source `unknown`, and the registry logs one warning that names the deployment model and the provider `litellm`. +- [Rows from before the change have no `served_model`] → Their recorded cost does not change. diff --git a/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/proposal.md b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/proposal.md new file mode 100644 index 0000000000..18ebcf174b --- /dev/null +++ b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/proposal.md @@ -0,0 +1,49 @@ +# Proposal + +## Why + +Issue #2031: the spend ledger priced a hosted gateway call at the route name that the client asked for, for example `devops-chat`. genai-prices does not know a route name, so the call cost $0 with the pricing source `unknown`. The LiteLLM gateway names the deployment model that served the call in the `x-litellm-model-name` reply header, for example `openai/gpt-4o`. devops-cli did not read this header. + +## What Changes + +- devops-cli reads the `x-litellm-model-name` header of a gateway reply for a blocking chat call, a streamed chat call and an embedding request. `CONST_AI_GATEWAY_SERVED_MODEL_HEADER` in `src/devops_cli/config/constants.py` holds the header name, and `extract_served_model` in `src/devops_cli/ai/client/network.py` reads it. Only these two files name a gateway reply header. `tests/test_url_credential_masking.py` now checks this rule for both headers. +- `PricingRegistry.calculate_request_cost` takes `served_model`. When the reply names a deployment model, a hosted call is priced at that model, as a LiteLLM model reference: genai-prices gets the provider ID `litellm` and takes the provider from the prefix. A price override of the deployment model applies, and a price override of the route name does not. When the reply names no deployment model, the call is priced at the model that the client asked for, as before. A local call stays local. +- The model that the client asked for stays the `model` of the spend-ledger row and the `model` label of `devops_cli_ai_requests_total`, `devops_cli_ai_tokens_total` and `devops_cli_ai_spend_usd_total`. Thus the dashboards and `devops ai cost` still group by the route name. +- Each spend-ledger row stores the deployment model in the new column `served_model`. An existing ledger gets the column and keeps its rows. +- The description of `devops_cli_ai_spend_usd_total` in `docs/TELEMETRY.md` and the help of `devops ai cost set-price` say which model prices a gateway call. +- The value of a metric, the spend ledger and the help of a command change, so the change has a spec delta. It adds requirements to `ai-spend-pricing`. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `ai-spend-pricing`: adds the requirements that a hosted gateway call is priced at the deployment model that the gateway names, that the route name stays the model of the row and of the metrics, and that each row stores the deployment model. + +## Impact + +- Code: `src/devops_cli/config/constants.py`, `src/devops_cli/ai/client/network.py`, `models.py`, `openai.py` and `unified.py`, `src/devops_cli/ai/rag/embeddings.py`, `src/devops_cli/ai/spend/pricing.py`, `ledger.py` and `models.py`, `src/devops_cli/telemetry/instruments.py` and `src/devops_cli/commands/ai_cost.py`. +- Documents: `docs/TELEMETRY.md`, `docs/CLI_REFERENCE.md` and `docs/commands/ai.md`, generated again. +- Tests: `tests/test_ai_served_by.py`, `tests/test_ai_spend_pricing.py`, `tests/test_ai_spend_ledger.py`, `tests/test_rag_embeddings.py`, `tests/test_telemetry_instruments.py` and `tests/test_url_credential_masking.py`. +- Today each route in `k8s/llm/gateway/config.yaml` sends its calls to an Ollama deployment in the cluster, so each live gateway call is local. The live spend changes only when a hosted deployment serves a call. + +## Feasibility + +- LiteLLM 1.103.0 source, read in the gateway pod (image `ghcr.io/berriai/litellm:v1.103.0`, read-only `kubectl -n llm exec deploy/llm-gateway -- python -c ...`): `ProxyBaseLLMRequestProcessing.get_custom_headers` sets `x-litellm-model-name` to `_get_deployment_model_name(litellm_logging_obj)`. That function reads `deployment` from the `litellm_metadata` or `metadata` of the `litellm_params` of the call. Its docstring says that the router writes the model-group alias that the client asked for in the `model` field of the reply. Thus the reply body and the other headers do not name the deployment model. +- `Router._update_kwargs_with_deployment` sets `deployment` to `litellm_params.model` of the deployment that it selects, and `api_base` from the same deployment. Thus `x-litellm-model-name` and `x-litellm-model-api-base` name the same deployment. +- Each call of `get_custom_headers` in `litellm/proxy/common_request_processing.py` gives the logging object: the blocking reply, the streamed reply and the failure reply. `/v1/embeddings` goes through `base_process_llm_request`, as `/v1/chat/completions` does. +- Live Prometheus, read-only through Grafana on 2026-10-24: in the last 7 days, `devops_cli_ai_requests_total{provider="gateway"}` had three `backend` values, one for each Ollama tier that served a call. devops-cli takes these values from `x-litellm-model-api-base`, which the same `get_custom_headers` call sets. The `model` values were the models that the clients asked for. +- genai-prices 0.1.9, installed source: `DataSnapshot.find_provider_model` takes the provider ID `litellm` with a model reference that has a `/`. It takes the provider ID from the prefix and the model from the remaining text, when `find_provider_by_id` knows the provider. `find_provider_by_id` also uses the `provider_match` of each provider, so `bedrock` finds `aws`. +- An offline probe of the bundled snapshot with the provider ID `litellm` and 1,000,000 input tokens gave these prices and providers: `openai/gpt-4o` $2.50 (openai), `openai/text-embedding-3-small` $0.02 (openai), `bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0` $3.00 (aws), `openrouter/anthropic/claude-3.5-sonnet` $3.00 (openrouter), `gemini/gemini-2.5-flash` and `vertex_ai/gemini-2.5-flash` $0.30 (google), `azure/gpt-4o` $2.50 (azure), and `anthropic/claude-sonnet-4-5` (anthropic). `ollama_chat/qwen3.8:27b` and `devops-chat` gave `LookupError`. With no provider, `text-embedding-3-small` and `openai/gpt-4o` gave `LookupError`. With the provider `gateway`, each model gave `LookupError`. +- On the base commit, the ten new tests failed: the ledger had no `served_model` column, `track_request_spend`, `SpendLedger.record_request` and `PricingRegistry.calculate_request_cost` took no `served_model`, and no source file named `x-litellm-model-name`. + +## Existing Tool Considered + +- genai-prices, the price source of the ledger, reads a LiteLLM model reference itself under the provider ID `litellm`. devops-cli gives it the deployment model with this provider ID. devops-cli holds no table of LiteLLM prefixes and does not split the reference. +- LiteLLM sends its own cost of a call in `x-litellm-response-cost`. Rejected: the ledger keeps one price source for each call: genai-prices, with its snapshot update and the price overrides of `devops ai cost set-price`. A call to a provider without the gateway has no such header. +- `litellm.get_llm_provider` also splits a LiteLLM model reference. Rejected: litellm is not a dependency of devops-cli, and genai-prices already does the split. +- The change deletes no code. `_parse_compat_response` takes the reply headers in place of the backend, and reads the backend and the deployment model from them. diff --git a/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/specs/ai-spend-pricing/spec.md b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/specs/ai-spend-pricing/spec.md new file mode 100644 index 0000000000..786984aa67 --- /dev/null +++ b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/specs/ai-spend-pricing/spec.md @@ -0,0 +1,41 @@ +## ADDED Requirements + +### Requirement: A hosted gateway call is priced at the deployment model that the gateway names +When a gateway reply names the deployment model that served the call in the `x-litellm-model-name` header, devops-cli SHALL price a hosted call at that model, which genai-prices reads as a LiteLLM model reference. When the reply names no deployment model, devops-cli SHALL price the call at the model that the client asked for. A call that a local backend served SHALL stay local. + +#### Scenario: A blocking reply and a streamed reply that name `openai/gpt-4o` +- **WHEN** a `devops-chat` call through the gateway gets a reply from `https://api.openai.com` that names `openai/gpt-4o`, once as a blocking reply and once as a streamed reply +- **THEN** each row has the model `devops-chat`, the deployment model `openai/gpt-4o`, the pricing source `genai_prices:openai` and a cost of more than $0 + +#### Scenario: A reply that names no deployment model +- **WHEN** the reply of a hosted `devops-chat` call names no deployment model +- **THEN** the row has the model `devops-chat`, no deployment model, the pricing source `unknown` and a cost of $0 + +#### Scenario: An embedding request that names its deployment model +- **WHEN** a gateway embedding reply from `https://api.openai.com` names `openai/text-embedding-3-small` and counts 1,000,000 input tokens for the model `bge-m3:latest` +- **THEN** the row has the model `bge-m3:latest`, the deployment model `openai/text-embedding-3-small`, the pricing source `genai_prices:openai` and a cost of $0.02 + +#### Scenario: Deployment models of other providers +- **WHEN** hosted replies name `openai/gpt-4o`, `openai/text-embedding-3-small`, `bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0`, `openrouter/anthropic/claude-3.5-sonnet` and two times `openai/gpt-9-preview`, and a local backend names `ollama_chat/qwen3.8:27b` +- **THEN** the pricing sources are `genai_prices:openai`, `genai_prices:openai`, `genai_prices:aws`, `genai_prices:openrouter`, two times `unknown`, and `local`, and one warning names `openai/gpt-9-preview` and the provider `litellm` + +### Requirement: A price override of the deployment model prices a gateway call +When a gateway reply names a deployment model, a price override of that model SHALL price the hosted call, and a price override of the route name SHALL NOT. + +#### Scenario: Price overrides of the deployment model and of the route name +- **WHEN** price overrides exist for `gpt-4o` and for `devops-chat`, and a hosted `devops-chat` reply names `openai/gpt-4o` +- **THEN** the call has the price of `gpt-4o`, and a reply that names no deployment model has the price of `devops-chat` + +### Requirement: The metrics keep the model that the client asked for +devops-cli SHALL keep the model that the client asked for, such as a gateway route name, as the `model` label of the AI request, token and spend metrics of a call that the deployment model priced. + +#### Scenario: A hosted call that names `openai/gpt-4o` +- **WHEN** a hosted `devops-chat` call that names `openai/gpt-4o` and counts 1,000,000 input tokens is recorded +- **THEN** the request, token and spend points have the `model` label `devops-chat`, and the spend point is $2.50 + +### Requirement: Each spend-ledger row records the deployment model that priced it +Each spend-ledger row SHALL store, in `served_model`, the deployment model that the gateway reply named, and no value when the reply named none. + +#### Scenario: A ledger from before the column +- **WHEN** a ledger that has no `served_model` column opens and records a `devops-chat` request whose reply names `openai/gpt-4o` +- **THEN** it keeps its rows, the old rows have no deployment model, and the new row has `openai/gpt-4o` diff --git a/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/tasks.md b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/tasks.md new file mode 100644 index 0000000000..1c05af7693 --- /dev/null +++ b/openspec/changes/archive/2026-10-24-2031-gateway-deployment-model-pricing/tasks.md @@ -0,0 +1,16 @@ +# Tasks + +## 1. Price a hosted gateway call at its deployment model + +- [x] 1.1 Write `test_a_hosted_gateway_reply_is_priced_at_the_deployment_model_that_it_names` in `tests/test_ai_served_by.py`, `test_a_gateway_call_is_priced_at_the_litellm_reference_of_its_deployment_model` and `test_a_price_override_of_the_deployment_model_prices_a_gateway_call` in `tests/test_ai_spend_pricing.py`, `test_a_hosted_gateway_embedding_is_priced_at_the_deployment_model_that_it_names` in `tests/test_rag_embeddings.py` and `test_a_call_priced_at_its_deployment_model_keeps_the_route_name_as_its_model_label` in `tests/test_telemetry_instruments.py`, extend the gateway header rule of `test_no_forbidden_constructs_remain` in `tests/test_url_credential_masking.py` to `x-litellm-model-name`, and verify that they fail on the base (`uv run devops ci test tests/test_ai_served_by.py tests/test_ai_spend_pricing.py tests/test_rag_embeddings.py tests/test_telemetry_instruments.py tests/test_url_credential_masking.py`) +- [x] 1.2 Add `CONST_AI_GATEWAY_SERVED_MODEL_HEADER`, `extract_served_model` and `stream_served_model`, carry `served_model` on `LLMResponse` and from the blocking, streamed and embedding paths to `track_request_spend`, and price it in `PricingRegistry.calculate_request_cost` under `CONST_GENAI_PRICES_LITELLM_PROVIDER` (`uv run devops ci test tests/test_ai_served_by.py tests/test_ai_spend_pricing.py tests/test_rag_embeddings.py tests/test_telemetry_instruments.py tests/test_url_credential_masking.py tests/test_ai_client_telemetry.py tests/test_ai_streaming.py tests/test_response_cache.py`) +- [x] 1.3 Describe the price of a gateway call in the description of `devops_cli_ai_spend_usd_total` and in the help of `devops ai cost set-price`, and generate the documents again (`uv run devops docs generate --sync-readme`, then `uv run devops docs check`) + +## 2. Record the deployment model in the spend ledger + +- [x] 2.1 Write `test_an_existing_ledger_gains_the_served_model_column` in `tests/test_ai_spend_ledger.py`, and verify that it fails on the base (`uv run devops ci test tests/test_ai_spend_ledger.py`) +- [x] 2.2 Add the `served_model` column, its in-place addition to an existing ledger and the `served_model` field of `SpendRecord`, and store the deployment model in `track_request_spend` (`uv run devops ci test tests/test_ai_spend_ledger.py tests/test_ai_served_by.py tests/test_ai_spend_cli.py tests/test_ai_spend_prometheus.py`) + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/ai-spend-pricing/spec.md b/openspec/specs/ai-spend-pricing/spec.md index ce9c1ec5fe..6492360af2 100644 --- a/openspec/specs/ai-spend-pricing/spec.md +++ b/openspec/specs/ai-spend-pricing/spec.md @@ -78,3 +78,43 @@ The spend ledger SHALL record reasoning tokens for each AI request, and the cost #### Scenario: Cost report displays reasoning share - **WHEN** `devops ai cost report --by backend` runs against the ledger - **THEN** the rendered table displays a Reasoning Share column + +### Requirement: A hosted gateway call is priced at the deployment model that the gateway names +When a gateway reply names the deployment model that served the call in the `x-litellm-model-name` header, devops-cli SHALL price a hosted call at that model, which genai-prices reads as a LiteLLM model reference. When the reply names no deployment model, devops-cli SHALL price the call at the model that the client asked for. A call that a local backend served SHALL stay local. + +#### Scenario: A blocking reply and a streamed reply that name `openai/gpt-4o` +- **WHEN** a `devops-chat` call through the gateway gets a reply from `https://api.openai.com` that names `openai/gpt-4o`, once as a blocking reply and once as a streamed reply +- **THEN** each row has the model `devops-chat`, the deployment model `openai/gpt-4o`, the pricing source `genai_prices:openai` and a cost of more than $0 + +#### Scenario: A reply that names no deployment model +- **WHEN** the reply of a hosted `devops-chat` call names no deployment model +- **THEN** the row has the model `devops-chat`, no deployment model, the pricing source `unknown` and a cost of $0 + +#### Scenario: An embedding request that names its deployment model +- **WHEN** a gateway embedding reply from `https://api.openai.com` names `openai/text-embedding-3-small` and counts 1,000,000 input tokens for the model `bge-m3:latest` +- **THEN** the row has the model `bge-m3:latest`, the deployment model `openai/text-embedding-3-small`, the pricing source `genai_prices:openai` and a cost of $0.02 + +#### Scenario: Deployment models of other providers +- **WHEN** hosted replies name `openai/gpt-4o`, `openai/text-embedding-3-small`, `bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0`, `openrouter/anthropic/claude-3.5-sonnet` and two times `openai/gpt-9-preview`, and a local backend names `ollama_chat/qwen3.8:27b` +- **THEN** the pricing sources are `genai_prices:openai`, `genai_prices:openai`, `genai_prices:aws`, `genai_prices:openrouter`, two times `unknown`, and `local`, and one warning names `openai/gpt-9-preview` and the provider `litellm` + +### Requirement: A price override of the deployment model prices a gateway call +When a gateway reply names a deployment model, a price override of that model SHALL price the hosted call, and a price override of the route name SHALL NOT. + +#### Scenario: Price overrides of the deployment model and of the route name +- **WHEN** price overrides exist for `gpt-4o` and for `devops-chat`, and a hosted `devops-chat` reply names `openai/gpt-4o` +- **THEN** the call has the price of `gpt-4o`, and a reply that names no deployment model has the price of `devops-chat` + +### Requirement: The metrics keep the model that the client asked for +devops-cli SHALL keep the model that the client asked for, such as a gateway route name, as the `model` label of the AI request, token and spend metrics of a call that the deployment model priced. + +#### Scenario: A hosted call that names `openai/gpt-4o` +- **WHEN** a hosted `devops-chat` call that names `openai/gpt-4o` and counts 1,000,000 input tokens is recorded +- **THEN** the request, token and spend points have the `model` label `devops-chat`, and the spend point is $2.50 + +### Requirement: Each spend-ledger row records the deployment model that priced it +Each spend-ledger row SHALL store, in `served_model`, the deployment model that the gateway reply named, and no value when the reply named none. + +#### Scenario: A ledger from before the column +- **WHEN** a ledger that has no `served_model` column opens and records a `devops-chat` request whose reply names `openai/gpt-4o` +- **THEN** it keeps its rows, the old rows have no deployment model, and the new row has `openai/gpt-4o` diff --git a/src/devops_cli/ai/client/models.py b/src/devops_cli/ai/client/models.py index a295f884d7..bedc0ed8c6 100644 --- a/src/devops_cli/ai/client/models.py +++ b/src/devops_cli/ai/client/models.py @@ -128,6 +128,7 @@ class LLMResponse(str): eval_duration_ms: float | None prompt_eval_duration_ms: float | None served_by: str | None + served_model: str | None model: str | None finish_reason: FinishReason | None @@ -148,6 +149,7 @@ def __new__( model: str | None = None, finish_reason: FinishReason | None = None, reasoning_tokens: int | None = None, + served_model: str | None = None, ) -> LLMResponse: obj = str.__new__(cls, content) obj.processing_seconds = processing_seconds @@ -163,6 +165,10 @@ def __new__( obj.cached = cached # The backend a gateway routed the call to; None when no gateway named one. obj.served_by = served_by + # The deployment model a gateway named as the model that served the call; None when no + # gateway named one. `model` is the model the reply body names: the route name for the + # gateway (#2031). + obj.served_model = served_model obj.model = model # Why the provider says the reply ended; None when it did not say. obj.finish_reason = finish_reason diff --git a/src/devops_cli/ai/client/network.py b/src/devops_cli/ai/client/network.py index b18fbdebc7..11706d010f 100644 --- a/src/devops_cli/ai/client/network.py +++ b/src/devops_cli/ai/client/network.py @@ -20,6 +20,7 @@ from devops_cli.config.constants import ( CONST_AI_GATEWAY_PROVIDER, CONST_AI_GATEWAY_SERVED_BY_HEADER, + CONST_AI_GATEWAY_SERVED_MODEL_HEADER, ) from devops_cli.config.defaults import ( DEFAULT_AI_MAX_RESPONSE_BYTES, @@ -83,6 +84,22 @@ def extract_served_by(headers: Mapping[str, str] | None) -> str | None: return str(u.copy_with(userinfo=b"")) +# The deployment model a gateway named in a streamed response's headers, read with the backend. +stream_served_model: ContextVar[str | None] = ContextVar("stream_served_model", default=None) + + +def extract_served_model(headers: Mapping[str, str] | None) -> str | None: + """The deployment model that a gateway reply names as the model that served the call, such as + `openai/gpt-4o`; None when the reply names none. + + The LiteLLM router writes the route name, such as `devops-chat`, in the reply body, so a + hosted call is priced at this model (#2031). + """ + if not headers: + return None + return (headers.get(CONST_AI_GATEWAY_SERVED_MODEL_HEADER) or "").strip() or None + + # Why a streamed reply ended, set by the stream reader when the provider's final frame arrives. # A generator's return value would be lost in the caller's `for` loop and the sanitizer wrapping # it, so the reason travels like the serving backend. diff --git a/src/devops_cli/ai/client/openai.py b/src/devops_cli/ai/client/openai.py index 90ad2d2967..fd64fd8534 100644 --- a/src/devops_cli/ai/client/openai.py +++ b/src/devops_cli/ai/client/openai.py @@ -4,7 +4,7 @@ import logging import time -from collections.abc import Generator +from collections.abc import Generator, Mapping from contextlib import AbstractContextManager, nullcontext from typing import Any @@ -18,9 +18,11 @@ from devops_cli.ai.client.network import ( acquire_gateway_slot, extract_served_by, + extract_served_model, reply_schema, request_limited_json, stream_served_by, + stream_served_model, stream_slot_wait, uses_gateway_slots, ) @@ -164,9 +166,10 @@ def _parse_compat_response( self, raw_json: dict[str, Any], wall_elapsed: float, - served_by: str | None, + reply_headers: Mapping[str, str] | None, ) -> LLMResponse: - """Parse raw OpenAI completion JSON into a structured LLMResponse.""" + """Parse raw OpenAI completion JSON into a structured LLMResponse, with the backend and + the deployment model that a gateway names in its reply headers.""" choices = raw_json.get("choices", [{}]) first_choice = choices[0] if choices else {} msg = first_choice.get("message", {}) @@ -190,7 +193,8 @@ def _parse_compat_response( prompt_tokens=usage.get("prompt_tokens"), completion_tokens=usage.get("completion_tokens"), total_tokens=usage.get("total_tokens"), - served_by=served_by, + served_by=extract_served_by(reply_headers), + served_model=extract_served_model(reply_headers), model=raw_json.get("model"), finish_reason=provider_finish_reason( CONST_OPENAI_FINISH_REASONS, first_choice.get("finish_reason") @@ -229,8 +233,7 @@ def _openai_compat_messages( timeout=self._request_timeout(), ) wall_elapsed = time.monotonic() - start_time - served_by = extract_served_by(reply_headers) - return self._parse_compat_response(raw_json, wall_elapsed, served_by) + return self._parse_compat_response(raw_json, wall_elapsed, reply_headers) except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: @@ -264,6 +267,7 @@ def _openai_compat_stream( response.read() response.raise_for_status() stream_served_by.set(extract_served_by(response.headers)) + stream_served_model.set(extract_served_model(response.headers)) yield from _read_event_stream(response, _openai_stream_frame, "Provider") except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index 738f89d886..7b7d71e6db 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -480,6 +480,7 @@ def _record_response_telemetry_and_spend( server=srv, backend_info=res.backend_info or self.backend_info, served_by=getattr(res, "served_by", None), + served_model=getattr(res, "served_model", None), prompt_tokens=p_tokens, completion_tokens=c_tokens, cached=res.cached, @@ -906,6 +907,7 @@ def chat_messages_stream( "ai.llm.stream", attributes=stream_attrs, kind=CONST_OTEL_SPAN_KIND_CLIENT ) as span_h: network.stream_served_by.set(None) + network.stream_served_model.set(None) network.stream_finish_reason.set(None) network.stream_slot_wait.set(0.0) network.stream_server.set(None) @@ -1008,6 +1010,7 @@ def _record_stream_spend( server=srv, backend_info=self.backend_info, served_by=network.stream_served_by.get(), + served_model=network.stream_served_model.get(), prompt_tokens=p_tokens, completion_tokens=c_tokens, cached=False, diff --git a/src/devops_cli/ai/rag/embeddings.py b/src/devops_cli/ai/rag/embeddings.py index ae811d0467..291dd992ac 100644 --- a/src/devops_cli/ai/rag/embeddings.py +++ b/src/devops_cli/ai/rag/embeddings.py @@ -712,9 +712,9 @@ def _record_embedding_request( """Record one answered embedding request in the spend ledger and the AI usage counters. The provider and server are those a chat call names, so both are local or hosted alike; - a gateway's header names the backend that served the request. + a gateway's headers name the backend and the deployment model that served the request. """ - from devops_cli.ai.client.network import extract_served_by + from devops_cli.ai.client.network import extract_served_by, extract_served_model from devops_cli.ai.spend import resolve_spend_stage, track_request_spend provider = self.ai_config.provider @@ -725,6 +725,7 @@ def _record_embedding_request( server=server, backend_info=f"{provider} ({server})", served_by=extract_served_by(res.headers), + served_model=extract_served_model(res.headers), prompt_tokens=_reply_input_tokens(res, parse_tokens, texts), request_type=CONST_SPEND_REQUEST_TYPE_EMBEDDING, duration_seconds=seconds, diff --git a/src/devops_cli/ai/spend/ledger.py b/src/devops_cli/ai/spend/ledger.py index 9fe0d73cfa..0e0f70cee1 100644 --- a/src/devops_cli/ai/spend/ledger.py +++ b/src/devops_cli/ai/spend/ledger.py @@ -57,7 +57,8 @@ stage TEXT, finish_reason TEXT, pricing_source TEXT, - reasoning_tokens INTEGER NOT NULL DEFAULT 0 + reasoning_tokens INTEGER NOT NULL DEFAULT 0, + served_model TEXT ); """ _QUERY_IDX_TIMESTAMP = ( @@ -81,6 +82,7 @@ "reasoning_tokens", "ALTER TABLE ai_spend_records ADD COLUMN reasoning_tokens INTEGER NOT NULL DEFAULT 0;", ), + ("served_model", "ALTER TABLE ai_spend_records ADD COLUMN served_model TEXT;"), ) _QUERY_INSERT_RECORD = """ @@ -88,8 +90,9 @@ timestamp, provider, server, backend_info, served_by, model, prompt_tokens, completion_tokens, total_tokens, cost_usd, cached, request_type, duration_seconds, stage, finish_reason, pricing_source, - reasoning_tokens -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + reasoning_tokens, + served_model +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); """ _QUERY_STAGE_BREAKDOWN = """ @@ -450,6 +453,7 @@ def record_request( finish_reason: FinishReason | None = None, pricing_source: str | None = None, reasoning_tokens: int = 0, + served_model: str | None = None, ) -> SpendRecord | None: """Record an inference request in the persistent SQLite ledger.""" ts = timestamp or datetime.now(UTC).isoformat() @@ -478,6 +482,7 @@ def record_request( finish_reason, pricing_source, reasoning_tokens, + served_model, ), ) rec_id = cursor.lastrowid @@ -500,6 +505,7 @@ def record_request( finish_reason=finish_reason, pricing_source=pricing_source, reasoning_tokens=reasoning_tokens, + served_model=served_model, ) except Exception: # Defensive logging: database failure must never crash user workflows @@ -818,6 +824,7 @@ def track_request_spend( server: str, backend_info: str | None = None, served_by: str | None = None, + served_model: str | None = None, prompt_tokens: int = 0, completion_tokens: int = 0, reasoning_tokens: int = 0, @@ -833,9 +840,12 @@ def track_request_spend( ``finish_reason`` is why the provider says the reply ended, None when it did not say; the ledger stores it and observers receive it. The metrics carry the call's GenAI operation: `embeddings` for an embedding request, `chat` for every other call. ``served_by``, the - backend a gateway reply names, decides whether the call is spend or local savings. The - ledger stores where the price came from. The tokens carry `local`, and no process sends a - price for them: the cluster prices local tokens at one reference for every process (#1672). + backend a gateway reply names, decides whether the call is spend or local savings. + ``served_model``, the deployment model a gateway reply names, prices a hosted call; ``model`` + stays the model that the client asked for, such as a gateway route name, in the ledger and + on the metrics, so they still group by it (#2031). The ledger stores where the price came + from. The tokens carry `local`, and no process sends a price for them: the cluster prices + local tokens at one reference for every process (#1672). """ from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import ( GenAiOperationNameValues, @@ -865,6 +875,7 @@ def track_request_spend( provider=provider, request_timestamp=now_utc, served_by=served_by, + served_model=served_model, ) ) cost = priced.cost_usd if priced else 0.0 @@ -888,6 +899,7 @@ def track_request_spend( finish_reason=finish_reason, pricing_source=pricing_source, reasoning_tokens=reasoning_tokens, + served_model=served_model, ) except Exception: rec = None diff --git a/src/devops_cli/ai/spend/models.py b/src/devops_cli/ai/spend/models.py index 7a3c4e9245..25a5fbfe7a 100644 --- a/src/devops_cli/ai/spend/models.py +++ b/src/devops_cli/ai/spend/models.py @@ -46,7 +46,11 @@ class SpendRecord(BaseModel): backend_info: str | None = None # The backend a gateway routed the call to (its api_base); None without a gateway. served_by: str | None = None + # The model the client asked for, such as a gateway route name. model: str + # The deployment model a gateway named as the model that served the call, which priced it; + # None when no gateway named one (#2031). + served_model: str | None = None prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 diff --git a/src/devops_cli/ai/spend/pricing.py b/src/devops_cli/ai/spend/pricing.py index a27dc1e58a..a350b3744a 100644 --- a/src/devops_cli/ai/spend/pricing.py +++ b/src/devops_cli/ai/spend/pricing.py @@ -14,6 +14,7 @@ from devops_cli.ai.spend.models import ModelPricing from devops_cli.config.constants import ( + CONST_GENAI_PRICES_LITELLM_PROVIDER, CONST_LOCAL_PROVIDER_NAMES, CONST_LOCAL_TRANSPORT_LABELS, CONST_PRICING_SOURCE_LOCAL, @@ -555,15 +556,23 @@ def calculate_request_cost( provider: str | None = None, request_timestamp: datetime | None = None, served_by: str | None = None, + served_model: str | None = None, ) -> RequestCost: """The cost of a request at its real token usage and timestamp, and its pricing source. A local call costs nothing, whatever override names its model or server (#1631). A hosted model that neither an override nor genai-prices prices costs $0 with the source `unknown`, and the registry logs one warning for each such model (#1672). + + `served_model` is the deployment model that a gateway reply names, a LiteLLM model + reference such as `openai/gpt-4o`. When the reply names it, a hosted call is priced at + it and not at `model`, the route name that the client asked for, which genai-prices does + not know. genai-prices takes the provider from the prefix of the reference (#2031). """ if is_local(server=server, provider=provider, served_by=served_by): return RequestCost(0.0, CONST_PRICING_SOURCE_LOCAL) + if served_model: + model, provider = served_model, CONST_GENAI_PRICES_LITELLM_PROVIDER override = self._get_override_pricing(model, server) if override is not None: diff --git a/src/devops_cli/commands/ai_cost.py b/src/devops_cli/commands/ai_cost.py index 13af1c1623..0bf3e0e1b4 100644 --- a/src/devops_cli/commands/ai_cost.py +++ b/src/devops_cli/commands/ai_cost.py @@ -715,7 +715,7 @@ def cost_set_price( target: Annotated[ str, typer.Argument( - help="Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). A local call costs nothing, also when it has a custom price. Its tokens count in local savings.", + help="Target model identifier or backend server address of hosted calls (e.g. 'gpt-4o', 'api.example.com'). When a gateway reply names its deployment model, such as 'openai/gpt-4o', that model is the target, not the route name. A local call costs nothing, also when it has a custom price. Its tokens count in local savings.", ), ], prompt_rate: Annotated[ diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 11879221de..2b78b59b1c 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -1192,6 +1192,9 @@ # `pricing_source` (#1672). CONST_PRICING_SOURCE_LOCAL: Final[str] = "local" CONST_PRICING_SOURCE_UNKNOWN: Final[str] = "unknown" +# The genai-prices provider ID that reads a LiteLLM model reference, such as `openai/gpt-4o`: +# genai-prices takes the provider from the prefix and the model from the rest (#2031). +CONST_GENAI_PRICES_LITELLM_PROVIDER: Final[str] = "litellm" CONST_URL_GITHUB_API_BASE = "https://api.github.com" # What the GitHub session sends with every REST request (#983): GitHub requires a User-Agent # naming the project or user, and the API version pins the REST contract the session reads. @@ -2884,6 +2887,9 @@ class WebhookExposure(StrEnum): CONST_CAPABILITY_PROBE_FORBIDDEN_WORDS: Final[tuple[str, ...]] = ("security", "vulnerability") CONST_CAPABILITY_PROBE_PROHIBITION_PREFIX: Final[str] = "SUMMARY:" +# Response header in which the LiteLLM gateway names the deployment model that served a call, +# such as `openai/gpt-4o`. The router writes the route name in the reply body (#2031). +CONST_AI_GATEWAY_SERVED_MODEL_HEADER: Final[str] = "x-litellm-model-name" # Why a provider says a reply ended, as pydantic-ai's FinishReason. The OpenAI-compatible and # Anthropic tables copy pydantic-ai 2.54.0's private maps (models/openai.py, models/anthropic.py), # which are not imported because they are private. A value absent from a table, or mapped to diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 652e0c6716..49145c16db 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -77,7 +77,9 @@ class Instrument: InstrumentKind.COUNTER, "USD", "Approximate LLM and embedding spend, by operation, provider, model, server and backend. " - "Each request that a model answers adds to it, and a local request adds 0", + "Each request that a model answers adds to it, and a local request adds 0. A hosted gateway " + "call is priced at the deployment model that the gateway names, and its model label is the " + "model that the client asked for, such as the route name", ) AI_JSON_REPAIRS_TOTAL = Instrument( "devops_cli_ai_json_repairs_total", diff --git a/tests/test_ai_served_by.py b/tests/test_ai_served_by.py index 5849d92ec0..e292ca5330 100644 --- a/tests/test_ai_served_by.py +++ b/tests/test_ai_served_by.py @@ -1,4 +1,5 @@ -"""Each gateway call records the backend that served it, for per-backend cost, time and quality.""" +"""Each gateway call records the backend that served it, for per-backend cost, time and quality, +and a hosted call is priced at the deployment model that the gateway names (#2031).""" from __future__ import annotations @@ -25,6 +26,10 @@ REMOTE = "http://remote.example.com:8000/v1" OLLAMA = "http://ollama-0.example.com:11434" SERVED_BY_HEADER = "x-litellm-model-api-base" +# LiteLLM 1.103.0 names the deployment model of the route in this header, and the router writes +# the route name in the reply body (#2031). +SERVED_MODEL_HEADER = "x-litellm-model-name" +HOSTED_API = "https://api.openai.com" # The ledger schema before the served_by column existed. _PREVIOUS_SCHEMA = """ @@ -51,9 +56,9 @@ def _public_endpoints(public_dns: str) -> None: """The configured endpoints are example.com URLs, which resolve to a public address.""" -def _gateway_client() -> LLMClient: +def _gateway_client(model: str = "devops-review") -> LLMClient: return LLMClient( - AIConfig(provider="gateway", gateway_url=GATEWAY_URL, model="devops-review"), + AIConfig(provider="gateway", gateway_url=GATEWAY_URL, model=model), api_key="sk-gateway", cache_enabled=False, ) @@ -171,6 +176,76 @@ def fake_send(self: Any, request: httpx2.Request, **kwargs: Any) -> httpx2.Respo assert (text, [c.get("served_by") for c in spend]) == ("OK", [OLLAMA]) +def _hosted_headers(served_model: str | None) -> dict[str, str]: + """The headers of a gateway reply that a hosted API served, with the deployment model.""" + headers = {SERVED_BY_HEADER: HOSTED_API} + if served_model is not None: + headers[SERVED_MODEL_HEADER] = served_model + return headers + + +def _chat_once(monkeypatch: pytest.MonkeyPatch, headers: dict[str, str]) -> None: + """One blocking `devops-chat` call, with a reply that counts one million prompt tokens.""" + body = { + "model": "devops-chat", + "choices": [{"message": {"content": "OK"}}], + "usage": {"prompt_tokens": 1_000_000, "completion_tokens": 0}, + } + route_llm_clients(monkeypatch, lambda request: httpx2.Response(200, json=body, headers=headers)) + _gateway_client("devops-chat").chat("You are terse.", "Reply with OK.", use_cache=False) + + +def _stream_once(monkeypatch: pytest.MonkeyPatch, headers: dict[str, str]) -> None: + """One streamed `devops-chat` call, whose headers arrive before the first chunk.""" + sse = b'data: {"model": "devops-chat", "choices": [{"delta": {"content": "OK"}}]}\n\n' + sse += b"data: [DONE]\n\n" + + def fake_send(self: Any, request: httpx2.Request, **kwargs: Any) -> httpx2.Response: + stream_headers = {**headers, "content-type": "text/event-stream"} + return httpx2.Response(200, headers=stream_headers, content=sse, request=request) + + monkeypatch.setattr(httpx2.Client, "send", fake_send) + "".join( + _gateway_client("devops-chat").chat_messages_stream( + "You are terse.", [ChatMessage(role="user", content="Reply with OK.")] + ) + ) + + +def _priced_rows(ledger: SpendLedger) -> list[tuple[Any, ...]]: + with contextlib.closing(sqlite3.connect(ledger.db_path)) as conn: + return conn.execute( + "SELECT model, served_model, pricing_source, cost_usd > 0 FROM ai_spend_records" + " ORDER BY id" + ).fetchall() + + +@pytest.mark.parametrize("call", [_chat_once, _stream_once], ids=["blocking", "stream"]) +@pytest.mark.parametrize( + ("served_model", "priced"), + [ + ("openai/gpt-4o", ("openai/gpt-4o", "genai_prices:openai", 1)), + (None, (None, "unknown", 0)), + ], + ids=["names-the-deployment", "names-no-deployment"], +) +def test_a_hosted_gateway_reply_is_priced_at_the_deployment_model_that_it_names( + monkeypatch: pytest.MonkeyPatch, + spend_ledger: SpendLedger, + call: Any, + served_model: str | None, + priced: tuple[Any, ...], +) -> None: + """genai-prices does not know the route name `devops-chat`, so a hosted call cost $0 (#2031). + + A reply that names its deployment model is priced at that model, and the row keeps the route + name as its model. A reply that names none is priced at the route name, as before. + """ + call(monkeypatch, _hosted_headers(served_model)) + + assert _priced_rows(spend_ledger) == [("devops-chat", *priced)] + + def test_cost_command_breaks_spend_down_by_backend( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_ai_spend_ledger.py b/tests/test_ai_spend_ledger.py index 87e1107f37..770bd87f05 100644 --- a/tests/test_ai_spend_ledger.py +++ b/tests/test_ai_spend_ledger.py @@ -655,6 +655,32 @@ def test_an_existing_ledger_gains_the_pricing_source_column(tmp_path: Path) -> N assert _pricing_sources(db_path) == [("qwen", None, 0.0), ("llama3:8b", "local", 0.0)] +def test_an_existing_ledger_gains_the_served_model_column(tmp_path: Path) -> None: + """Verify a ledger written before served_model existed keeps its rows and records the + deployment model that a gateway reply names (#2031).""" + db_path = tmp_path / "spend.db" + with contextlib.closing(sqlite3.connect(db_path)) as conn, conn: + conn.execute(_SCHEMA_BEFORE_FINISH_REASON) + conn.execute( + "INSERT INTO ai_spend_records (timestamp, provider, server, model) " + "VALUES ('2026-09-01T00:00:00+00:00', 'ollama', 'local', 'qwen')" + ) + + SpendLedger(db_path=db_path).record_request( + provider="gateway", + server="example.com:4000", + model="devops-chat", + served_model="openai/gpt-4o", + prompt_tokens=10, + completion_tokens=5, + cost_usd=0.0, + ) + + with contextlib.closing(sqlite3.connect(db_path)) as conn: + rows = conn.execute("SELECT model, served_model FROM ai_spend_records ORDER BY id") + assert rows.fetchall() == [("qwen", None), ("devops-chat", "openai/gpt-4o")] + + def test_spend_ledger_export_prometheus_with_report(tmp_path: Path) -> None: """Verify export_ai_spend_prometheus accepts precomputed report.""" from devops_cli.ai.spend.prometheus import export_ai_spend_prometheus diff --git a/tests/test_ai_spend_pricing.py b/tests/test_ai_spend_pricing.py index 7d1670da5d..0e9b34145c 100644 --- a/tests/test_ai_spend_pricing.py +++ b/tests/test_ai_spend_pricing.py @@ -789,6 +789,88 @@ def price(model: str, server: str, provider: str) -> RequestCost: ) +def test_a_gateway_call_is_priced_at_the_litellm_reference_of_its_deployment_model( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """The LiteLLM gateway names the deployment model of a call as a LiteLLM model reference, + such as `openai/gpt-4o`, and genai-prices takes the provider from its prefix. So each hosted + deployment is priced at the price of its provider, not at the route name `devops-chat` that + genai-prices does not know. A local backend stays local, and a deployment with no price + warns once with its own name (#2031).""" + registry = PricingRegistry(data_dir=tmp_path) + peak_ts = datetime(2026, 1, 1, 12, 0, tzinfo=UTC) + caplog.set_level(logging.WARNING, logger="devops_cli.ai.spend.pricing") + + def price(served_model: str | None, served_by: str = "https://api.openai.com") -> RequestCost: + return registry.calculate_request_cost( + "devops-chat", + 1_000_000, + 0, + server="example.com:4000", + provider="gateway", + request_timestamp=peak_ts, + served_by=served_by, + served_model=served_model, + ) + + hosted = [ + price(model) + for model in ( + "openai/gpt-4o", + "openai/text-embedding-3-small", + "bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0", + "openrouter/anthropic/claude-3.5-sonnet", + "openai/gpt-9-preview", + "openai/gpt-9-preview", + ) + ] + local = price("ollama_chat/qwen3.8:27b", "http://ollama-16gib.llm.svc.cluster.local:11434") + + assert ( + hosted, + local, + [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING], + ) == ( + [ + RequestCost(2.5, "genai_prices:openai"), + RequestCost(0.02, "genai_prices:openai"), + RequestCost(3.0, "genai_prices:aws"), + RequestCost(3.0, "genai_prices:openrouter"), + RequestCost(0.0, "unknown"), + RequestCost(0.0, "unknown"), + ], + RequestCost(0.0, "local"), + [ + "genai-prices and the price overrides hold no price for model openai/gpt-9-preview under provider litellm. Its requests are recorded at $0 with the pricing source unknown." + ], + ) + + +def test_a_price_override_of_the_deployment_model_prices_a_gateway_call(tmp_path: Path) -> None: + """When a gateway reply names its deployment model, that model is the target of a price + override, not the route name. A reply that names none takes the price of the route name, as + the help of `devops ai cost set-price` says (#2031).""" + registry = PricingRegistry(data_dir=tmp_path) + registry.set_custom_pricing("gpt-4o", prompt_rate=1.0, completion_rate=2.0) + registry.set_custom_pricing("devops-chat", prompt_rate=9.0, completion_rate=9.0) + + def price(served_model: str | None) -> RequestCost: + return registry.calculate_request_cost( + "devops-chat", + 1_000_000, + 1_000_000, + server="example.com:4000", + provider="gateway", + served_by="https://api.openai.com", + served_model=served_model, + ) + + assert (price("openai/gpt-4o"), price(None)) == ( + RequestCost(3.0, "custom_override"), + RequestCost(18.0, "custom_override"), + ) + + def test_only_the_defaults_name_the_default_reference_model() -> None: """The default reference model is named in `config/defaults.py` alone, and other code reads `DEFAULT_AI_REFERENCE_MODEL`, so a changed default changes every use (#1672).""" diff --git a/tests/test_rag_embeddings.py b/tests/test_rag_embeddings.py index 2d5f798d85..4ac6753242 100644 --- a/tests/test_rag_embeddings.py +++ b/tests/test_rag_embeddings.py @@ -1124,6 +1124,38 @@ def test_a_gateway_batch_records_one_embedding_row_with_the_replys_tokens_and_ba ) +def test_a_hosted_gateway_embedding_is_priced_at_the_deployment_model_that_it_names( + monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger +) -> None: + """A gateway reply that a hosted API served names its deployment model in + `x-litellm-model-name`. The row is priced at that model and keeps the requested model (#2031). + """ + + def hosted_reply(request: httpx2.Request) -> httpx2.Response: + texts = _inputs(request) + return httpx2.Response( + 200, + headers={ + CONST_AI_GATEWAY_SERVED_BY_HEADER: "https://api.openai.com", + "x-litellm-model-name": "openai/text-embedding-3-small", + }, + json={ + "data": [{"index": i, "embedding": [0.5] * 4} for i in range(len(texts))], + "usage": {"prompt_tokens": 1_000_000, "total_tokens": 1_000_000}, + }, + ) + + _serve(monkeypatch, hosted_reply) + + _gateway_engine().embed_texts(["hosted chunk"]) + + with contextlib.closing(sqlite3.connect(spend_ledger.db_path)) as conn: + rows = conn.execute( + "SELECT model, served_model, pricing_source, cost_usd FROM ai_spend_records" + ).fetchall() + assert rows == [("bge-m3:latest", "openai/text-embedding-3-small", "genai_prices:openai", 0.02)] + + def test_a_batch_retried_after_http_429_records_one_row( monkeypatch: pytest.MonkeyPatch, spend_ledger: SpendLedger ) -> None: diff --git a/tests/test_telemetry_instruments.py b/tests/test_telemetry_instruments.py index 780643baf7..7149b686fa 100644 --- a/tests/test_telemetry_instruments.py +++ b/tests/test_telemetry_instruments.py @@ -513,6 +513,29 @@ def test_a_gateway_call_is_spend_or_savings_by_the_backend_that_served_it( ) == ([spent], {str(saved).lower()}) +def test_a_call_priced_at_its_deployment_model_keeps_the_route_name_as_its_model_label( + captured: Captured, spend_ledger: SpendLedger +) -> None: + """Verify a hosted gateway call is priced at the deployment model that the gateway names, + and its points keep the model that the client asked for, so the dashboards still group by + the route name (#2031).""" + track_request_spend( + provider="gateway", + model="devops-chat", + server="example.com:4000", + served_by="https://api.openai.com", + served_model="openai/gpt-4o", + prompt_tokens=1_000_000, + completion_tokens=0, + ) + + assert ( + [(a["model"], v) for a, v in captured.points("devops_cli_ai_spend_usd_total")], + {a["model"] for a, _ in captured.points("devops_cli_ai_tokens_total")}, + [a["model"] for a, _ in captured.points("devops_cli_ai_requests_total")], + ) == ([("devops-chat", 2.5)], {"devops-chat"}, ["devops-chat"]) + + def test_a_price_override_leaves_a_local_call_in_local_savings( captured: Captured, spend_ledger: SpendLedger ) -> None: diff --git a/tests/test_url_credential_masking.py b/tests/test_url_credential_masking.py index 7a012deecf..b2962bfb52 100644 --- a/tests/test_url_credential_masking.py +++ b/tests/test_url_credential_masking.py @@ -22,6 +22,9 @@ pytestmark = pytest.mark.usefixtures("mock_keyring") +# The only source files that may name a header of a gateway reply. +_GATEWAY_HEADER_FILES = ("config/constants.py", "ai/client/network.py") + def _eval_ssrf_target(input_str: str) -> Any: return SSRFBlockedError(input_str).details["target_url"] @@ -435,21 +438,18 @@ def test_no_forbidden_constructs_remain() -> None: res3 = subprocess.run(cmd3, cwd=REPO_ROOT, capture_output=True, text=True) assert (res3.returncode, res3.stdout.strip()) == (1, "") - # 4. Check served_by header references: only constants.py and network.py - cmd4 = [ - "git", - "grep", - "-n", - "-E", + # 4. Check gateway reply header references: only constants.py and network.py. The served-by + # header names the backend, and the served-model header the deployment model (#2031). + for header_pattern in ( "CONST_AI_GATEWAY_SERVED_BY_HEADER|x-litellm-model-api-base", - "src", - ] - res4 = subprocess.run(cmd4, cwd=REPO_ROOT, capture_output=True, text=True) - lines = [line.split(":")[0] for line in res4.stdout.strip().splitlines() if line] - assert ( - res4.returncode == 0 - and len(lines) >= 2 - and all( - p.endswith("config/constants.py") or p.endswith("ai/client/network.py") for p in lines - ) - ) + "CONST_AI_GATEWAY_SERVED_MODEL_HEADER|x-litellm-model-name", + ): + cmd4 = ["git", "grep", "-n", "-E", header_pattern, "src"] + res4 = subprocess.run(cmd4, cwd=REPO_ROOT, capture_output=True, text=True) + lines = [line.split(":")[0] for line in res4.stdout.strip().splitlines() if line] + assert ( + header_pattern, + res4.returncode, + len(lines) >= 2, + sorted({p for p in lines if not p.endswith(_GATEWAY_HEADER_FILES)}), + ) == (header_pattern, 0, True, [])