Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-24
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Design

## Context

See `proposal.md` for motivation.
The system streams LLM completions without capturing provider-reported token usage.
Reasoning tokens are not separated from completion tokens in the spend ledger.

## Goals / Non-Goals

**Goals:**
- Request and parse provider-reported usage across OpenAI, Ollama, and Claude streams.
- Attribute multi-node Ollama stream spend to the leased server node.
- Ensure stream spend is recorded in a `finally` block on normal completion, error, or early exit.
- Store reasoning tokens in the SQLite spend ledger schema and report reasoning share.

**Non-Goals:**
- Implement per-route token budgets or reasoning caps (addressed in #479).
- Add custom token counters when provider usage is available.

## Decisions

### Decision: Transmit stream usage through ContextVar objects
- **Choice**: Use ContextVar objects in `network.py` (`stream_usage`, `stream_server`) to transport stream metadata to spend recording.
- **Rationale**: Python generators yield chunks in caller loops where return values are lost and wrapper layers intervene. Context variables maintain context-local state cleanly.
- **Alternative Considered**: Returning metadata in a custom generator wrapper object.
- *Evidence for rejection*: Wrapping generators breaks compatibility with standard Python generator iteration and requires modifying every caller.

### Decision: Handle stream spend recording in a finally block
- **Choice**: Move `_record_stream_spend` execution into a `finally` block with a single-execution guard.
- **Rationale**: `GeneratorExit` and `KeyboardInterrupt` inherit from `BaseException` rather than `Exception`. A `finally` block guarantees spent tokens are recorded when consumers abandon streams.
- **Alternative Considered**: Catching `BaseException` directly.
- *Evidence for rejection*: Catching `BaseException` requires re-raising logic across multiple blocks and risks swallowing system exits.

### Decision: Schema evolution with ALTER TABLE in _ADDED_COLUMNS
- **Choice**: Add `reasoning_tokens` via `_ADDED_COLUMNS` in `src/devops_cli/ai/spend/ledger.py`.
- **Rationale**: Maintains consistency with existing migrations for `served_by`, `stage`, and `pricing_source`.
- **Alternative Considered**: Recreating the table or creating a separate reasoning table.
- *Evidence for rejection*: Recreating the table loses user spend records; a separate table adds join overhead to every query.

## Risks / Trade-offs

- [Risk]: Some providers do not report reasoning tokens directly.
→ Mitigation: Fall back to estimating tokens over `LLMResponse.thinking` via `count_tokens` when thinking text is present.
- [Risk]: Double-counting tokens in queries.
→ Mitigation: Keep reasoning tokens as a subset of completion tokens and avoid summing across token types.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Proposal

## Why

Issue #591: devops-cli does not record reasoning tokens or provider-reported stream usage.
Stream spend hand-counts joined chunks and inflates completion tokens without a reasoning split.
Multi-node Ollama streams record every configured host rather than the leased node.
Streams that close or abort early fail to record spent tokens because exceptions do not catch generator exits.

## What Changes

- devops-cli requests provider stream usage by sending `stream_options: {"include_usage": true}` on OpenAI-compatible streams.
- The stream parser extracts stream token usage from OpenAI chunks, Ollama final lines, and Claude delta events.
- Token counting remains only as a fallback when a stream provides no usage metrics.
- A multi-node Ollama stream records the specific leased node as its server in the spend ledger.
- A stream generator records spent tokens in a `finally` block when a consumer abandons or interrupts the stream.
- `LLMResponse` carries `reasoning_tokens` beside existing token fields.
- `ai/client/openai.py` reads `reasoning_tokens` from `usage.completion_tokens_details.reasoning_tokens`.
- Native Ollama and Claude estimate reasoning tokens from `LLMResponse.thinking` when present.
- The spend ledger adds a `reasoning_tokens` column to `ai_spend_records` and updates `track_request_spend`.
- Telemetry instruments emit `AI_TOKENS_TOTAL` with `type="reasoning"` as a subset of completion tokens.
- Telemetry spans record `gen_ai.usage.reasoning.output_tokens` from OpenTelemetry semantic conventions.
- `devops ai cost report` displays a reasoning-share column, including in the `--by backend` view.
- The change fits one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

- `ai-spend-pricing`: record stream usage from providers, track reasoning tokens in the spend ledger, and report reasoning share.

## Impact

- Code: `src/devops_cli/ai/client/models.py`, `src/devops_cli/ai/client/streaming.py`, `src/devops_cli/ai/client/network.py`, `src/devops_cli/ai/client/openai.py`, `src/devops_cli/ai/client/ollama.py`, `src/devops_cli/ai/client/claude.py`, `src/devops_cli/ai/client/unified.py`, `src/devops_cli/ai/spend/models.py`, `src/devops_cli/ai/spend/ledger.py`, and `src/devops_cli/commands/ai_cost.py`.
- Manifests: none.
- Documents: command references updated with `devops docs generate --sync-readme`.
- Tests: `tests/test_ai_streaming.py`, `tests/test_ai_spend_ledger.py`, `tests/test_ai_spend_cli.py`, and `tests/test_ai_client_telemetry.py`.

## Feasibility

- OpenAI-compatible stream protocol: `stream_options: {"include_usage": true}` delivers usage in final chunks before completion.
- Ollama streaming protocol: the terminal frame with `done: true` carries `prompt_eval_count` and `eval_count`.
- Anthropic streaming protocol: `message_start` events provide input tokens and `message_delta` events provide output tokens.
- OpenTelemetry semantic conventions: `GEN_AI_USAGE_REASONING_OUTPUT_TOKENS` is confirmed in `opentelemetry.semconv._incubating.attributes.gen_ai_attributes`.
- Leased node tracking: `acquire_ollama_slot` returns the single leased endpoint string.
- Generator exit handling: `finally` blocks execute reliably on `GeneratorExit` and `KeyboardInterrupt`.

## Existing Tool Considered

Provider stream options and OpenTelemetry semantic conventions provide standard interfaces.
SQLite table alteration handles schema evolution in place.
No custom token estimator or external character counter is built.
Internal manual token counting is replaced by provider-reported usage.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Spec Delta

## ADDED Requirements

### Requirement: A streamed request records provider-reported usage and leased server
devops-cli SHALL read token usage reported by streaming providers and SHALL record the leased server endpoint for multi-node streams.

#### Scenario: An OpenAI stream provides final usage
- **WHEN** an OpenAI-compatible stream returns a final usage chunk
- **THEN** prompt, completion, and reasoning tokens match the provider-reported usage

#### Scenario: An interrupted stream records spend in a finally block
- **WHEN** a client abandons a stream after receiving tokens
- **THEN** one ledger record captures the spent tokens

#### Scenario: A multi-node Ollama stream records the leased node
- **WHEN** an Ollama stream completes across multiple configured endpoints
- **THEN** the ledger server column contains the leased node address

### Requirement: Spend tracking records reasoning tokens and cost reports show reasoning share
The spend ledger SHALL record reasoning tokens for each AI request, and the cost report SHALL display reasoning share across backends and servers.

#### Scenario: A request with reasoning tokens is recorded
- **WHEN** an AI response contains reasoning tokens
- **THEN** the spend ledger stores reasoning tokens in its dedicated column and emits reasoning tokens to telemetry

#### 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Tasks

## 1. Provider-Reported Stream Usage and Lifecycle Handling

- [x] 1.1 Write failing tests for provider stream usage, multi-node Ollama leased server, and stream generator exit handling (`uv run devops ci test tests/test_ai_streaming.py`).
- [x] 1.2 Implement stream options in OpenAI requests, stream usage extraction in stream readers, leased server tracking in Ollama, and `finally` spend recording in `unified.py` (`uv run devops ci test tests/test_ai_streaming.py`).
- [x] 1.3 Update generated documentation (`uv run devops docs generate --sync-readme`).

## 2. Reasoning Tokens in LLMResponse, Ledger, and Telemetry

- [x] 2.1 Write failing tests for reasoning tokens in `LLMResponse`, SQLite spend ledger schema evolution, and OpenTelemetry reasoning attributes (`uv run devops ci test tests/test_ai_spend_ledger.py tests/test_ai_client_telemetry.py`).
- [x] 2.2 Implement `reasoning_tokens` on `LLMResponse`, parse reasoning in `openai.py`, add `reasoning_tokens` column to `ai_spend_records`, update `track_request_spend`, and emit telemetry (`uv run devops ci test tests/test_ai_spend_ledger.py tests/test_ai_client_telemetry.py`).
- [x] 2.3 Update generated documentation (`uv run devops docs generate --sync-readme`).

## 3. Reasoning Share in Cost Reporting

- [x] 3.1 Write failing tests for the reasoning-share column in `devops ai cost report` and `--by backend` (`uv run devops ci test tests/test_ai_spend_cli.py`).
- [x] 3.2 Implement reasoning share reporting across backend tables and models in `ai_cost.py` and `src/devops_cli/ai/spend/models.py` (`uv run devops ci test tests/test_ai_spend_cli.py`).
- [x] 3.3 Update generated documentation (`uv run devops docs generate --sync-readme`).

## Workflow follow-up

- Per-route token budgets and reasoning effort limits belong to follow-up issue #479.
- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
26 changes: 26 additions & 0 deletions openspec/specs/ai-spend-pricing/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,29 @@ Each spend-ledger row SHALL store its pricing source: `genai_prices:<provider>`,
#### Scenario: A ledger from before the column
- **WHEN** a ledger that has no `pricing_source` column opens
- **THEN** it keeps its rows and records the pricing source of each new row

### Requirement: A streamed request records provider-reported usage and leased server
devops-cli SHALL read token usage reported by streaming providers and SHALL record the leased server endpoint for multi-node streams.

#### Scenario: An OpenAI stream provides final usage
- **WHEN** an OpenAI-compatible stream returns a final usage chunk
- **THEN** prompt, completion, and reasoning tokens match the provider-reported usage

#### Scenario: An interrupted stream records spend in a finally block
- **WHEN** a client abandons a stream after receiving tokens
- **THEN** one ledger record captures the spent tokens

#### Scenario: A multi-node Ollama stream records the leased node
- **WHEN** an Ollama stream completes across multiple configured endpoints
- **THEN** the ledger server column contains the leased node address

### Requirement: Spend tracking records reasoning tokens and cost reports show reasoning share
The spend ledger SHALL record reasoning tokens for each AI request, and the cost report SHALL display reasoning share across backends and servers.

#### Scenario: A request with reasoning tokens is recorded
- **WHEN** an AI response contains reasoning tokens
- **THEN** the spend ledger stores reasoning tokens in its dedicated column and emits reasoning tokens to telemetry

#### 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
9 changes: 9 additions & 0 deletions src/devops_cli/ai/client/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ class LLMResponse(str):
prompt_tokens: int | None
completion_tokens: int | None
total_tokens: int | None
reasoning_tokens: int | None
cached: bool
eval_duration_ms: float | None
prompt_eval_duration_ms: float | None
Expand All @@ -146,6 +147,7 @@ def __new__(
served_by: str | None = None,
model: str | None = None,
finish_reason: FinishReason | None = None,
reasoning_tokens: int | None = None,
) -> LLMResponse:
obj = str.__new__(cls, content)
obj.processing_seconds = processing_seconds
Expand All @@ -155,6 +157,7 @@ def __new__(
obj.prompt_tokens = prompt_tokens
obj.completion_tokens = completion_tokens
obj.total_tokens = total_tokens
obj.reasoning_tokens = reasoning_tokens
obj.eval_duration_ms = eval_duration_ms
obj.prompt_eval_duration_ms = prompt_eval_duration_ms
obj.cached = cached
Expand Down Expand Up @@ -185,9 +188,15 @@ def to_model_response(self, model_name: str | None = None) -> Any:
parts.append(ThinkingPart(content=self.thinking.strip()))
if str(self):
parts.append(TextPart(content=str(self)))
details = (
{"reasoning_tokens": self.reasoning_tokens}
if self.reasoning_tokens is not None
else None
)
usage = RequestUsage(
input_tokens=self.prompt_tokens or 0,
output_tokens=self.completion_tokens or 0,
details=details,
)
return ModelResponse(
parts=parts,
Expand Down
17 changes: 17 additions & 0 deletions src/devops_cli/ai/client/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,23 @@ def extract_served_by(headers: Mapping[str, str] | None) -> str | None:
"stream_finish_reason", default=None
)


@dataclass(frozen=True)
class StreamUsage:
"""Token usage metrics reported directly by a streaming LLM provider."""

prompt_tokens: int | None = None
completion_tokens: int | None = None
total_tokens: int | None = None
reasoning_tokens: int | None = None


# Token usage metrics extracted from the final frames of a streamed reply.
stream_usage: ContextVar[StreamUsage | None] = ContextVar("stream_usage", default=None)

# The specific server node leased for a streamed request, e.g. for multi-node Ollama.
stream_server: ContextVar[str | None] = ContextVar("stream_server", default=None)

# A reply-token cap for the calls made inside `limit_completion_tokens`. It travels with the
# context, like the request priority, so one call site can bound a reply without every layer
# between it and the provider taking a parameter.
Expand Down
4 changes: 4 additions & 0 deletions src/devops_cli/ai/client/ollama.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
reply_schema,
request_limited_json,
request_priority_scope,
stream_server,
)
from devops_cli.ai.client.streaming import _ollama_stream_frame, _read_ndjson_stream
from devops_cli.config.constants import CONST_OLLAMA_DONE_REASONS
Expand Down Expand Up @@ -420,6 +421,9 @@ def _ollama_stream(
remaining_candidates, max_parallel=max_par, priority=priority
) as leased_url:
base = self._validate_base_url(leased_url, purpose="Ollama")
if leased_url:
host_str = urlparse(leased_url).netloc or leased_url
stream_server.set(host_str)
yield from self._try_single_ollama_stream(
base, leased_url, system, messages, enable_thinking
)
Expand Down
4 changes: 4 additions & 0 deletions src/devops_cli/ai/client/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def _build_compat_payload(
}
if stream:
payload["stream"] = True
payload["stream_options"] = {"include_usage": True}

limit = self._completion_limit()
if self._supports_reasoning():
Expand Down Expand Up @@ -177,6 +178,8 @@ def _parse_compat_response(

content, thinking_str = self._extract_inline_thinking(raw_content, thinking_str)
usage = raw_json.get("usage", {})
completion_details = usage.get("completion_tokens_details") or {}
reasoning_tokens = completion_details.get("reasoning_tokens")
b_info = f"{self.backend_type} ({self.backend_host})"
return LLMResponse(
content,
Expand All @@ -192,6 +195,7 @@ def _parse_compat_response(
finish_reason=provider_finish_reason(
CONST_OPENAI_FINISH_REASONS, first_choice.get("finish_reason")
),
reasoning_tokens=reasoning_tokens,
)

def _gateway_slot(self) -> AbstractContextManager[float]:
Expand Down
Loading