Collect costs for dispatched model attempts

This commit is contained in:
2026-11-22 18:27:01 +00:00
parent cd0e1f5d39
commit 81a2a7591d
9 changed files with 129 additions and 6 deletions

View File

@@ -30,6 +30,7 @@ type Recorder struct {
generationDuration time.Duration
retryDelay time.Duration
usage UsageAccumulator
cost *CostAccumulator
}
// Selection contains resolved identities only. Unresolved fields stay empty.
@@ -53,6 +54,7 @@ type AttemptData struct {
StatusCode int
Usage domain.TokenUsage
UsagePresence *domain.TokenUsagePresence
CostUSD domain.ObservedCost
}
// DelayData describes one completed or interrupted retry wait.
@@ -99,6 +101,9 @@ func (r *Recorder) RunID() string { return r.runID }
// SetParentRunID records the immediate source identity before start delivery.
func (r *Recorder) SetParentRunID(id string) { r.parentRunID = id }
// SetCostAccumulator selects the invocation-owned cost state for terminal reporting.
func (r *Recorder) SetCostAccumulator(cost *CostAccumulator) { r.cost = cost }
// Start delivers the opening event with only identities already resolved.
func (r *Recorder) Start() {
event := r.event(domain.ExecutionStarted)
@@ -138,6 +143,7 @@ func (r *Recorder) Attempt(data AttemptData) {
event.StatusCode = data.StatusCode
if data.Dispatched {
event.Usage = observedUsage(data.Usage, data.UsagePresence)
event.CostUSD = data.CostUSD
}
r.deliver(event)
}
@@ -176,6 +182,9 @@ func (r *Recorder) Finish(data FinishData) {
event.Duration = 0
}
event.Usage = r.usage.Observed()
if r.cost != nil {
event.CostUSD = r.cost.Observed()
}
r.deliver(event)
}
@@ -222,7 +231,7 @@ type executionBoundary struct{ context.Context }
func (c executionBoundary) Value(key any) any {
switch key.(type) {
case contextKey, claimSinkKey:
case contextKey, claimSinkKey, costContextKey:
return nil
default:
return c.Context.Value(key)