Skip to content

fix(llm): Pass the OpenRouter cost of a streamed call through #6165

Done

Description

@dan-petty

Update 2026-11-26 (infra move): the gateway and monitoring files are now in dan-petty/homelab.

  • The ingress rule that lets devops reach Prometheus on TCP 9090 is a follow-up issue there.
  • This issue keeps the command, the CronJob, the egress rule, the secret row and the product alert.
  • Read k8s/llm/... below as a homelab path.

Follow-up: dan-petty/homelab#310.


Problem

Owner, 2026-11-17: "litellm prices should be passed through and accurate". They are not for streamed calls.

  • OpenRouter Activity, last 1 day: $6.92 total, 522M tokens, cache hit rate 95.5%.
  • The gateway counters for the same day (litellm_spend_metric_total, api_provider="openrouter"): $5.85 ($3.60 deepseek/deepseek-v4.1-flash-1017, $2.25 deepseek/deepseek-v4.1-flash) for 517.7M tokens. The tokens agree within 1%, so the spend is about 15% low on price, not on traffic.
  • Cause: LiteLLM v1.103.11 (litellm/llms/openrouter/chat/transformation.py) always asks OpenRouter for usage accounting (usage.include: true) and, in transform_response (no stream), copies usage.cost into the hidden header llm_provider-x-litellm-response-cost, so the billed cost passes through. The streaming handler (OpenRouterChatCompletionStreamingHandler.chunk_parser) keeps usage but sets no cost. A streamed call is then priced from the model_info prices that k8s/llm/gateway/config.yaml of dan-petty/homelab writes for each DeepSeek deployment (order 1: 0.0784 / 0.2352 / cache read 0.002352 USD per million; order 2: 0.30 / 1.20), which are fixed estimates. The roadmap jobs stream (fix(ai): one retry layer for a gateway call #5965).
  • LiteLLM 1.109.1 has the same streaming handler, so an upgrade alone does not fix it (chore(k8s): Update the LLM gateway to LiteLLM 1.109.1 #6001).

Expected behavior

  • The gateway records the cost that OpenRouter bills for each call, streamed or not: the usage.cost of the final stream chunk, through the open tool first (an upstream LiteLLM fix or a supported LiteLLM hook), and no hand-kept price table for OpenRouter deployments.
  • A daily check compares the gateway spend of OpenRouter with the spend that OpenRouter reports for the same day (its activity or key usage API) and fails, or alerts, when they differ by more than 5%.
  • Until the pass-through works, the model_info prices of the DeepSeek deployments match the prices of the providers that OpenRouter routes them to (the fp8 filter), with the source and date in a comment.

Related

Alternatives check of 2026-11-24: in-use.
The repository already uses this tool.
Tool: BerriAI/litellm (https://github.com/BerriAI/litellm), NOASSERTION, last activity 2026-11-24, maintained.
Reason: Searches found no maintained tool that passes OpenRouter's billed streamed cost into gateway spend or reconciles it daily; the in-use LiteLLM gateway already passes usage.cost for non-streamed calls and offers the callback hook, so it covers only part.

Covers:

  • Non-streamed OpenRouter usage.cost already passes through
  • CustomLogger callbacks hook exists for pricing and spend
  • Gateway spend metrics and per-deployment model_info prices

Lacks:

  • No streamed usage.cost in v1.103.11 or v1.109.1
  • No daily reconciliation against OpenRouter activity totals
  • Fixed model_info estimates drift from provider fp8 rates

Proposed design

Problem statement

Streamed OpenRouter calls are priced from the fixed model_info prices, so the gateway spend was about 15% below the OpenRouter bill ($5.85 against $6.92 on 2026-11-17). The gateway and monitoring files are in dan-petty/homelab, so this repository adds only the daily reconciliation: it compares the gateway spend of a day with the OpenRouter activity total, exits 1 over 5 percent, and alerts when the Job fails. It also adds the CronJob, the key Secret, the egress rule to Prometheus and the pod label that homelab#310 admits. Gate: the Job reaches Prometheus only after a person merges dan-petty/homelab#310.

Acceptance criteria

Requirement: Gateway spend of the day

The reconciliation MUST read the gateway OpenRouter spend of a day as the Prometheus value of sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d])) at 00:00 UTC of the next day.

Scenario: Prometheus gives the day spend

  • WHEN A unit test gives the Prometheus client a fake response with the value 5.85 and runs the reader for 2026-11-17.
  • THEN The request holds the query sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d])) at 2026-11-18T00:00:00Z, and the reader returns 5.85.

Requirement: Prometheus retry

The Prometheus reader MUST retry a refused connection with a bounded backoff before it fails.

Scenario: The first connections are refused

  • WHEN A unit test gives the reader a fake transport that refuses the first two connections and returns 5.85 on the third.
  • THEN The reader makes three attempts, waits between the attempts, and returns 5.85.

Requirement: Activity request

The activity reader MUST request the OpenRouter activity endpoint for the day with the gateway key as a bearer token.

Scenario: The request names the day and the key

  • WHEN A unit test runs the reader for 2026-11-17 with DEVOPS_CLI_OPENROUTER_API_KEY set to a test key and a fake HTTP transport.
  • THEN The recorded request is GET https://openrouter.ai/api/v1/activity?date=2026-11-17 with the header Authorization: Bearer <test key>.

Requirement: Activity total of the day

The activity reader MUST sum the usage field of the rows of the requested day.

Scenario: Rows of another day are ignored

  • WHEN A unit test gives the reader a recorded activity response with two rows of 2026-11-17 whose usage is 4.10 and 2.82, and one row of 2026-11-16.
  • THEN The reader returns 6.92.

Requirement: Daily reconciliation fails over 5 percent

The command MUST exit 1 when the gateway spend and the activity total of a day differ by more than 5 percent.

Scenario: Spend is 15 percent low

  • WHEN A unit test calls the reconciliation with the gateway total 5.85 USD and the activity total 6.92 USD for 2026-11-17.
  • THEN The command exits 1 and prints a message with both totals and their percentage difference.

Requirement: Daily reconciliation passes within 5 percent

The command MUST exit 0 when the two daily totals differ by at most 5 percent.

Scenario: Spend is within tolerance

  • WHEN A unit test calls the reconciliation with the gateway total 6.60 USD and the activity total 6.92 USD for 2026-11-17.
  • THEN The command exits 0 and prints a message with the difference.

Requirement: Daily reconciliation CronJob

A CronJob MUST run ai spend reconcile-openrouter once each day in namespace devops.

Scenario: The rendered CronJob has the schedule, the args and the label

  • WHEN uv run devops ci --check --only k8s validates the rendered devops manifests.
  • THEN The check passes and the CronJob openrouter-reconcile has a daily schedule, the args ai spend reconcile-openrouter, the variable DEVOPS_CLI_PROMETHEUS_URL set to http://prometheus-server.monitoring.svc.cluster.local:9090, and the pod label app.kubernetes.io/name: openrouter-reconcile.

Requirement: Reconciliation key

Secret devops/openrouter-activity MUST hold DEVOPS_CLI_OPENROUTER_API_KEY adopted from key openrouter-api-key of Secret llm/llm-gateway-secrets.

Scenario: The cluster Secret plan adopts the key

  • WHEN A unit test builds the cluster Secret plan.
  • THEN The devops/openrouter-activity Secret holds DEVOPS_CLI_OPENROUTER_API_KEY with an adopt_from reference to key openrouter-api-key of Secret llm/llm-gateway-secrets.

Requirement: Reconciliation alert

A Prometheus rule MUST alert when the daily reconciliation Job fails.

Scenario: The rule selects the failed Job

  • WHEN uv run devops ci --check --only k8s validates the rendered monitoring rules.
  • THEN The check passes and the rule expression selects kube_job_status_failed of the Job openrouter-reconcile.

Requirement: Egress to Prometheus

The devops egress rule MUST allow TCP 9090 to monitoring for the pods that carry the label app.kubernetes.io/name: openrouter-reconcile only.

Scenario: The egress rule selects the reconciliation pods

  • WHEN uv run devops ci --check --only k8s validates the rendered network policies.
  • THEN The check passes and the devops egress rule that names monitoring on port 9090 selects the pod label app.kubernetes.io/name: openrouter-reconcile and no other pod.

Requirement: Pending a person after the merge

The reconciliation Job MUST reach Prometheus after a person merges dan-petty/homelab#310, which admits the label app.kubernetes.io/name: openrouter-reconcile on TCP 9090.

Scenario: One manual Job run reaches Prometheus

  • WHEN A person creates one Job from CronJob openrouter-reconcile after dan-petty/homelab#310 merges.
  • THEN The Job exits 0 and its log shows the two daily totals and their difference.

Existing Tool Considered

BerriAI/litellm (https://github.com/BerriAI/litellm), verdict in-use: the alternatives check in the issue body records what the tool covers and lacks. The gateway files are in dan-petty/homelab, so this change adds no gateway workaround. It builds the daily reconciliation in devops-cli on the existing devops prometheus client and the OpenRouter activity endpoint, which the tool lacks: about 220 lines of code and 320 lines of tests, about 45k tokens to build and review, about 6 hours of elapsed time, and about 8k tokens a month to keep and fix.

Key questions

  • Where does the streamed-cost pass-through itself go?: To dan-petty/homelab, which holds the gateway. This repository holds no environment tree, so this change adds only the daily reconciliation and its cluster plumbing. The reconciliation shows whether the pass-through works. (best practice) [sources: CONTEXT.md]
    • Chosen: Keep the gateway change in dan-petty/homelab. CONTEXT.md states that the environment of the homelab cluster lives only in dan-petty/homelab.
    • Rejected: Add a LiteLLM callback in this repository. The gateway image and its config are in homelab, so a callback here would not load.
  • Which OpenRouter endpoint gives a past day's billed total?: The activity endpoint, GET https://openrouter.ai/api/v1/activity?date=YYYY-MM-DD, read with the gateway key as a bearer token. No source in the repository yet confirms the path, the parameter or the response shape, so keep the URL, the query and the parsing in one function with one recorded fixture. (best practice) [sources: docs/ENV_VARS.md:198]
    • Chosen: Activity endpoint with the day parameter. It is the endpoint that the issue names for a day's total, and the Job needs a past day.
    • Rejected: Key usage endpoint. The earlier proposal recorded no source that it gives a past day, so the reader stays in one function until a fixture shows the shape.
  • Which Prometheus query gives the gateway OpenRouter spend of a day?: sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d])), evaluated at 00:00 UTC of the next day, through the existing devops prometheus client. The 1-day window at the day's end is the calendar day, not a rolling 24 hours from the run time. (best practice) [sources: k8s/devops/dashboards/ai-spend.json, docs/ENV_VARS.md:199, docs/CONFIGURATION.md:78, tests/commands/test_prometheus.py:21]
    • Chosen: Reuse the devops prometheus client. The repository already reads Prometheus with it and reads the address from DEVOPS_CLI_PROMETHEUS_URL.
    • Rejected: Build a new HTTP client. It repeats the address, the timeout and the error handling of an existing client.
  • Where does the reconcile-openrouter command live?: In src/devops_cli/commands/ai_cost.py, the Typer app that serves the spend commands. The ai spend group and the ai cost group use the same app, so one module serves both names. [sources: src/devops_cli/commands/ai_cost.py, src/devops_cli/commands/ai.py, docs/CLI_REFERENCE.md]
  • How does the reconciliation pod get the OpenRouter key?: From a new Secret devops/openrouter-activity, whose DEVOPS_CLI_OPENROUTER_API_KEY is adopted from key openrouter-api-key of Secret llm/llm-gateway-secrets, read by the pod with valueFrom.secretKeyRef. Secret devops-cli is loaded with envFrom by every Job pod, so a provider key must not go there. (best practice) [sources: src/devops_cli/k8s/cluster_secrets.py:230, tests/k8s/test_cluster_secret_plan.py, SECURITY.md, k8s/devops/cronjob-repos-drift.yaml]
    • Chosen: Dedicated Secret read with secretKeyRef. Only the reconciliation pod holds the key, and the key keeps its one source.
    • Rejected: Add the key to Secret devops-cli. Every pod that loads that Secret with envFrom would hold the provider key.
  • Does the daily check fail, alert, or both?: Both. The command exits 1 over 5 percent, as the nightly drift Job exits 1 on a drift, and a Prometheus rule alerts on kube_job_status_failed of the Job. (best practice) [sources: k8s/devops/cronjob-repos-drift.yaml, k8s/devops/monitoring/prometheus-rules-values.yaml]
    • Chosen: Fail and alert. The command gives a testable exit status, and the rule makes the daily failure visible.
    • Rejected: Fail only. A failed CronJob with no alert is silent.
    • Rejected: Alert only. A manual run would have no failing exit status.
  • Which pods does the egress rule select, and how does the Job survive the kube-router sync?: The CronJob pod template carries the label app.kubernetes.io/name: openrouter-reconcile. The devops egress rule to monitoring on TCP 9090 selects that label only, and dan-petty/homelab#310 admits the same label. kube-router admits a new pod as an ingress source at its next policy sync, 0.3 s to 1.7 s, so the command retries the first Prometheus query with a bounded backoff. (best practice) [sources: k8s/devops/networkpolicy.yaml]
    • Chosen: A dedicated pod label and a retry. homelab#310 selects the label, and the retry covers the policy sync delay.
    • Rejected: Admit the whole devops namespace. homelab#310 admits only the reconciliation pods, and the reply says the egress must match.
  • Do the gateway model_info prices or the client price table change?: No. The gateway prices are homelab config, and the client price table in src/devops_cli/ai/spend/pricing.py prices local and hosted calls, not the gateway's OpenRouter routes. A call whose final chunk carries no usage.cost still records the fallback price. (best practice) [sources: CONTEXT.md, src/devops_cli/ai/spend/pricing.py]
    • Chosen: Keep both price tables as the fallback. The billed cost wins when LiteLLM sets it, and a call with no cost still records a price.
    • Rejected: Remove the OpenRouter prices. A call whose final chunk carries no cost would record zero cost.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    type/bug
    on Nov 17, 2026
  2. dan-petty commented on Nov 17, 2026

    @dan-petty
    OwnerAuthor
    • Scope: none. The title has the scope llm, and .github/labels.yml declares no scope/llm label. Add the label to the file to give the scope to this item.
    • Related: fix(ai): record the gateway cost of each gateway call #4734, which asks for a different change. Both address gateway cost being recorded lower than actual, but #4734 fixes the CLI-side pricing computation while this candidate fixes the gateway streaming handler that drops usage.cost.
  3. added
    source/agent
    status/new
    value/medium
    effort/medium
    priority/p2-medium
    on Nov 17, 2026
  4. devops-cli-service commented on Nov 18, 2026

    @devops-cli-service
    Contributor

    The result in the alternatives block of the issue body changed. Before this check: no check. A person decides what the new result means for the item.

    Searches (10)

    Tools considered:

    Searches run:

    • LiteLLM OpenRouter streaming response cost usage chunk pass through, results: 5
    • litellm custom callback pass cost for streaming calls spend tracking, results: 5
    • litellm docs custom logging callback response_cost streaming, results: 5
    • BerriAI litellm github issue OpenRouter stream cost not tracked, results: 5
    • "litellm" openrouter "usage.cost" streaming, results: 5
    • litellm openrouter usage cost streaming, results: 5
    • OpenRouter usage accounting cost API, results: 5
    • github BerriAI litellm repository, results: 5
    • openrouter, results: 5
    • litellm, results: 5

    Sources:

  5. added
    status/ready
    and removed
    status/new
    on Nov 18, 2026
  6. devops-cli-service commented on Nov 18, 2026

    @devops-cli-service
    Contributor

    Status set to Ready at 8d638d7 (see proposed design in issue body).

  7. added
    owner/agent
    and removed
    owner/agent
    on Nov 25, 2026
  8. dan-petty commented on Nov 25, 2026

    @dan-petty
    OwnerAuthor

    Returning #6165 to New because its core premise (litellm:v1.103.11 lacks streamed OpenRouter usage.cost pass-through and requires a custom openrouter_cost.py callback + fallback price update) has been overtaken on main, and the fp8 fallback-price rule is underspecified against the live OpenRouter API:

    1. Gateway already upgraded past v1.103.11: PR fix(deps): update container images #6817 (fb349e537, merged 2026-11-23) updated k8s/llm/gateway/deployment.yaml from ghcr.io/berriai/litellm:v1.103.11 to ghcr.io/berriai/litellm:1.110.2 (and uv.lock is at litellm==1.110.3). This issue was refined at sha=8d638d707 assuming v1.103.11 would stay pinned.
    2. Streamed OpenRouter usage.cost pass-through is already fixed in LiteLLM 1.110.2: In both BerriAI/litellm v1.110.2 (litellm/litellm_core_utils/streaming_handler.py _USAGE_COST_HEADER_PROVIDERS and CustomStreamWrapper._propagate_usage_cost_to_hidden_params) and local 1.110.3, streamed OpenRouter chunks already propagate usage.cost into response.hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"], which Logging.response_cost_calculator uses ahead of model_info estimates. Verified locally on OpenRouter streamed chunks (usage.cost = 0.00042 with conflicting 0.0005 token estimates): both kwargs["response_cost"] and standard_logging_object["response_cost"] in async_log_success_event are 0.00042. Building an injected openrouter_cost.py ConfigMap callback contradicts the issue's own open-tool-first rule now that LiteLLM 1.110.2 includes the fix. (Also note that in 1.110.2/1.110.3, dotted litellm_settings.callbacks entries must resolve to an instance module.instance, and async_logging_hook/async_log_success_event run after standard_logging_object["response_cost"] has already been computed.)
    3. DeepSeek fp8 fallback price rule is ambiguous against live OpenRouter endpoints: On 2026-11-25, https://openrouter.ai/api/v1/models/deepseek/deepseek-v4.1-flash-1017/endpoints and .../deepseek-v4.1-flash/endpoints include quantization == "fp8" endpoints in priority and ultrafast tiers (e.g. morph/fast at $0.60/$2.40 per M and venice/ultrafast at $1.50/$6.00 per M, 5x list price) alongside standard service_tier: null endpoints (venice/fp8, featherless/fp8), with no single endpoint holding the highest prompt, completion, and cache-read rate simultaneously and no service_tier filter rule in the spec; furthermore, those table updates were only specified "until the pass-through works."

    Suggested re-scope for refinement: drop the v1.103.11 openrouter_cost.py callback / ConfigMap workaround (and temporary model_info table bump), and scope the item cleanly if daily OpenRouter activity reconciliation (ai spend reconcile-openrouter, CronJob/alert, and DEVOPS_CLI_OPENROUTER_API_KEY) is still desired against litellm:1.110.2.

  9. 2 remaining items

  10. added
    status/ready
    and removed
    status/new
    on Nov 25, 2026
  11. devops-cli-service commented on Nov 25, 2026

    @devops-cli-service
    Contributor

    Next step: the stage job writes the plan of the item. See the section Proposed design of the body.

  12. dan-petty commented on Nov 27, 2026

    @dan-petty
    OwnerAuthor

    Input for the plan of this item from dan-petty/homelab#310 (checked live on 2026-11-27):

    • The path from namespace devops to prometheus-server.monitoring:9090 is closed on both sides today. A temporary pod with no NetworkPolicy got Connection refused from Prometheus (the monitoring ingress refuses). A temporary pod in devops got Connection refused from a test server on 9090 that admits all traffic (the devops egress refuses). Evidence: https://github.com/dan-petty/homelab/issues/310#issuecomment-7220019545
    • The requirement "Reconciliation reaches Prometheus" says that monitoring admits the whole devops namespace on 9090. homelab#310 admits only the reconciliation pods. The plan must give those pods a label of their own and name it, so that homelab#310 can select them.
    • The egress rule to monitoring on 9090 must also select only those pods, not the whole devops perimeter.
    • kube-router admits a new pod as an ingress source only at its next policy sync (0.3 s to 1.7 s on this cluster, homelab k8s/README.md, NetworkPolicy). The first Prometheus query of the Job can get Connection refused, so the command must retry it.
  13. devops-cli-service commented on Nov 27, 2026

    @devops-cli-service
    Contributor

    Next step: the stage job writes the plan of the item. See the section Proposed design of the body.

  14. added
    owner/agent
    status/in-progress
    status/in-review
    and removed
    status/ready
    status/in-progress
    on Nov 29, 2026
  15. removed
    status/in-review
    owner/agent
    on Nov 29, 2026
  16. devops-cli-service commented on Nov 29, 2026

    @devops-cli-service
    Contributor

    Live since 2026-11-29 16:17 UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/mediumpriority/p2-mediumsource/agenttype/bugvalue/medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions