Skip to content

feat(cli): reasoning-token share in the spend ledger and provider-reported stream usage #591

Description

@dan-petty

Context & Rationale

Nothing records reasoning tokens. Two FSMs isolate <think> blocks (ai/thinking_stream.py:51, ai/client/streaming.py:23), and each provider reasoning delta is rewrapped in its own <think>…</think> (streaming.py:252,279,299). LLMResponse carries thinking text beside prompt/completion/total tokens (ai/client/models.py:84-87); the ledger (ai/spend/ledger.py:33-35), both token exporters (ai/spend/prometheus.py:86-87, ledger.py:486-487) and the span token attributes (ai/client/unified.py:82-89) have no reasoning field. Stream spend is hand-counted: _record_stream_spend runs count_tokens over the joined chunks (unified.py:809,833). Both stream callers (ai/agents/agent.py:1110, commands/ai.py:942) keep the default sanitize=False (unified.py:738,766), so reasoning and its wrapper tags inflate completion tokens with no split. #479 infers "much of it on reasoning" with no record behind it. vibes patterns/streaming-reasoning-isolation-and-token-budgeting.md budgets what reasoning may cost but caps only a character buffer (max_thought_chars).

Scope & Deliverables

  • Context & Rationale*: Nothing records reasoning tokens. Two FSMs isolate <think> blocks (ai/thinking_stream.py:51, ai/client/streaming.py:23), and each provider reasoning delta is rewrapped in its own <think>…</think> (streaming.py:252,279,299). LLMResponse carries thinking text beside prompt/completion/total tokens (ai/client/models.py:84-87); the ledger (ai/spend/ledger.py:33-35), both token exporters (ai/spend/prometheus.py:86-87, ledger.py:486-487) and the span token attributes (ai/client/unified.py:82-89) have no reasoning field. Stream spend is hand-counted: _record_stream_spend runs count_tokens over the joined chunks (unified.py:809,833). Both stream callers (ai/agents/agent.py:1110, commands/ai.py:942) keep the default sanitize=False (unified.py:738,766), so reasoning and its wrapper tags inflate completion tokens with no split. feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479 infers "much of it on reasoning" with no record behind it. vibes patterns/streaming-reasoning-isolation-and-token-budgeting.md budgets what reasoning may cost but caps only a character buffer (max_thought_chars).
  • Deliverable*: First, probe the gateway once on the devops-review gpt-oss entries (k8s/llm/gateway/configmap.yaml:85,92; the Qwen entries do not reason), stream and non-stream, and record whether usage.completion_tokens_details.reasoning_tokens arrives and sits inside completion_tokens. PR 1, stream usage from the provider: request stream_options: {include_usage: true} on the OpenAI-compatible stream and read its final usage chunk, Ollama's final eval_count and Claude's message_delta usage; count_tokens remains only as a fallback flagged estimated. This fixes the overcount alone. PR 2, reasoning end to end: ai/client/openai.py, the gateway path reviews use, reads reasoning_tokens (it reads only three usage fields at openai.py:134-137) into LLMResponse; track_request_spend and a ledger column added in place like served_by (ledger.py:53) carry it; devops_cli_ai_tokens_total gains type="reasoning", which ai-spend.json:381 already splits; spans use GEN_AI_USAGE_REASONING_OUTPUT_TOKENS from opentelemetry-semantic-conventions, pinned directly; devops ai cost report adds a reasoning-share column, including --by backend. ai/direct.py also reads resp.usage.details, where pydantic-ai maps the same field. Claude and native Ollama report no count, so estimate over LLMResponse.thinking, labelled. No per-route budget: feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479 sets reasoning_effort and max_tokens per deployment, and any alert belongs there once share is measured.
  • Constraint*: Reasoning is a subset of completion, never added to it, or spend double-counts; no dashboard may sum across type. Ollama returns one eval_count beside a separate thinking string, so whether it includes thinking is checked before any estimate is split out. Estimated rows are labelled in the report and kept out of feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479's comparison. Per-stream character counters belong to the drafted Thinking-Stream Sanitizer: Initial State, Unopened-Tag Count and Thought Cap; a second set here is worse than none. Enforcing a budget by lowering max_tokens reproduces the findings-cut-short failure feat(ai): gpt-oss reasoning effort for group analysis is measured and set on its gateway deployments #479 describes.
  • Measured*: grep -rn reasoning_tokens src | wc -l gives 1, a function name in a knowledge-base markdown file. grep -rn 'include_usage\|stream_options' src finds nothing. .venv/bin/python probe/stream_count.py (synthetic one-word reasoning deltas wrapped as the clients wrap them, then content deltas) counts 321 tokens on the sanitize=False spend path against 59 of reasoning text and 20 of content.
  • Source*: vibes patterns/streaming-reasoning-isolation-and-token-budgeting.md, vibes examples/streaming-reasoning-sanitizer/sanitizer.py, vibes observations/devops-cli/13-streaming-reasoning-token-parsers-and-think-block-sanitization.md

Update 2026-10-08: refinement

Nothing reads reasoning_tokens or sends stream_options. Owner decision on #1001: pydantic-ai 2.54.0 already asks for stream usage and fills RequestUsage.details, so the OpenAI-compatible half moves onto #1001's seam; the ledger column, counter and report column can land first. Use the span key gen_ai.usage.reasoning.output_tokens (telemetry/semconv_genai.json:86). Stream callers: ai/agents/agent.py:1181, commands/ai.py:968.

Proposed design

Problem statement

The system does not record reasoning tokens, leading to overcounting of completion tokens and lack of visibility into reasoning usage. Two finite state machines isolate reasoning blocks, and each provider wraps reasoning deltas in their own tags. The ledger and token exporters have no reasoning field, and stream spend is hand-counted.

Acceptance criteria

  • Criterion 1: The system records reasoning tokens from providers that report them directly
    Verification: Run a probe on the gateway to check if usage.completion_tokens_details.reasoning_tokens arrives and sits inside completion_tokens for gpt-oss entries.
  • Criterion 2: Stream usage from the provider is correctly read and recorded
    Verification: Request stream_options: {include_usage: true} on OpenAI-compatible streams, read final usage chunks, and verify Ollama's eval_count and Claude's message_delta usage are captured.
  • Criterion 3: LLMResponse includes reasoning tokens when available
    Verification: Verify that ai/client/openai.py reads reasoning_tokens into LLMResponse and that track_request_spend carries it in the ledger.
  • Criterion 4: The spend ledger records reasoning tokens with a new column
    Verification: Check that ai/spend/ledger.py has a ledger column for reasoning tokens added in place like served_by and verify it's populated by track_request_spend.
  • Criterion 5: The cost report includes a reasoning-share column
    Verification: Run devops ai cost report and confirm that the output includes a reasoning-share column, including with the --by backend option.

Key questions

  • What providers return reasoning tokens directly?: OpenAI-compatible endpoints and Claude return reasoning tokens. Ollama and native Ollama report no count. [sources: k8s/llm/gateway/configmap.yaml]
  • How should the system handle estimation for providers that don't report reasoning tokens?: Estimate over LLMResponse.thinking and label estimated rows in the report. (proposed) [sources: docs/agent/tasks/task-591-reasoning-token-share-in-the-spend-ledger-and-provider-repor.md]
  • What is the expected behavior for stream usage from the provider?: Request stream_options: {include_usage: true} on OpenAI-compatible streams, read final usage chunks, and use Ollama's final eval_count and Claude's message_delta usage as sources. (proposed) [sources: docs/agent/tasks/task-591-reasoning-token-share-in-the-spend-ledger-and-provider-repor.md]

Fit

Needs splitting into 4 items:

  1. Probe the gateway to check for reasoning token availability
  2. Implement stream usage from providers
  3. Read reasoning tokens in LLMResponse and ledger integration
  4. Add reasoning-share column to cost report

Suspected block

None.

Dependencies

None.

Activity

  1. added this to the v0.2.23 milestone on Sep 25, 2026
  2. added
    type/feature
    scope/cli
    priority/p2-medium
    on Sep 25, 2026
  3. modified the milestones: v0.2.23, v0.2.24 on Sep 28, 2026
  4. removed this from the v0.2.23 milestone on Oct 1, 2026
  5. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    Moved from the shipped v0.2.23 to the backlog. It is still valid (checked 2026-10-01), and P2 items don't displace P1 work in the planned releases.

  6. added
    scope/ai
    and removed
    scope/cli
    on Oct 2, 2026
  7. modified the milestones: v0.2.39, v0.2.38 on Oct 17, 2026
  8. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Proposal needs splitting into 4 items at 3dd7fa6 (see proposed design in issue body).

  9. dan-petty commented on Oct 17, 2026

    @dan-petty
    OwnerAuthor

    Amendment from the gateway usage investigation of 2026-10-17, at main 3dd7fa6.

    #591 already covers provider-reported stream usage (OpenAI-compatible include_usage, Ollama's final eval_count, Claude's message_delta). Two more stream gaps belong with it:

    • For a multi-node Ollama stream, _record_stream_spend (src/devops_cli/ai/client/unified.py:893-927) takes server from self.backend_info, which joins every configured node (unified.py:276-287). _ollama_stream (src/devops_cli/ai/client/ollama.py:412-455) never exposes the node it leased, while the non-stream path does (ollama.py:363-370). Record the leased node as server.
    • A stream that the consumer abandons (GeneratorExit) or interrupts (KeyboardInterrupt) after yielding chunks records nothing, because the handler at unified.py:868 catches only Exception. Record the spent tokens in a finally.

    Tests first, with the existing stream fakes: a two-node Ollama stream records the leased node as server, and a stream closed after two chunks writes one ledger row.

    Neither ledger holds a stream row, and no stream traffic appears in 30 days, so priority stays P2.

  10. modified the milestones: v0.2.38, on Oct 20, 2026
  11. added a commit that references this issue on Oct 24, 2026
    a692877
  12. added a commit that references this issue on Oct 24, 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

    priority/p2-mediumscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions