// SPDX-License-Identifier: AGPL-3.0-or-later package ai import ( "context" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "net/url" "slices" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" ) // ---- Secrets ------------------------------------------------------------------- // sealer encrypts provider keys with AES-256-GCM. type sealer struct{ aead cipher.AEAD } func newSealer(secret string) *sealer { key := sha256.Sum256([]byte("docwell-ai-keys:" + secret)) block, _ := aes.NewCipher(key[:]) aead, _ := cipher.NewGCM(block) return &sealer{aead: aead} } func (s *sealer) seal(plain string) string { if plain == "" { return "" } nonce := make([]byte, s.aead.NonceSize()) _, _ = rand.Read(nonce) return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil)) } var errUnreadableKey = errors.New("the stored API key cannot be decrypted (the server secret changed); enter the key again") func (s *sealer) open(sealed string) (string, error) { if sealed == "" { return "", nil } raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:")) n := s.aead.NonceSize() if err != nil || len(raw) < n { return "", errUnreadableKey } plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil) if err != nil { return "", errUnreadableKey } return string(plain), nil } // ---- Profiles -------------------------------------------------------------------- type profileRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` Name string `json:"name"` Kind string `json:"kind"` BaseURL string `json:"base_url"` APIKey string `json:"api_key"` ChatModel string `json:"chat_model"` EmbedModel string `json:"embed_model"` // TranscribeModel is the speech-to-text model (OpenAI-compatible only). TranscribeModel string `json:"transcribe_model"` Effort string `json:"effort"` Enabled bool `json:"enabled"` Position float64 `json:"position"` Requests float64 `json:"requests"` InputTokens float64 `json:"input_tokens"` OutputTokens float64 `json:"output_tokens"` LastUsed string `json:"last_used"` LastError string `json:"last_error"` Created string `json:"created"` } // Profile is a provider configuration as admins see it, without the key. type Profile struct { ID string `json:"id"` // Workspace is "" for an instance default. Workspace string `json:"workspace"` Name string `json:"name"` Kind string `json:"kind"` BaseURL string `json:"baseUrl"` KeySet bool `json:"keySet"` ChatModel string `json:"chatModel"` EmbedModel string `json:"embedModel"` // TranscribeModel turns audio attachments into text ("" when unused). TranscribeModel string `json:"transcribeModel"` Effort string `json:"effort"` Enabled bool `json:"enabled"` Position int `json:"position"` Usage struct { Requests int `json:"requests"` InputTokens int `json:"inputTokens"` OutputTokens int `json:"outputTokens"` } `json:"usage"` LastUsed string `json:"lastUsed"` LastError string `json:"lastError"` Created string `json:"created"` } func (r profileRecord) view() Profile { p := Profile{ ID: r.ID, Workspace: r.Workspace, Name: r.Name, Kind: r.Kind, BaseURL: r.BaseURL, KeySet: r.APIKey != "", ChatModel: r.ChatModel, EmbedModel: r.EmbedModel, TranscribeModel: r.TranscribeModel, Effort: r.Effort, Enabled: r.Enabled, Position: int(r.Position), LastUsed: r.LastUsed, LastError: r.LastError, Created: r.Created, } p.Usage.Requests, p.Usage.InputTokens, p.Usage.OutputTokens = int(r.Requests), int(r.InputTokens), int(r.OutputTokens) return p } // ProfileInput creates or changes a profile. A nil APIKey keeps the stored // key; "" removes it. type ProfileInput struct { Name *string `json:"name"` Kind *string `json:"kind"` BaseURL *string `json:"baseUrl"` APIKey *string `json:"apiKey"` ChatModel *string `json:"chatModel"` EmbedModel *string `json:"embedModel"` // TranscribeModel is the speech-to-text model. TranscribeModel *string `json:"transcribeModel"` Effort *string `json:"effort"` Enabled *bool `json:"enabled"` } var efforts = []string{"", "low", "medium", "high", "xhigh", "max"} const maxProfiles = 20 func (in ProfileInput) body(s *sealer, create bool) (map[string]any, error) { fields := map[string]string{} body := map[string]any{} str := func(p *string, key, field string, max int) { if p == nil { return } v := strings.TrimSpace(*p) if len(v) > max { fields[field] = fmt.Sprintf("Use at most %d characters.", max) } body[key] = v } str(in.Name, "name", "name", 80) str(in.ChatModel, "chat_model", "chatModel", 200) str(in.EmbedModel, "embed_model", "embedModel", 200) str(in.TranscribeModel, "transcribe_model", "transcribeModel", 200) if in.Name != nil && strings.TrimSpace(*in.Name) == "" { fields["name"] = "Give the profile a name." } if create && in.Name == nil { fields["name"] = "Give the profile a name." } if in.Kind != nil { if !slices.Contains([]string{KindOpenAI, KindAnthropic, KindOllama}, *in.Kind) { fields["kind"] = "Choose OpenAI-compatible, Anthropic or Ollama." } body["kind"] = *in.Kind } else if create { fields["kind"] = "Choose OpenAI-compatible, Anthropic or Ollama." } if in.BaseURL != nil { v := strings.TrimRight(strings.TrimSpace(*in.BaseURL), "/") if v != "" { u, err := url.Parse(v) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { fields["baseUrl"] = "Enter an http:// or https:// address." } } body["base_url"] = v } if in.Effort != nil { if !slices.Contains(efforts, *in.Effort) { fields["effort"] = "Effort must be low, medium, high, xhigh or max." } body["effort"] = *in.Effort } if in.APIKey != nil { v := strings.TrimSpace(*in.APIKey) if len(v) > 1000 { fields["apiKey"] = "That key is too long." } body["api_key"] = s.seal(v) } if in.Enabled != nil { body["enabled"] = *in.Enabled } else if create { body["enabled"] = true } if len(fields) > 0 { return nil, apperr.InvalidFields(fields) } return body, nil } // canManage checks that c may change the profiles of wsID ("" = instance). func (s *Service) canManage(ctx context.Context, c access.Caller, wsID string) error { if wsID == "" { if !c.IsSuperadmin() { return apperr.Forbidden("only superadmins manage the instance's AI profiles") } return nil } role, err := s.dir.WorkspaceRole(ctx, c, wsID) if err != nil { return err } if !access.AtLeast(role, access.WorkspaceAdmin) { return apperr.Forbidden("workspace admin role required") } return nil } func profileFilter(wsID string) string { if wsID == "" { return "workspace = ''" } return fmt.Sprintf("workspace = '%s'", wsID) } func (s *Service) profileRecords(ctx context.Context, wsID string) ([]profileRecord, error) { res, err := pocketbase.List[profileRecord](ctx, s.pb, "ai_profiles", pocketbase.ListOptions{ PerPage: 200, Filter: profileFilter(wsID), Sort: "position,created", }) if err != nil { return nil, err } return res.Items, nil } // ListProfiles lists the profiles of a workspace ("" = the instance's). func (s *Service) ListProfiles(ctx context.Context, c access.Caller, wsID string) ([]Profile, error) { if err := s.canManage(ctx, c, wsID); err != nil { return nil, err } recs, err := s.profileRecords(ctx, wsID) if err != nil { return nil, err } out := make([]Profile, 0, len(recs)) for _, r := range recs { out = append(out, r.view()) } return out, nil } // CreateProfile adds a profile at the end of the list. func (s *Service) CreateProfile(ctx context.Context, c access.Caller, wsID string, in ProfileInput) (Profile, error) { if err := s.canManage(ctx, c, wsID); err != nil { return Profile{}, err } body, err := in.body(s.keys, true) if err != nil { return Profile{}, err } recs, err := s.profileRecords(ctx, wsID) if err != nil { return Profile{}, err } if len(recs) >= maxProfiles { return Profile{}, apperr.Invalid("This list has as many profiles as allowed.") } body["workspace"] = wsID body["position"] = len(recs) rec, err := pocketbase.Create[profileRecord](ctx, s.pb, "ai_profiles", body) if err != nil { return Profile{}, err } s.changed(wsID) return rec.view(), nil } func (s *Service) profileFor(ctx context.Context, c access.Caller, id string) (profileRecord, error) { if !validID(id) { return profileRecord{}, apperr.NotFound("profile not found") } rec, err := pocketbase.Get[profileRecord](ctx, s.pb, "ai_profiles", id) if err != nil { if pocketbase.IsNotFound(err) { return rec, apperr.NotFound("profile not found") } return rec, err } if err := s.canManage(ctx, c, rec.Workspace); err != nil { if rec.Workspace != "" { return rec, apperr.NotFound("profile not found") } return rec, err } return rec, nil } // UpdateProfile changes the fields that are set. func (s *Service) UpdateProfile(ctx context.Context, c access.Caller, id string, in ProfileInput) (Profile, error) { rec, err := s.profileFor(ctx, c, id) if err != nil { return Profile{}, err } body, err := in.body(s.keys, false) if err != nil { return Profile{}, err } body["last_error"] = "" rec, err = pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", id, body) if err != nil { return Profile{}, err } s.changed(rec.Workspace) return rec.view(), nil } // DeleteProfile removes a profile. func (s *Service) DeleteProfile(ctx context.Context, c access.Caller, id string) error { rec, err := s.profileFor(ctx, c, id) if err != nil { return err } if err := s.pb.Delete(ctx, "ai_profiles", id); err != nil { return err } s.changed(rec.Workspace) return nil } // OrderProfiles sets the order of a workspace's profiles (ids first to last). func (s *Service) OrderProfiles(ctx context.Context, c access.Caller, wsID string, ids []string) ([]Profile, error) { if err := s.canManage(ctx, c, wsID); err != nil { return nil, err } recs, err := s.profileRecords(ctx, wsID) if err != nil { return nil, err } pos := map[string]int{} for i, id := range ids { pos[id] = i } for _, r := range recs { p, ok := pos[r.ID] if !ok { p = len(ids) + int(r.Position) } if p != int(r.Position) { if _, err := pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", r.ID, map[string]any{"position": p}); err != nil { return nil, err } } } s.changed(wsID) return s.ListProfiles(ctx, c, wsID) } // TestResult is what a profile test found. type TestResult struct { OK bool `json:"ok"` Chat string `json:"chat"` Embeddings string `json:"embeddings"` Dimensions int `json:"dimensions"` LatencyMS int `json:"latencyMs"` Error string `json:"error"` } // TestProfile sends a tiny chat (and embedding) through a profile. func (s *Service) TestProfile(ctx context.Context, c access.Caller, id string) (TestResult, error) { rec, err := s.profileFor(ctx, c, id) if err != nil { return TestResult{}, err } ctx, cancel := context.WithTimeout(ctx, 60*time.Second) defer cancel() p, err := s.provider(rec) if err != nil { return TestResult{Error: err.Error()}, nil } res := TestResult{OK: true} start := time.Now() if rec.ChatModel != "" { var out strings.Builder usage, err := p.Chat(ctx, ChatRequest{ Model: rec.ChatModel, Effort: rec.Effort, MaxTokens: 64, Messages: []Message{{Role: "user", Content: "Reply with the single word: ready"}}, }, func(d string) { out.WriteString(d) }) s.record(rec.Workspace, rec, usage, err) if err != nil { res.OK, res.Error = false, err.Error() } else { res.Chat = strings.TrimSpace(out.String()) } } if rec.EmbedModel != "" && res.OK { vecs, usage, err := p.Embed(ctx, rec.EmbedModel, []string{"Docwell"}) s.record(rec.Workspace, rec, usage, err) if err != nil { res.OK, res.Error = false, err.Error() } else { res.Embeddings, res.Dimensions = "ok", len(vecs[0]) } } res.LatencyMS = int(time.Since(start).Milliseconds()) return res, nil } // provider builds the driver for a profile. Workspace profiles follow the // webhook address rules; instance profiles may reach any address (a // superadmin set them, and local models usually run next to the server). func (s *Service) provider(rec profileRecord) (Provider, error) { key, err := s.keys.open(rec.APIKey) if err != nil { return nil, err } client := s.guarded if rec.Workspace == "" { client = s.open } return NewProvider(rec.Kind, rec.BaseURL, key, client) } // record adds a call's usage to a profile's counters, and its error. // ws is the workspace the call was for ("" for none), whose monthly usage // grows by it too. func (s *Service) record(ws string, rec profileRecord, u Usage, callErr error) { s.usageMu.Lock() defer s.usageMu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() body := map[string]any{ "requests+": 1, "input_tokens+": u.InputTokens, "output_tokens+": u.OutputTokens, "last_used": time.Now().UTC().Format("2006-01-02 15:04:05.000Z"), "last_error": "", } if callErr != nil { msg := callErr.Error() if len(msg) > 480 { msg = msg[:480] } body["last_error"] = msg } if _, err := pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", rec.ID, body); err != nil { s.log.Warn("ai: recording usage", "profile", rec.ID, "err", err) } if ws != "" { if err := s.addUsage(ctx, ws, rec.Workspace == "", u); err != nil { s.log.Warn("ai: recording workspace usage", "workspace", ws, "err", err) } } } // ---- Workspace settings ----------------------------------------------------------- // Settings is a workspace's AI switches. type Settings struct { Enabled bool `json:"enabled"` UseInstanceProfiles bool `json:"useInstanceProfiles"` Index bool `json:"index"` Ignored []string `json:"ignored"` // MonthlyTokenLimit caps the tokens the workspace uses per month; 0 is no cap. MonthlyTokenLimit int `json:"monthlyTokenLimit"` // ReadScans has a document-reading model write out scanned PDFs attached // to pages, once each, so search finds their text (scans.go). ReadScans bool `json:"readScans"` } func defaultSettings() Settings { return Settings{Enabled: true, UseInstanceProfiles: true, Ignored: []string{}} } type workspaceAI struct { ID string `json:"id"` AISettings json.RawMessage `json:"ai_settings"` } func (s *Service) settings(ctx context.Context, wsID string) (Settings, error) { rec, err := pocketbase.Get[workspaceAI](ctx, s.pb, "workspaces", wsID) if err != nil { return Settings{}, err } out := defaultSettings() if len(rec.AISettings) > 0 && string(rec.AISettings) != "null" { _ = json.Unmarshal(rec.AISettings, &out) } if out.Ignored == nil { out.Ignored = []string{} } return out, nil } // GetSettings returns a workspace's AI settings (workspace admin). func (s *Service) GetSettings(ctx context.Context, c access.Caller, wsID string) (Settings, error) { if err := s.canManage(ctx, c, wsID); err != nil { return Settings{}, err } return s.settings(ctx, wsID) } // SaveSettings replaces a workspace's AI settings (workspace admin). func (s *Service) SaveSettings(ctx context.Context, c access.Caller, wsID string, in Settings) (Settings, error) { if err := s.canManage(ctx, c, wsID); err != nil { return Settings{}, err } if in.MonthlyTokenLimit < 0 { return Settings{}, apperr.InvalidFields(map[string]string{"monthlyTokenLimit": "Use 0 for no limit, or a positive number."}) } ignored := []string{} for _, id := range in.Ignored { if validID(id) && !slices.Contains(ignored, id) && len(ignored) < 2000 { ignored = append(ignored, id) } } in.Ignored = ignored if _, err := pocketbase.Update[workspaceAI](ctx, s.pb, "workspaces", wsID, map[string]any{"ai_settings": in}); err != nil { return Settings{}, err } s.recheck(wsID) return in, nil } // ---- Choosing profiles ---------------------------------------------------------- // chain is the profiles a workspace uses, in order: its own, then the // instance's unless turned off. Disabled profiles are left out. func (s *Service) chain(ctx context.Context, wsID string, st Settings) ([]profileRecord, error) { own, err := s.profileRecords(ctx, wsID) if err != nil { return nil, err } all := own if st.UseInstanceProfiles { inst, err := s.profileRecords(ctx, "") if err != nil { return nil, err } all = append(all, inst...) } return slices.DeleteFunc(all, func(r profileRecord) bool { return !r.Enabled }), nil } // embedProfile is the profile a workspace embeds with, or false. func embedProfile(chain []profileRecord) (profileRecord, bool) { for _, r := range chain { if r.EmbedModel != "" { return r, true } } return profileRecord{}, false } // errNoProfile is shown when a workspace has nothing to answer with. var errNoProfile = apperr.Invalid("AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.") // chat runs a chat on the first profile of the chain that answers. It moves // to the next one only while nothing was streamed yet. func (s *Service) chat(ctx context.Context, ws string, chain []profileRecord, req ChatRequest, onDelta func(string)) (profileRecord, error) { var lastErr error = errNoProfile for _, rec := range chain { if rec.ChatModel == "" { continue } p, err := s.provider(rec) if err != nil { lastErr = err continue } r := req r.Model, r.Effort = rec.ChatModel, rec.Effort if rec.Kind != KindAnthropic { r.Effort = "" } streamed := false usage, err := p.Chat(ctx, r, func(d string) { streamed = true; onDelta(d) }) s.record(ws, rec, usage, err) if err == nil || streamed || errors.Is(err, ErrRefused) || ctx.Err() != nil { return rec, err } s.log.Warn("ai: profile failed, trying the next", "profile", rec.ID, "err", err) lastErr = err } return profileRecord{}, lastErr } // changed wakes the indexer after a workspace's setup changed, so a new // embedding model or a switched-on index is picked up at once. func (s *Service) changed(string) { s.wake() }