Skip to content

fix(ai): price cached prompt tokens of build_agent runs #4483

Closed

Description

@dan-petty

Problem Description

The spend hook of build_agent records all the prompt tokens of an agent run at the full prompt rate. _spend_hook in src/devops_cli/ai/client/factory.py gives track_request_spend the input, output and reasoning tokens of response.usage, but it does not give cache_read_tokens. Since #4403 the pricing registry prices cached prompt tokens at the cached input rate, but this hook gives it 0.

Pull request #4454 added cache_read_tokens only to record_run_spend in src/devops_cli/roadmap/agent_run.py. Only the implement step calls record_run_spend (src/devops_cli/roadmap/implement/implement_step.py). The analysis step of refine (src/devops_cli/roadmap/refine/refine_investigation.py, build_agent(..., request_type="agent_run", stage="analysis")) and the agents of src/devops_cli/commands/ai.py record their spend through the factory hook.

The workstation ledger (.data/ai/spend.db, read-only query) has 2,657 DeepSeek agent_run rows with stage analysis (189.8 M prompt tokens) and 1 row with stage implement (2.1 M prompt tokens). Thus most DeepSeek agent runs still cost the full prompt rate for their cached tokens.

Reproduction Steps

  1. On main after fix(ai): price the DeepSeek group and its cached input #4454, build an agent with build_agent(FunctionModel(reply), request_type="agent_run", stage="analysis"). Let reply return a ModelResponse with RequestUsage(input_tokens=1_000_000, cache_read_tokens=900_000, output_tokens=100_000) and model_name="deepseek-v4.1-flash-1017".
  2. Patch devops_cli.ai.spend.ledger.track_request_spend to capture its keyword arguments, and run the agent.
  3. Price the captured tokens with get_pricing_registry().calculate_request_cost("deepseek-v4.1-flash-1017", 1_000_000, 100_000, provider="openrouter"), with and without cache_read_tokens=900_000.

Expected vs Actual Behavior

Expected: the hook gives cache_read_tokens=900000, and the ledger row costs 0.033477 USD.

Actual: the hook gives no cache_read_tokens, and the ledger row costs 0.10192 USD. The captured keyword arguments are completion_tokens, model, prompt_tokens, provider, reasoning_tokens, request_type, served_model, server and stage.

The Service runs task analysis on deepseek-v4.1-flash-1017 (0.0784 USD for each million prompt tokens, 0.002352 USD for each million cached prompt tokens). When 94% of the prompt tokens come from the cache, as from 2026-11-08 to 2026-11-11, the prompt part of the cost reads about 11 times high, and the hosted spend alert HostedSpendDailyHigh (sum over 24 h above 25 USD) can fire with no real cause. docs/TELEMETRY.md, src/devops_cli/telemetry/instruments.py and k8s/README.md say that a cached prompt token costs the cached input rate, with no limit.

Proposed fix

In _spend_hook of src/devops_cli/ai/client/factory.py, give cache_read_tokens=getattr(response.usage, "cache_read_tokens", 0) to track_request_spend. Add a test that sends a build_agent reply with cached tokens through the hook and expects 0.033477 USD for the numbers above. The library value comes from pydantic-ai RequestUsage.cache_read_tokens; no new code is needed to read it.

Issue #4442 covers the LLMClient chat path only. This issue covers the build_agent hook only.

Environment Diagnostics

Logs, Traces, or Terminal Output

hook kwargs: ['completion_tokens', 'model', 'prompt_tokens', 'provider', 'reasoning_tokens', 'request_type', 'served_model', 'server', 'stage']
cache_read_tokens given: <absent>
cost as recorded: RequestCost(cost_usd=0.10192, pricing_source='builtin:hosted_group_prices')
cost with cache:  RequestCost(cost_usd=0.033477, pricing_source='builtin:hosted_group_prices')

Found in the review of #4454.

Proposed design

Problem statement

The build_agent spend hook must send the cached prompt tokens of each reply to track_request_spend. The repository at this commit already sends cache_read_tokens, so the defect is fixed. The remaining work is a regression test that pins the cached input price and the 0.033477 USD result.

Acceptance criteria

Requirement: Cached prompt tokens reach the spend hook

The build_agent spend hook SHALL pass the cached prompt tokens of each model reply to track_request_spend.

Scenario: A cached agent reply

  • WHEN A build_agent reply reports 1,000,000 input tokens, 900,000 cached prompt tokens and 100,000 output tokens for deepseek-v4.1-flash-1017.
  • THEN The captured spend call has cache_read_tokens=900000, and the priced request costs 0.033477 USD.

Requirement: A regression test pins the cached input price

A test SHALL send a build_agent reply with cached prompt tokens through the spend hook and assert the cached input price.

Scenario: A regression test for the factory hook

  • WHEN The test patches track_request_spend and runs an agent_run analysis reply with 900,000 cached prompt tokens.
  • THEN The test asserts cache_read_tokens=900000 and a request cost of 0.033477 USD.

Existing Tool Considered

No alternatives check has run. The open, maintained pydantic-ai library covers the need. RequestUsage.cache_read_tokens gives the cached prompt tokens. The spend ledger already prices them at the cached input rate. It lacks nothing for this need. The change adds no new token reader.

Key questions

  • Does _spend_hook in build_agent already pass cache_read_tokens?: Yes. _spend_hook passes cache_read_tokens=getattr(response.usage, "cache_read_tokens", 0) to track_request_spend at this commit. [sources: src/devops_cli/ai/client/factory.py]
  • Which library field gives the cached prompt tokens of a model reply?: pydantic-ai gives RequestUsage.cache_read_tokens. record_run_spend already sums it for an implement run. [sources: src/devops_cli/roadmap/agent_run.py, src/devops_cli/ai/client/factory.py]
  • Should the change add a new cache-token field or read the existing pydantic-ai field?: Read the existing pydantic-ai field. A new field would duplicate the library and need pricing changes. (best practice) [sources: src/devops_cli/ai/client/factory.py, src/devops_cli/roadmap/agent_run.py]
    • Chosen: Use RequestUsage.cache_read_tokens. The field is in the reply usage and the pricing registry already prices it.
    • Rejected: Add a project cache-token field. The field duplicates pydantic-ai and adds code to keep.
  • Where should the regression test go?: Add the regression test to tests/ai/client/test_agent_factory.py. That module tests build_agent. (best practice) [sources: tests/ai/client/test_agent_factory.py, tests/ai/client/test_roadmap_agent_run.py]
    • Chosen: tests/ai/client/test_agent_factory.py. It tests the factory hook that the issue names.
    • Rejected: tests/ai/client/test_roadmap_agent_run.py. It tests the implement run record, not the factory hook.

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    source/agent
    type/bug
    scope/ai
    status/new
    value/medium
    effort/low
    on Nov 11, 2026
  2. dan-petty commented on Nov 11, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: intake puts every new item in the backlog. A person plans the milestones.

    • Type: type/bug. The fix prefix of the title gives the type.
    • Scope: scope/ai. The (ai) scope of the title gives the scope.
    • Priority: P2-Medium. Spend is reported up to 11 times too high for cached tokens, which can trigger false alerts, but no functional break occurs.
    • Value: Medium. Correct cost reporting prevents false spend alerts and gives accurate per-run cost data to operators.
    • Effort: Low. The fix adds one keyword argument to an existing call and one test case.
    • Related: fix(ai): price cached prompt tokens of chat calls #4442, which asks for a different change. Both fix cached prompt token pricing, but #4442 covers the LLMClient chat path and this issue covers the build_agent factory hook.
  3. added
    priority/p2-medium
    on Nov 11, 2026
  4. added
    status/ready
    and removed
    status/new
    on Nov 11, 2026
  5. devops-cli-service commented on Nov 11, 2026

    @devops-cli-service
    Contributor

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

  6. dan-petty commented on Nov 11, 2026

    @dan-petty
    OwnerAuthor

    Pull request #4484 (merge commit d9c8ee8) delivered the fix of this issue.

    • _spend_hook of build_agent in src/devops_cli/ai/client/factory.py (line 244 on main) gives cache_read_tokens=getattr(response.usage, "cache_read_tokens", 0) to track_request_spend.
    • The test test_a_request_on_the_deepseek_group_costs_its_cached_and_new_input_and_its_output in tests/ai/client/test_agent_factory.py sends a build_agent reply with 1,000,000 input tokens, 900,000 cached tokens and 100,000 output tokens on deepseek-v4.1-flash-1017. It expects 0.033477 USD in the ledger.

    Proof on main at 9b14af0: the test passes. When I remove the line at factory.py:244, the test fails with assert 0.10192 == 0.033477, which is the cost that this issue reports.

    Thus no work is left for this issue, and it closes as completed. Found in the review of #4484.

  7. removed
    status/ready
    on Nov 11, 2026
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/lowpriority/p2-mediumscope/aisource/agenttype/bugvalue/medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions