// 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" "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 from a website TaskContent = "content" // writing posts ) // Tasks lists the tasks with a description, for the settings page. var Tasks = []struct{ ID, Label string }{ {TaskProfile, "Drafting the company profile"}, {TaskContent, "Writing posts"}, } // 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" // LoadConfig returns the saved AI config, or Anthropic's defaults. func LoadConfig(d *db.DB) (Config, error) { c := Config{Provider: ProviderAnthropic, Model: DefaultAnthropicModel, Effort: "medium"} if _, err := d.GetJSON(settingKey, &c); err != nil { return c, err } return c, nil } // 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) } // 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 := sec.Get(secrets.AnthropicAPIKey) if key == "" { return nil, fmt.Errorf("%w: add an Anthropic API key in Settings", 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 }