Skip to documentation
Documentation navigation

Documentation navigation

Documentation / guides

Aggregate usage

Add independent usage observations with overflow and validation checks.

developer

content.Usage.Add combines token fields without mutating either operand and uses checked addition for every field. It performs no relationship validation: an operand whose reasoning exceeds its output is summed like any other, because refusing it would invalidate every later aggregate that folds it in.

Add

total, err := first.Add(second)
if err != nil {
	var overflow *content.UsageOverflowError
	if errors.As(err, &overflow) {
		return overflow
	}
	return err
}
contextTokens, err := total.ContextTokens()
if err != nil {
	return err
}
fmt.Println(contextTokens)

The fields added are input, output, cache read, cache creation, and reasoning. Derived context and total values are computed on demand rather than stored, which keeps aggregation unambiguous when cache fields are absent.

Overflow

An addition that exceeds content.TokenCount returns *content.UsageOverflowError naming the field and both operands. A failed aggregation returns the zero usage value and does not expose a wrapped partial sum.

Source and proof

Run go test ./usage and go test in the core module.

← back to documentation