Files
archie/internal/infrastructure/modelcatalog/catalog.go
T
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

255 lines
7.0 KiB
Go

package modelcatalog
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"slices"
"strings"
"time"
"github.com/samcharles93/ai-sdk/catalog"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/fsutil"
)
type Options struct {
URL string
CachePath string
Getenv func(string) string
Configured map[string]config.Provider
HTTPClient *http.Client
}
type Snapshot struct {
Providers []Provider
}
type Provider struct {
ID string
Name string
Class string
APIKeyEnv string
BaseURL string
Models []Model
}
type Model struct {
ID string
Name string
ContextWindow int
MaxOutputTokens int
Reasoning bool
Attachment bool
Structured bool
InputModalities []string
Cost Cost
}
// Cost is a model's list price in USD per million tokens, as the catalog
// publishes it. A zero field means the catalog published no price.
type Cost struct {
Input float64 `json:"input,omitempty"`
Output float64 `json:"output,omitempty"`
CacheRead float64 `json:"cache_read,omitempty"`
CacheWrite float64 `json:"cache_write,omitempty"`
}
type catalogProvider struct {
ID string `json:"id"`
Name string `json:"name"`
NPM string `json:"npm"`
API string `json:"api"`
Env []string `json:"env"`
Models map[string]catalog.Model `json:"models"`
}
func Load(ctx context.Context, opts Options) (Snapshot, error) {
if opts.Getenv == nil {
opts.Getenv = os.Getenv
}
raw, fetchErr := fetch(ctx, opts)
if fetchErr == nil {
snapshot, parseErr := parse(raw, opts)
if parseErr == nil {
if opts.CachePath != "" {
// The downloaded catalog is already usable. A cache persistence
// failure must not prevent startup with valid in-memory data.
_ = writeCache(opts.CachePath, raw)
}
return snapshot, nil
}
fetchErr = parseErr
}
cached, cacheErr := os.ReadFile(opts.CachePath)
if cacheErr != nil {
return Snapshot{}, errors.Join(fetchErr, fmt.Errorf("read model catalog cache: %w", cacheErr))
}
snapshot, cacheErr := parse(cached, opts)
if cacheErr != nil {
return Snapshot{}, errors.Join(fetchErr, fmt.Errorf("parse cached model catalog: %w", cacheErr))
}
return snapshot, nil
}
func fetch(ctx context.Context, opts Options) ([]byte, error) {
url := strings.TrimSpace(opts.URL)
if url == "" {
url = catalog.DefaultURL
}
client := opts.HTTPClient
if client == nil {
client = &http.Client{Timeout: 30 * time.Second}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("build model catalog request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("fetch model catalog: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("fetch model catalog: status %d", resp.StatusCode)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read model catalog response: %w", err)
}
return raw, nil
}
func writeCache(path string, raw []byte) error {
return fsutil.WriteFileAtomic(path, raw, 0o600)
}
func parse(raw []byte, opts Options) (Snapshot, error) {
var catalog map[string]catalogProvider
if err := json.Unmarshal(raw, &catalog); err != nil {
return Snapshot{}, fmt.Errorf("parse model catalog: %w", err)
}
providers := make([]Provider, 0, len(catalog))
for key, source := range catalog {
if provider, ok := usableProvider(key, source, opts); ok {
providers = append(providers, provider)
}
}
slices.SortFunc(providers, func(a, b Provider) int {
return strings.Compare(a.Name, b.Name)
})
return Snapshot{Providers: providers}, nil
}
func usableProvider(key string, source catalogProvider, opts Options) (Provider, bool) {
id := strings.TrimSpace(source.ID)
if id == "" {
id = key
}
override, configured := opts.Configured[id]
envVar, ok := providerCredentialEnv(configured, override, source, opts.Getenv)
if !ok {
return Provider{}, false
}
models := toolModels(source.Models)
if len(models) == 0 {
return Provider{}, false
}
class, baseURL := providerRuntimeDefaults(source)
if configured {
if override.Class != "" {
class = override.Class
}
if override.BaseURL != "" {
baseURL = override.BaseURL
}
}
name := strings.TrimSpace(source.Name)
if name == "" {
name = displayName(id)
}
return Provider{
ID: id, Name: name, Class: class, APIKeyEnv: envVar,
BaseURL: baseURL, Models: models,
}, true
}
// providerCredentialEnv returns the environment variable whose value is the
// provider's key, and whether the provider may be served at all. A configured
// provider is disabled when its key failed to resolve and must never fall
// back to the catalog's ambient environment, which would send a turn with a
// key the operator did not choose: the catalog names the environment
// variables it would use, and a configured provider overrides that with the
// variable its own resolution exported.
func providerCredentialEnv(configured bool, override config.Provider, source catalogProvider, getenv func(string) string) (string, bool) {
if configured && override.Disabled {
return "", false
}
envVar := firstSetEnv(source.Env, getenv)
if configured && override.APIKeyEnv != "" {
envVar = override.APIKeyEnv
}
if (!configured && envVar == "") ||
(configured && override.APIKeyEnv != "" && getenv(override.APIKeyEnv) == "") {
return "", false
}
return envVar, true
}
func providerRuntimeDefaults(source catalogProvider) (class, baseURL string) {
class = "openai-compatible"
if mapped, ok := catalog.NPMClassMapping[source.NPM]; ok {
class = mapped
}
return class, source.API
}
func firstSetEnv(names []string, getenv func(string) string) string {
for _, name := range names {
if name = strings.TrimSpace(name); name != "" && getenv(name) != "" {
return name
}
}
return ""
}
func toolModels(source map[string]catalog.Model) []Model {
models := make([]Model, 0, len(source))
for key, model := range source {
if !model.ToolCall {
continue
}
id := strings.TrimSpace(model.ID)
if id == "" {
id = key
}
models = append(models, Model{
ID: id, Name: model.Name,
ContextWindow: model.ContextWindow(), MaxOutputTokens: model.MaxOutputTokens(),
Reasoning: model.Reasoning, Attachment: model.Attachment, Structured: model.Structured,
InputModalities: slices.Clone(model.Modalities.Input),
Cost: Cost{
Input: model.Cost.Input, Output: model.Cost.Output,
CacheRead: model.Cost.CacheRead, CacheWrite: model.Cost.CacheWrite,
},
})
}
slices.SortFunc(models, func(a, b Model) int { return strings.Compare(a.ID, b.ID) })
return models
}
func displayName(id string) string {
words := strings.FieldsFunc(id, func(r rune) bool { return r == '-' || r == '_' })
for i := range words {
if words[i] != "" {
words[i] = strings.ToUpper(words[i][:1]) + words[i][1:]
}
}
return strings.Join(words, " ")
}