// Package ai sends prompts to the configured model provider: Anthropic, or // any server that speaks the OpenAI chat-completions API (Ollama, LM Studio, // llama.cpp, vLLM, OpenRouter, ...). package ai import ( "context" "encoding/json" "errors" "fmt" "os" "strings" "supermarket/internal/db" "supermarket/internal/secrets" ) // Providers. const ( ProviderAnthropic = "anthropic" ProviderOpenAI = "openai" // OpenAI-compatible server ) // DefaultAnthropicModel is the model used until the user picks another. const DefaultAnthropicModel = "claude-opus-5-5" // Tasks the app asks a model to do. Each can use its own model. const ( TaskProfile = "profile" // drafting the company profile, or an inventory entry, from a website TaskContent = "content" // writing posts TaskProspects = "prospects" // finding companies that show a buying signal (with web search) TaskOutreach = "outreach" // writing emails and LinkedIn messages to prospects ) // Tasks lists the tasks with a description, for the settings page. var Tasks = []struct{ ID, Label string }{ {TaskProfile, "Drafting the profile and filling in inventory entries"}, {TaskContent, "Writing posts"}, {TaskProspects, "Finding prospects for a buying signal (needs Claude, for web search)"}, {TaskOutreach, "Writing emails and LinkedIn messages to prospects"}, } // Config is the AI setting. type Config struct { Provider string `json:"provider"` Model string `json:"model"` BaseURL string `json:"base_url,omitempty"` // OpenAI-compatible servers only Effort string `json:"effort,omitempty"` // Anthropic: low, medium, high, xhigh, max // TaskModels overrides the model for a task, on the same provider. TaskModels map[string]string `json:"task_models,omitempty"` } const settingKey = "ai" // SharedFile is the file with the Anthropic key and model shared from // Hermes (written by lib.sh's sync_hermes_ai), or "" for none. Set at start. var SharedFile string // Shared is what Hermes shares. type Shared struct { Provider string `json:"provider"` Model string `json:"model"` APIKey string `json:"api_key"` } // LoadShared reads the shared key, or nil if there's none. It's read on // every use, so a key changed in Hermes applies at the next update.sh. func LoadShared() *Shared { if SharedFile == "" { return nil } raw, err := os.ReadFile(SharedFile) if err != nil { return nil } var sh Shared if json.Unmarshal(raw, &sh) != nil || sh.Provider != ProviderAnthropic || strings.TrimSpace(sh.APIKey) == "" { return nil } return &sh } // LoadConfig returns the saved AI config. Until one is saved: Anthropic, // with Hermes' model if it shares one. func LoadConfig(d *db.DB) (Config, error) { c := Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel, Effort: "medium"} found, err := d.GetJSON(settingKey, &c) if err != nil { return c, err } if !found { if sh := LoadShared(); sh != nil && sh.Model != "" { c.Model = sh.Model } } return c, nil } // AnthropicKey is the key to use: Supermarket's own, else Hermes'. It // reports whether it's Hermes'. func AnthropicKey(sec *secrets.Store) (key string, shared bool) { if key = sec.Get(secrets.AnthropicAPIKey); key != "" { return key, false } if sh := LoadShared(); sh != nil { return sh.APIKey, true } return "", false } // SaveConfig stores the AI config. func SaveConfig(d *db.DB, c Config) error { return d.PutJSON(settingKey, c) } // ModelFor is the model to use for task. func (c Config) ModelFor(task string) string { if m := strings.TrimSpace(c.TaskModels[task]); m != "" { return m } return c.Model } // Request is one prompt. type Request struct { Task string // picks the model; see Config.TaskModels System string Prompt string MaxTokens int // Schema, if set, asks for JSON matching this JSON Schema; the reply's // text is then that JSON. Schema map[string]any } // Client is a provider with its config. type Client interface { Generate(ctx context.Context, req Request) (string, error) } // ResearchRequest is a prompt answered with web search. type ResearchRequest struct { Task string System string Prompt string MaxTokens int MaxSearches int // web searches allowed (each is billed) BlockedDomains []string // never search these } // Source is a web page the model saw. type Source struct{ URL, Title string } // ResearchResult is the reply, the pages behind it, and how many searches // it took. type ResearchResult struct { Text string Sources []Source Searches int SearchErrors []string } // Researcher is a client that can search the web. Only Claude can. type Researcher interface { Research(ctx context.Context, req ResearchRequest) (*ResearchResult, error) } // ErrNoResearch means the AI provider can't search the web. var ErrNoResearch = errors.New("web research needs Claude (Anthropic) as the AI provider; other servers can't search the web") // DecodeJSON reads the outermost JSON object in a reply. func DecodeJSON(text string, out any) error { return decodeJSON(text, out) } // ErrNotConfigured means the provider can't be used yet (no key, no server). var ErrNotConfigured = errors.New("AI provider not configured") // New returns a client for the config, using keys from the secrets store. func New(c Config, sec *secrets.Store) (Client, error) { switch c.Provider { case ProviderAnthropic, "": key, _ := AnthropicKey(sec) if key == "" { return nil, fmt.Errorf("%w: add an Anthropic API key in Settings, or share Hermes' with `supermarket hermes`", ErrNotConfigured) } return newAnthropic(key, c), nil case ProviderOpenAI: if strings.TrimSpace(c.BaseURL) == "" { return nil, fmt.Errorf("%w: set the server's address in Settings", ErrNotConfigured) } return newOpenAI(c.BaseURL, sec.Get(secrets.OpenAIAPIKey), c), nil default: return nil, fmt.Errorf("unknown AI provider %q", c.Provider) } } // GenerateJSON runs req (which must have a Schema) and decodes the reply into // out. Servers that ignore the schema sometimes wrap the JSON in prose or a // code fence, so the outermost {...} is decoded. func GenerateJSON(ctx context.Context, c Client, req Request, out any) error { if req.Schema == nil { return errors.New("GenerateJSON needs a schema") } text, err := c.Generate(ctx, req) if err != nil { return err } return decodeJSON(text, out) } func decodeJSON(text string, out any) error { start := strings.Index(text, "{") end := strings.LastIndex(text, "}") if start < 0 || end < start { return fmt.Errorf("the model didn't return JSON: %.200q", text) } if err := json.Unmarshal([]byte(text[start:end+1]), out); err != nil { return fmt.Errorf("the model returned invalid JSON: %w", err) } return nil }