Files
supermarket/internal/ai/ai.go
T
davidandClaude Opus 5.5 81a7d0596c Let Supermarket use Hermes' Anthropic key and model
Hermes is already set up with an Anthropic key, so AI needn't be set up
twice. `supermarket hermes` asks once, then it and update.sh copy just
the key and model to hermes-ai.json in the data folder (0600). The app
uses them when it has no key of its own, re-reading the file on each use.

Generation still calls the model directly rather than through Hermes'
API: post writing feeds it text from the web, which must not reach an
agent with a terminal, a browser and write access to the CRM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:58:06 -07:00

183 lines
5.2 KiB
Go

// 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 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"
// 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)
}
// 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
}