Usage export as CSV: by period and by place, person, key and model, from the rollups

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5.5 committed 2026-10-04 16:49:04 +02:00
1 parent 15a7237a02
commit 57739d736a
11 files changed
+428 -2

No files matched your search

+52
View File
@@ -3,12 +3,15 @@ package cli
import (
"encoding/json"
"fmt"
"net/url"
"os"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"gitea.mynodes.xyz/ilker/llmgw/internal/control/adminapi"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
// newUsageCmd shows what each group of the tenancy tree spent.
@@ -17,6 +20,54 @@ import (
// anything could show what any of them had used: usage came back per key, per
// user and per model only. A quota whose consumption cannot be seen is one
// nobody reviews until the day it refuses somebody.
func newUsageExportCmd(client func() *ctlClient) *cobra.Command {
var from, to, period, by, output string
c := &cobra.Command{
Use: "export",
Short: "Usage as CSV, by period and by organization, team, project, user, key or model",
Long: "Totals from the hourly and daily sums, so it reaches back past the request\n" +
"records' retention. Periods are UTC. Cost is given in micro-units and in\n" +
"units; names, not ids, except for keys.",
Example: " llmgw ctl usage export --from 2026-09-01 --to 2026-10-01 --by project,model > september.csv\n" +
" llmgw ctl usage export --period month --by org --output 2026.csv",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
q := url.Values{"period": {period}, "by": {by}, "format": {"json"}}
if from != "" {
q.Set("from", from)
}
if to != "" {
q.Set("to", to)
}
var rows []store.ExportRow
if err := client().get(cmd.Context(), "/api/v1/usage/export?"+q.Encode(), &rows); err != nil {
return err
}
out := cmd.OutOrStdout()
if output != "" {
f, err := os.Create(output)
if err != nil {
return err
}
defer f.Close()
out = f
}
adminapi.WriteExportCSV(out, rows)
if output != "" {
cmd.PrintErrf("%d rows written to %s\n", len(rows), output)
}
return nil
},
}
f := c.Flags()
f.StringVar(&from, "from", "", "first day, 2026-09-01 (default: the first of this month)")
f.StringVar(&to, "to", "", "the day after the last, 2026-10-01 (default: now)")
f.StringVar(&period, "period", "day", "hour, day or month")
f.StringVar(&by, "by", "project,model", "any of org, team, project, user, key, model, comma-separated")
f.StringVarP(&output, "output", "o", "", "write to this file instead of standard output")
return c
}
func newUsageCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
var by string
var since time.Duration
@@ -70,5 +121,6 @@ func newUsageCmd(client func() *ctlClient, asJSON *bool) *cobra.Command {
}
c.Flags().StringVar(&by, "by", "team", "level to group by: org, team or project")
c.Flags().DurationVar(&since, "since", 24*time.Hour, "how far back to total")
c.AddCommand(newUsageExportCmd(client))
return c
}