// SPDX-License-Identifier: AGPL-3.0-or-later package ai import ( "context" "encoding/json" "fmt" "slices" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" ) // ---- Monthly token limits -------------------------------------------------------- // // Every call's tokens count against its workspace in ai_usage, per calendar // month (UTC). Two caps apply: a workspace admin's cap on everything the // workspace uses, and a superadmin's cap on what each workspace may use // through the server's own profiles (the server pays for those). When the // server's cap is reached, the workspace's own profiles still work. type usageRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` Month string `json:"month"` Requests float64 `json:"requests"` InputTokens float64 `json:"input_tokens"` OutputTokens float64 `json:"output_tokens"` InstanceTokens float64 `json:"instance_tokens"` } func (u usageRecord) tokens() int { return int(u.InputTokens + u.OutputTokens) } func thisMonth() string { return time.Now().UTC().Format("2006-01") } // usage is a workspace's usage this month (zero when it has none). func (s *Service) usage(ctx context.Context, ws string) (usageRecord, error) { res, err := pocketbase.List[usageRecord](ctx, s.pb, "ai_usage", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && month = '%s'", ws, thisMonth()), }) if err != nil || len(res.Items) == 0 { return usageRecord{Workspace: ws, Month: thisMonth()}, err } return res.Items[0], nil } // addUsage counts a call against its workspace. Callers hold usageMu. func (s *Service) addUsage(ctx context.Context, ws string, instance bool, u Usage) error { cur, err := s.usage(ctx, ws) if err != nil { return err } tokens := u.InputTokens + u.OutputTokens inc := map[string]any{"requests+": 1, "input_tokens+": u.InputTokens, "output_tokens+": u.OutputTokens} if instance { inc["instance_tokens+"] = tokens } if cur.ID != "" { _, err = pocketbase.Update[usageRecord](ctx, s.pb, "ai_usage", cur.ID, inc) return err } body := map[string]any{"workspace": ws, "month": cur.Month, "requests": 1, "input_tokens": u.InputTokens, "output_tokens": u.OutputTokens} if instance { body["instance_tokens"] = tokens } if _, err = pocketbase.Create[usageRecord](ctx, s.pb, "ai_usage", body); err != nil { // Another server made the month's record first: add to it. if cur, err2 := s.usage(ctx, ws); err2 == nil && cur.ID != "" { _, err = pocketbase.Update[usageRecord](ctx, s.pb, "ai_usage", cur.ID, inc) } } return err } // InstanceSettings are the superadmin's AI rules for every workspace. type InstanceSettings struct { // WorkspaceTokenLimit caps the tokens one workspace may use through the // server's profiles per month; 0 is no cap. WorkspaceTokenLimit int `json:"workspaceTokenLimit"` } type kvRecord struct { ID string `json:"id"` Key string `json:"key"` Value json.RawMessage `json:"value"` } const instanceKey = "ai" func (s *Service) instanceSettings(ctx context.Context) (InstanceSettings, string, error) { var out InstanceSettings res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("key = '%s'", instanceKey), }) if err != nil || len(res.Items) == 0 { return out, "", err } _ = json.Unmarshal(res.Items[0].Value, &out) return out, res.Items[0].ID, nil } // GetInstanceSettings returns the server's AI rules (superadmin). func (s *Service) GetInstanceSettings(ctx context.Context, c access.Caller) (InstanceSettings, error) { if !c.IsSuperadmin() { return InstanceSettings{}, apperr.Forbidden("superadmin role required") } out, _, err := s.instanceSettings(ctx) return out, err } // SaveInstanceSettings replaces the server's AI rules (superadmin). func (s *Service) SaveInstanceSettings(ctx context.Context, c access.Caller, in InstanceSettings) (InstanceSettings, error) { if !c.IsSuperadmin() { return InstanceSettings{}, apperr.Forbidden("superadmin role required") } if in.WorkspaceTokenLimit < 0 { return InstanceSettings{}, apperr.InvalidFields(map[string]string{"workspaceTokenLimit": "Use 0 for no limit, or a positive number."}) } _, id, err := s.instanceSettings(ctx) if err != nil { return InstanceSettings{}, err } body := map[string]any{"key": instanceKey, "value": in} if id != "" { _, err = pocketbase.Update[kvRecord](ctx, s.pb, "instance_settings", id, body) } else { _, err = pocketbase.Create[kvRecord](ctx, s.pb, "instance_settings", body) } return in, err } // UsageView is a workspace's usage this month, with its caps. type UsageView struct { Workspace string `json:"workspace"` Name string `json:"name,omitempty"` Month string `json:"month"` Requests int `json:"requests"` InputTokens int `json:"inputTokens"` OutputTokens int `json:"outputTokens"` InstanceTokens int `json:"instanceTokens"` // Limit is the workspace's own cap, InstanceLimit the server's cap on // instanceTokens; 0 means none. Limit int `json:"limit"` InstanceLimit int `json:"instanceLimit"` } func (u usageRecord) view(limit, instanceLimit int) UsageView { return UsageView{ Workspace: u.Workspace, Month: u.Month, Requests: int(u.Requests), InputTokens: int(u.InputTokens), OutputTokens: int(u.OutputTokens), InstanceTokens: int(u.InstanceTokens), Limit: limit, InstanceLimit: instanceLimit, } } // Usage reports a workspace's usage this month (workspace admin). func (s *Service) Usage(ctx context.Context, c access.Caller, wsID string) (UsageView, error) { if err := s.canManage(ctx, c, wsID); err != nil { return UsageView{}, err } st, err := s.settings(ctx, wsID) if err != nil { return UsageView{}, err } inst, _, err := s.instanceSettings(ctx) if err != nil { return UsageView{}, err } u, err := s.usage(ctx, wsID) return u.view(st.MonthlyTokenLimit, inst.WorkspaceTokenLimit), err } // AllUsage lists every workspace's usage this month, most first (superadmin). func (s *Service) AllUsage(ctx context.Context, c access.Caller) ([]UsageView, error) { if !c.IsSuperadmin() { return nil, apperr.Forbidden("superadmin role required") } inst, _, err := s.instanceSettings(ctx) if err != nil { return nil, err } res, err := pocketbase.List[struct { usageRecord Expand struct { Workspace *struct { Name string `json:"name"` AISettings json.RawMessage `json:"ai_settings"` } `json:"workspace"` } `json:"expand"` }](ctx, s.pb, "ai_usage", pocketbase.ListOptions{ PerPage: 500, Filter: fmt.Sprintf("month = '%s'", thisMonth()), Sort: "-output_tokens", Expand: "workspace", }) if err != nil { return nil, err } out := make([]UsageView, 0, len(res.Items)) for _, r := range res.Items { st := defaultSettings() name := "" if w := r.Expand.Workspace; w != nil { name = w.Name if len(w.AISettings) > 0 { _ = json.Unmarshal(w.AISettings, &st) } } v := r.view(st.MonthlyTokenLimit, inst.WorkspaceTokenLimit) v.Name = name out = append(out, v) } slices.SortStableFunc(out, func(a, b UsageView) int { return (b.InputTokens + b.OutputTokens) - (a.InputTokens + a.OutputTokens) }) return out, nil } var ( errWorkspaceLimit = apperr.Forbidden("This workspace has used its AI tokens for this month; a workspace admin can raise the limit.") errInstanceLimit = apperr.Forbidden("This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.") ) // limit applies the monthly caps to a workspace's chain: it fails when the // workspace's own cap is reached, and drops the server's profiles when the // server's cap is. func (s *Service) limit(ctx context.Context, ws string, st Settings, chain []profileRecord) ([]profileRecord, error) { u, err := s.usage(ctx, ws) if err != nil { return nil, err } if st.MonthlyTokenLimit > 0 && u.tokens() >= st.MonthlyTokenLimit { return nil, errWorkspaceLimit } inst, _, err := s.instanceSettings(ctx) if err != nil { return nil, err } if inst.WorkspaceTokenLimit > 0 && int(u.InstanceTokens) >= inst.WorkspaceTokenLimit { hadInstance := slices.ContainsFunc(chain, func(r profileRecord) bool { return r.Workspace == "" }) chain = slices.DeleteFunc(slices.Clone(chain), func(r profileRecord) bool { return r.Workspace == "" }) if hadInstance && len(chain) == 0 { return nil, errInstanceLimit } } return chain, nil }