Files
sam 4728c8c253 feat(usage): report model usage per org with identity and cost (#1855)
Model usage was recorded per call and never read, so an org could not see
what it spent. Add the read side:

- model_usage carries identity_id. Task calls take it from the task row,
  chat and curator calls from the calling principal carried in the usage
  record, so an outbox replay keeps its attribution. Existing task rows are
  backfilled from tasks.
- StatsService.UsageTotals sums the caller org's rows by UTC day, source,
  provider, model and identity. The org comes from the principal, with no
  org parameter, so cross-org reads do not exist.
- GET /api/usage prices tokens at the catalog's list rate, netting cache
  hits, and reports calls to unpriced models as tokens only. The published
  catalog view now carries each model's cost.
- A new org Usage page behind a read_usage grant: admin and owner only,
  with a 7, 30 or 90 day range, totals, the daily series, and model, source
  and identity breakdowns. The org shell keeps it on the caller's own org.
2026-11-11 02:15:29 +11:00

43 lines
1.7 KiB
Go

package postgres
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// RecordUsage appends one model call's usage record.
func (s *Store) RecordUsage(ctx context.Context, r usage.Record) error {
return postgresdb.New(s.pool).InsertModelUsage(ctx, postgresdb.InsertModelUsageParams{
TaskID: r.TaskID, OrgID: r.Org, Source: string(r.Source), Attempt: int64(r.Attempt),
Workflow: r.Workflow, Step: r.Step, Alias: r.Alias, Provider: r.Provider, Model: r.Model,
IdentityID: r.Identity,
InputTokens: r.InputTokens, OutputTokens: r.OutputTokens, CachedTokens: r.CachedTokens, At: r.At,
})
}
// UsageTotals sums the caller org's model usage over the last days days: one
// row per day, source, provider, model and identity. The org comes from the
// caller, never a parameter, so no call can read another org's usage.
func (s *Store) UsageTotals(ctx context.Context, days int) ([]usage.TotalRow, error) {
from, to := usage.ReportWindow(days, time.Now())
rows, err := postgresdb.New(s.pool).ListModelUsageTotals(ctx, postgresdb.ListModelUsageTotalsParams{
OrgID: string(org.OrgFromContext(ctx)), FromAt: from, ToAt: to,
})
if err != nil {
return nil, err
}
out := make([]usage.TotalRow, 0, len(rows))
for _, row := range rows {
out = append(out, usage.TotalRow{
Day: row.Day, Source: usage.Source(row.Source), Provider: row.Provider,
Model: row.Model, Identity: row.IdentityID, Calls: row.Calls,
InputTokens: row.InputTokens, OutputTokens: row.OutputTokens, CachedTokens: row.CachedTokens,
})
}
return out, nil
}