Repository navigation
feat(agent): emit session_stats summary on stream completion - #553
Merged
Merged
Conversation
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
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]>
3 tasks done
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))
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #552.
When an
infer agentsession finishes, emit a single additive JSON line summarizing token usage and dollar cost, so headless consumers — notablyinference-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
AgentSession, summed from each turn's OpenAI-compatibleresponse.UsageinprocessSyncResponse. Each/chat/completionscall reportsusageper-completion, so the session total is the sum across turns — consistent with howconversationRepo.AddTokenUsage/ the/costshortcut already aggregate.TokenUsage):maybeRollover()resetss.conversationmid-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.PricingService.CalculateCost— no pricing-table duplication. Currency frompricing.currency(fallbackUSD).costis always present (zeros when pricing is disabled) for a stable consumer schema.defer s.emitSessionStats()inexecute(), so it fires on normal completion, early error return, and panic unwind. Suppressed when no usage-bearing request occurred (requests == 0).typeis 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).FakePricingService(registered inTaskfile.ymlmocks:generate).task build/task test/task lintall green.Cross-repo impact
Public stream-surface addition. Docs follow-up filed: inference-gateway/docs#85 (documents the
session_statsline). No SDK/operator impact.🤖 Generated with Claude Code