AI › AI Tools

Tracking LiteLLM Proxy spend with custom pricing and privacy

Verify custom token pricing, /spend/logs/v2 request ID lookup, and PostgreSQL zero-message logging in LiteLLM Proxy v1.112.0 with Ollama and a mock server.

Tracking LiteLLM Proxy spend with custom pricing and privacy

Self-hosted Ollama models and internal inference endpoints often return token counts in usage while omitting x-litellm-response-cost and logging 0 spend. In LiteLLM Proxy v1.112.0, pairing model_info custom token pricing with turn_off_message_logging: true tracks per-request cost accurately while keeping prompts and responses out of PostgreSQL.

Every result in this note was verified on ghcr.io/berriai/litellm:v1.112.0 and postgres:17-alpine using non-streaming requests against a live local Ollama qwen2.5:1.5b model and a deterministic local Python OpenAI-compatible upstream server.

An internal HR and policy FAQ assistant (policy-qa-bot) usually faces two conflicting requirements. Finance needs per-request token counts and dollar spend in a database for chargeback, while compliance forbids storing raw employee prompts or assistant answers in log tables. Mixing a local Ollama model with an internal billed inference endpoint adds a second snag: models missing from LiteLLM’s built-in price map show up with $0 spend even when token counts are present.

Why local models log zero cost and how spend layers fit

After an upstream call finishes, LiteLLM Proxy reads prompt_tokens and completion_tokens from the response usage object and looks up the model in its bundled price map (model_prices_and_context_window.json). Commercial cloud models have built-in rates, so cost calculation works out of the box. Local Ollama models and custom internal aliases are either absent from that map or priced at 0. As a result, LiteLLM omits the x-litellm-response-cost header and writes spend = 0 to PostgreSQL.

Cost calculation and prompt redaction sit across three layers:

flowchart TD
    A["policy-qa-bot request"] --> B["LiteLLM Proxy (v1.112.0)"]
    B --> C["Custom pricing (model_info)"]
    B --> D["Message filter (turn_off_message_logging)"]
    C --> E["Response headers (cost, call-id)"]
    D --> F["PostgreSQL (LiteLLM_SpendLogs)"]

Picking the right layer for each consumer avoids duplicate parsing later:

Observability layerAvailable fieldsStrengthsPractical limits
Response body usageprompt_tokens, completion_tokens, total_tokensImmediate, no extra queryNo dollar cost
Response headers x-litellm-*x-litellm-response-cost, x-litellm-call-idEasy to emit into app logsCost header is omitted when unpriced
/spend/logs/v2 & PostgreSQLspend, tokens, key_alias, metadataSupports period and key aggregationAsync flush delay; API requires UTC dates

You don’t need custom pricing or database spend logs in every setup. If a single team runs local models on fixed-cost GPUs and never bills by token, maintaining a PostgreSQL spend pipeline adds overhead with little payoff. This pattern makes sense when multiple services share one gateway and you need per-key cost accounting or budget enforcement across custom endpoints.

Setting up custom pricing and zero-message logging

The test setup models policy-qa-bot calling two aliases through the same proxy:

  • policy-local: routes to a live local Ollama qwen2.5:1.5b instance with no custom pricing.
  • policy-metered: routes to a local OpenAI-compatible server (:18103) that returns fixed token counts (120 prompt, 40 completion) and a fixed completion ID (chatcmpl-upstream-policy-001).

compose.yaml starts PostgreSQL 17 and LiteLLM Proxy v1.112.0, mapping host.docker.internal so the container can reach both Ollama and the local upstream server on the host.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# compose.yaml
services:
  postgres:
    image: postgres:17-alpine
    environment:
      POSTGRES_DB: litellm
      POSTGRES_USER: litellm
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U litellm -d litellm"]
      interval: 2s
      timeout: 3s
      retries: 20

  litellm:
    image: ghcr.io/berriai/litellm:v1.112.0
    depends_on:
      postgres:
        condition: service_healthy
    ports:
      - "14003:4000"
    environment:
      LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
      DATABASE_URL: postgresql://litellm:${POSTGRES_PASSWORD}@postgres:5432/litellm
    volumes:
      - ./config.yaml:/app/config.yaml:ro
    command: ["--config", "/app/config.yaml", "--port", "4000"]
    extra_hosts:
      - "host.docker.internal:host-gateway"

In config.yaml, policy-metered defines per-token USD rates under model_info, and litellm_settings.turn_off_message_logging: true disables storing prompt and response payloads.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# config.yaml
model_list:
  - model_name: policy-local
    litellm_params:
      model: ollama_chat/qwen2.5:1.5b
      api_base: http://host.docker.internal:11434
    model_info:
      id: policy-local-ollama

  - model_name: policy-metered
    litellm_params:
      model: openai/policy-metered-v1
      api_base: http://host.docker.internal:18103/v1
      api_key: dummy-upstream-key
    model_info:
      id: policy-metered-v1
      input_cost_per_token: 0.000002
      output_cost_per_token: 0.000006

litellm_settings:
  turn_off_message_logging: true

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  store_model_in_db: false

The local upstream server (upstream.py) runs on Python’s standard ThreadingHTTPServer. It embeds a unique response marker (CONFIDENTIAL_HR_RESPONSE_MARKER_7319) so you can verify later that neither the prompt nor the answer landed in PostgreSQL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# upstream.py (core do_POST payload on :18103)
payload = {
    "id": "chatcmpl-upstream-policy-001",
    "object": "chat.completion",
    "created": int(time.time()),
    "model": model,
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "CONFIDENTIAL_HR_RESPONSE_MARKER_7319: Half-day leave requires manager approval in the HR portal at least one business day ahead.",
            },
            "finish_reason": "stop",
        }
    ],
    "usage": {
        "prompt_tokens": 120,
        "completion_tokens": 40,
        "total_tokens": 160,
    },
}

Comparing unpriced Ollama and custom-priced responses

Once the containers are healthy, generate a virtual key aliased as policy-qa-bot so key metadata appears in the spend logs. Then send the same prompt—tagged with a dummy sensitive marker (CONFIDENTIAL_HR_POLICY_MARKER_9482)—to both models.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 1. Generate a virtual key for policy-qa-bot
SERVICE_KEY=$(curl -sS -X POST http://127.0.0.1:14003/key/generate \
  -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"key_alias":"policy-qa-bot","models":["policy-local","policy-metered"]}' \
  | jq -r '.key')

# 2. Call unpriced local Ollama (-i prints response headers)
curl -i -sS -X POST http://127.0.0.1:14003/v1/chat/completions \
  -H "Authorization: Bearer ${SERVICE_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "policy-local",
    "messages": [{"role": "user", "content": "[CONFIDENTIAL_HR_POLICY_MARKER_9482] Summarize the manager approval rule for half-day leave in one sentence."}],
    "max_tokens": 48
  }'

# 3. Call the custom-priced endpoint
curl -i -sS -X POST http://127.0.0.1:14003/v1/chat/completions \
  -H "Authorization: Bearer ${SERVICE_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "policy-metered",
    "messages": [{"role": "user", "content": "[CONFIDENTIAL_HR_POLICY_MARKER_9482] Summarize the manager approval rule for half-day leave in one sentence."}]
  }'

Both calls returned HTTP 200, and waiting a few seconds for the async spend flush produced a clear side-by-side split:

Model aliasBackend targetResponse usage (in/out/total)x-litellm-response-cost headerDB spend (USD)
policy-localOllama qwen2.5:1.5b (live)66 / 42 / 108Header absent0
policy-meteredLocal upstream (fixed tokens)120 / 40 / 1600.000479999999999999960.00047999999999999996

For policy-metered, the expected cost is 120 × 0.000002 + 40 × 0.000006 = 0.00048 USD. The response header, /spend/logs/v2, and PostgreSQL all recorded 0.00047999999999999996—the exact IEEE 754 binary floating-point result (120 * 2e-6 = 0.00023999999999999998, 40 * 6e-6 = 0.00024). Billing jobs should round or normalize these floats with a decimal type before aggregating. Meanwhile, policy-local returned 108 total tokens in usage, yet omitted x-litellm-response-cost completely and logged spend = 0.

Matching request IDs and auditing PostgreSQL message columns

Querying a single request back from /spend/logs/v2 reveals two operational details that trip up log correlation pipelines.

First, /spend/logs/v2 requires UTC start_date and end_date query parameters even when you pass request_id. Calling the endpoint without them returns HTTP 400 Bad Request ("Start date and end date are required").

Second, the response JSON .id and the x-litellm-call-id response header are different values. For policy-metered, the JSON .id was chatcmpl-upstream-policy-001, while x-litellm-call-id was a proxy-generated UUID (16d3aa70-5a33-4a21-b33f-2ecd5c4e7bbb). The same mismatch appeared on policy-local (chatcmpl-2d35e763-5379-489c-ba05-b0dda836aff3 vs. 4fc29fad-f7d0-42b3-93cb-7d7e777d904b).

1
2
3
4
5
6
# Query /spend/logs/v2 with UTC date bounds using either ID
curl -sS "http://127.0.0.1:14003/spend/logs/v2?start_date=2026-12-01&end_date=2026-12-03&request_id=chatcmpl-upstream-policy-001" \
  -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" | jq '.total, .data[0].request_id, .data[0].litellm_call_id, .data[0].spend'

curl -sS "http://127.0.0.1:14003/spend/logs/v2?start_date=2026-12-01&end_date=2026-12-03&request_id=16d3aa70-5a33-4a21-b33f-2ecd5c4e7bbb" \
  -H "Authorization: Bearer ${LITELLM_MASTER_KEY}" | jq '.total, .data[0].request_id, .data[0].litellm_call_id, .data[0].spend'

On v1.112.0, both queries returned HTTP 200 with 1 matching row. Under the hood, though, PostgreSQL’s "LiteLLM_SpendLogs" table stores the response JSON .id in its request_id column, while x-litellm-call-id lives inside metadata->>'litellm_call_id' and the API’s litellm_call_id field. If you join directly against PostgreSQL or run mixed proxy versions, treat the response JSON .id as your primary join key.

To confirm that turn_off_message_logging: true prevents raw text from reaching disk—not just the API response—inspect "LiteLLM_SpendLogs" directly with psql:

1
2
3
4
5
6
7
docker compose exec -T postgres psql -U litellm -d litellm -x -c '
  SELECT request_id, model_group, prompt_tokens, completion_tokens, spend,
         messages::text AS messages_col, response::text AS response_col,
         metadata->>'\''user_api_key_alias'\'' AS key_alias
  FROM "LiteLLM_SpendLogs"
  ORDER BY "startTime" ASC;
'

The live psql output confirmed that both rows dropped the payload text while preserving accounting fields:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-[ RECORD 1 ]-----+----------------------------------------------
request_id        | chatcmpl-2d35e763-5379-489c-ba05-b0dda836aff3
model_group       | policy-local
prompt_tokens     | 66
completion_tokens | 42
spend             | 0
messages_col      | {}
response_col      | {}
key_alias         | policy-qa-bot
-[ RECORD 2 ]-----+----------------------------------------------
request_id        | chatcmpl-upstream-policy-001
model_group       | policy-metered
prompt_tokens     | 120
completion_tokens | 40
spend             | 0.00047999999999999996
messages_col      | {}
response_col      | {}
key_alias         | policy-qa-bot

Both messages and response stored empty JSON objects ({}). A LIKE scan across "LiteLLM_SpendLogs" for CONFIDENTIAL_HR_POLICY_MARKER_9482 and CONFIDENTIAL_HR_RESPONSE_MARKER_7319 returned 0 rows, while prompt_tokens, completion_tokens, spend, and key_alias (policy-qa-bot) remained intact.

Terminal output showing LiteLLM Proxy v1.112.0 custom pricing headers,spend/logs/v2 ID lookup, and empty PostgreSQL message columns Figure 1. Verification output on ghcr.io/berriai/litellm:v1.112.0 and postgres:17-alpine comparing live local Ollama (qwen2.5:1.5b) against a fixed-token local upstream server, /spend/logs/v2 ID lookup, and psql confirmation that messages_col and response_col remain {} with marker_hits = 0.

Production caveats and pre-deployment checklist

Watch out for per-token units, UTC date windows, and streaming or callback scope.

  1. Per-token USD, not per 1M tokens: input_cost_per_token and output_cost_per_token expect a single-token USD price. Entering 2.0 instead of 0.000002 for $2 / 1M tokens inflates spend by a million times and can trip budgets on the first request.
  2. UTC bounds and async DB flushes: /spend/logs/v2 evaluates start_date and end_date in UTC. Passing local dates around midnight can miss rows, and querying immediately after a call may race with the background database writer.
  3. Streaming and external callbacks: This test covered non-streaming calls and PostgreSQL "LiteLLM_SpendLogs". Streaming responses don’t know final token counts when headers go out, which changes x-litellm-response-cost behavior. If you also enable external callbacks such as Langfuse or Datadog, verify their payload redaction settings separately.

Run through these checks before rolling custom pricing and zero-message logging into production:

  • Confirm input_cost_per_token and output_cost_per_token use per-token USD and match a hand-calculated test call.
  • Normalize IEEE 754 float values (0.00047999999999999996) with a decimal type in downstream billing jobs.
  • Log both response JSON .id and x-litellm-call-id in your service, and always pass UTC start_date/end_date to /spend/logs/v2.
  • Send one test call containing a dummy marker after deployment and verify via psql that messages and response stay {}.

References

For customer and end-user spend tracking from v1.111, start with Customer Management. Its customer usage APIs report organization, team, and member totals. The enduser field and /customer/* examples below refer to legacy tracking.
Overview
When you make a request to the proxy, the proxy will return the following headers:
View Spend, Token Usage, Key, Team Name for Each Request to LiteLLM
This post is licensed under CC BY 4.0 by the author.