Skip to content

feat(agent): emit session_stats summary on stream completion - #553

Merged
edenreich merged 1 commit into
mainfrom
feat/agent-session-stats
May 29, 2026
Merged

edenreich merged 1 commit into
mainfrom
feat/agent-session-stats

Conversation

@edenreich

@edenreich edenreich commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #552.

When an infer agent session finishes, emit a single additive JSON line summarizing token usage and dollar cost, so headless consumers — notably inference-gateway/infer-action — can report real run cost without re-implementing the per-model pricing table (which would drift).

{"type":"session_stats","message":"Session complete","timestamp":"...","model":"deepseek/deepseek-v4-flash","prompt_tokens":21000,"completion_tokens":1260,"total_tokens":22260,"requests":7,"cost":{"input":0.0021,"output":0.0008,"total":0.0029,"currency":"USD"}}

How it works

  • Token source: session-local accumulators on AgentSession, summed from each turn's OpenAI-compatible response.Usage in processSyncResponse. Each /chat/completions call reports usage per-completion, so the session total is the sum across turns — consistent with how conversationRepo.AddTokenUsage / the /cost shortcut already aggregate.
  • Why dedicated fields (vs. summing the per-message TokenUsage): maybeRollover() resets s.conversation mid-run, so summing the in-memory conversation would drop pre-rollover turns and could fold in resumed prior-run usage. The accumulators stay scoped to this run and survive rollover.
  • Cost: computed via the shared PricingService.CalculateCost — no pricing-table duplication. Currency from pricing.currency (fallback USD). cost is always present (zeros when pricing is disabled) for a stable consumer schema.
  • Emission: defer s.emitSessionStats() in execute(), so it fires on normal completion, early error return, and panic unwind. Suppressed when no usage-bearing request occurred (requests == 0).
  • Gating: always emitted in agent mode, no flag — the new type is additive and existing stream consumers ignore unknown types.

Tests

  • TestEmitSessionStats* — full-line shape/values, suppression at zero requests, zero-cost when pricing disabled, currency fallback, nil-pricing safety.
  • TestProcessSyncResponseAccumulatesTokens — accumulator wiring incl. nil-usage and usage-bearing-empty-response (increment precedes the early return).
  • Adds a counterfeiter-generated FakePricingService (registered in Taskfile.yml mocks:generate).

task build / task test / task lint all green.

Cross-repo impact

Public stream-surface addition. Docs follow-up filed: inference-gateway/docs#85 (documents the session_stats line). No SDK/operator impact.

🤖 Generated with Claude Code

When an `infer agent` session finishes, emit a single additive JSON line
summarizing token usage and dollar cost so headless consumers (e.g.
inference-gateway/infer-action) can report run cost without re-implementing
the per-model pricing table:

  {"type":"session_stats","message":"Session complete",...,"model":...,
   "prompt_tokens":...,"completion_tokens":...,"total_tokens":...,
   "requests":...,"cost":{"input":...,"output":...,"total":...,"currency":"USD"}}

Token counts come from session-local accumulators on AgentSession, summed
from each turn's OpenAI-compatible response.Usage. Accumulating in dedicated
fields (rather than the per-message TokenUsage) keeps the totals rollover-safe,
since maybeRollover resets s.conversation mid-run. Cost is computed via the
shared PricingService so the pricing table is never duplicated. Emitted via a
defer in execute() so it fires on completion, early error, and panic unwind;
suppressed when no usage-bearing request occurred.

Always emitted in agent mode (no flag) — the new type is additive and existing
stream consumers ignore unknown types.

Adds a counterfeiter-generated FakePricingService for tests.

Closes #552
@edenreich
edenreich requested a review from a team as a code owner May 29, 2026 16:01
@edenreich
edenreich merged commit dff370f into main May 29, 2026
@edenreich
edenreich deleted the feat/agent-session-stats branch May 29, 2026 16:05
edenreich added a commit that referenced this pull request May 29, 2026
## Summary

Closes #552.

When an `infer agent` session finishes, emit a single additive JSON line
summarizing token usage and dollar cost, so headless consumers — notably
[`inference-gateway/infer-action`](https://github.com/inference-gateway/infer-action)
— can report real run cost without re-implementing the per-model pricing
table (which would drift).

```json
{"type":"session_stats","message":"Session complete","timestamp":"...","model":"deepseek/deepseek-v4-flash","prompt_tokens":21000,"completion_tokens":1260,"total_tokens":22260,"requests":7,"cost":{"input":0.0021,"output":0.0008,"total":0.0029,"currency":"USD"}}
```

## How it works

- **Token source:** session-local accumulators on `AgentSession`, summed
from each turn's OpenAI-compatible `response.Usage` in
`processSyncResponse`. Each `/chat/completions` call reports `usage`
per-completion, so the session total is the sum across turns —
consistent with how `conversationRepo.AddTokenUsage` / the `/cost`
shortcut already aggregate.
- **Why dedicated fields** (vs. summing the per-message `TokenUsage`):
`maybeRollover()` resets `s.conversation` mid-run, so summing the
in-memory conversation would drop pre-rollover turns and could fold in
resumed prior-run usage. The accumulators stay scoped to this run and
survive rollover.
- **Cost:** computed via the shared `PricingService.CalculateCost` — no
pricing-table duplication. Currency from `pricing.currency` (fallback
`USD`). `cost` is always present (zeros when pricing is disabled) for a
stable consumer schema.
- **Emission:** `defer s.emitSessionStats()` in `execute()`, so it fires
on normal completion, early error return, and panic unwind. Suppressed
when no usage-bearing request occurred (`requests == 0`).
- **Gating:** always emitted in agent mode, no flag — the new `type` is
additive and existing stream consumers ignore unknown types.

## Tests

- `TestEmitSessionStats*` — full-line shape/values, suppression at zero
requests, zero-cost when pricing disabled, currency fallback,
nil-pricing safety.
- `TestProcessSyncResponseAccumulatesTokens` — accumulator wiring incl.
nil-usage and usage-bearing-empty-response (increment precedes the early
return).
- Adds a counterfeiter-generated `FakePricingService` (registered in
`Taskfile.yml` `mocks:generate`).

`task build` / `task test` / `task lint` all green.

## Cross-repo impact

Public stream-surface addition. Docs follow-up filed:
**inference-gateway/docs#85** (documents the `session_stats` line). No
SDK/operator impact.
claude Bot added a commit to inference-gateway/docs that referenced this pull request May 29, 2026
Adds a new "Headless Agent Stream Output" subsection to the CLI
reference covering the JSONL stream contract for `infer agent` and
the final `session_stats` line emitted on session completion. Fields,
the nested `cost` object (including pricing-disabled zeros behavior),
and consumer guidance (additive, emitted once, ignore unknown types)
are all documented.

Closes #85.
Source: inference-gateway/cli#553, inference-gateway/cli#552.

Co-authored-by: Eden Reich <[email protected]>
edenreich added a commit to inference-gateway/docs that referenced this pull request May 29, 2026
Adds a new "Headless Agent Stream Output" subsection to the CLI
reference covering the JSONL stream contract for `infer agent` and
the final `session_stats` line emitted on session completion. Fields,
the nested `cost` object (including pricing-disabled zeros behavior),
and consumer guidance (additive, emitted once, ignore unknown types)
are all documented.

Closes #85.
Source: inference-gateway/cli#553, inference-gateway/cli#552.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Eden Reich <[email protected]>
github-actions Bot pushed a commit to inference-gateway/docs that referenced this pull request May 29, 2026
## [0.6.45](0.6.44...0.6.45) (2026-05-29)

### 📚 Documentation

* **cli:** document the agent stream session_stats summary line ([#86](#86)) ([f8b5aec](f8b5aec)), closes [inference-gateway/cli#553](inference-gateway/cli#553)
inference-gateway-releaser Bot pushed a commit that referenced this pull request May 29, 2026
## [0.115.0](v0.114.0...v0.115.0) (2026-05-29)

### 🚀 Features

* add 'infer conversations show <id>' subcommand ([#547](#547)) ([#554](#554)) ([41e06d5](41e06d5)), closes [#n](https://github.com/inference-gateway/cli/issues/n)
* **agent:** emit session_stats summary on stream completion ([#553](#553)) ([892203b](892203b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Emit a session token/cost summary on agent stream completion

1 participant