chore(cellar): replace Anthropic with Openrouter c087dcb2
suck it
Steve · 2026-10-24 16:50 8 file(s) · +147 −128
apps/cellar/README.md +1 −2
1 1
# cellar
2 2
3 -
Wine tasting log with optional Anthropic vision (label analysis) and per-wine
3 +
Wine tasting log with optional Openrouter vision (label analysis) and per-wine
4 4
RSS feed.
5 5
6 6
## Install
35 35
36 36
## Notes
37 37
38 -
- Anthropic `/v1/messages` called via stdlib `net/http` (no SDK).
39 38
- Image processing uses stdlib `image` decode + JPEG re-encode at quality 75.
40 39
  EXIF orientation is not respected; rotate before upload if needed.
41 40
- Multipart upload limit 10 MB.
apps/cellar/app.go +2 −2
19 19
	Sessions        *auth.Store
20 20
	AppPassword     string
21 21
	CookieSecure    bool
22 -
	AnthropicAPIKey string
22 +
	OpenrouterAPIKey string
23 23
	SiteURL         string
24 24
	SiteTitle       string
25 25
	SiteDescription string
92 92
type wineFormPageData struct {
93 93
	Wine            *Wine
94 94
	Error           string
95 -
	HasAnthropicKey bool
95 +
	HasOpenrouterKey bool
96 96
}
97 97
98 98
type wishlistPageData struct {
apps/cellar/claude.go (deleted) +0 −113
1 -
package main
2 -
3 -
import (
4 -
	"bytes"
5 -
	"context"
6 -
	"encoding/base64"
7 -
	"encoding/json"
8 -
	"fmt"
9 -
	"io"
10 -
	"net/http"
11 -
	"strings"
12 -
	"time"
13 -
)
14 -
15 -
type AnalyzeResult struct {
16 -
	Name       string `json:"name"`
17 -
	Origin     string `json:"origin"`
18 -
	Grape      string `json:"grape"`
19 -
	Background string `json:"background"`
20 -
}
21 -
22 -
type claudeImageSource struct {
23 -
	Type      string `json:"type"`
24 -
	MediaType string `json:"media_type"`
25 -
	Data      string `json:"data"`
26 -
}
27 -
28 -
type claudeContent struct {
29 -
	Type   string             `json:"type"`
30 -
	Source *claudeImageSource `json:"source,omitempty"`
31 -
	Text   string             `json:"text,omitempty"`
32 -
}
33 -
34 -
type claudeMessage struct {
35 -
	Role    string          `json:"role"`
36 -
	Content []claudeContent `json:"content"`
37 -
}
38 -
39 -
type claudeRequest struct {
40 -
	Model     string          `json:"model"`
41 -
	MaxTokens int             `json:"max_tokens"`
42 -
	Messages  []claudeMessage `json:"messages"`
43 -
}
44 -
45 -
type claudeResponse struct {
46 -
	Content []struct {
47 -
		Text string `json:"text"`
48 -
	} `json:"content"`
49 -
}
50 -
51 -
const claudeModel = "claude-sonnet-4-20250514"
52 -
const claudePrompt = `Look at this wine bottle label. Return a JSON object with exactly these fields: {"name": "the full wine name", "origin": "region and/or country", "grape": "grape variety or blend", "background": "brief background about the wine and the winery, including any notable history or interesting facts"}. If you cannot determine a field, use an empty string. Respond with ONLY the JSON, no other text.`
53 -
54 -
func analyzeWineImage(ctx context.Context, apiKey string, imageBytes []byte, mediaType string) (*AnalyzeResult, error) {
55 -
	encoded := base64.StdEncoding.EncodeToString(imageBytes)
56 -
	req := claudeRequest{
57 -
		Model:     claudeModel,
58 -
		MaxTokens: 1024,
59 -
		Messages: []claudeMessage{{
60 -
			Role: "user",
61 -
			Content: []claudeContent{
62 -
				{Type: "image", Source: &claudeImageSource{Type: "base64", MediaType: mediaType, Data: encoded}},
63 -
				{Type: "text", Text: claudePrompt},
64 -
			},
65 -
		}},
66 -
	}
67 -
	body, err := json.Marshal(req)
68 -
	if err != nil {
69 -
		return nil, err
70 -
	}
71 -
	client := &http.Client{Timeout: 60 * time.Second}
72 -
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.anthropic.com/v1/messages", bytes.NewReader(body))
73 -
	if err != nil {
74 -
		return nil, err
75 -
	}
76 -
	httpReq.Header.Set("x-api-key", apiKey)
77 -
	httpReq.Header.Set("anthropic-version", "2023-06-01")
78 -
	httpReq.Header.Set("content-type", "application/json")
79 -
	resp, err := client.Do(httpReq)
80 -
	if err != nil {
81 -
		return nil, fmt.Errorf("Request failed: %w", err)
82 -
	}
83 -
	defer resp.Body.Close()
84 -
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
85 -
		buf, _ := io.ReadAll(resp.Body)
86 -
		return nil, fmt.Errorf("API error %s: %s", resp.Status, string(buf))
87 -
	}
88 -
	var cr claudeResponse
89 -
	if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil {
90 -
		return nil, fmt.Errorf("Failed to parse response: %w", err)
91 -
	}
92 -
	var text string
93 -
	for _, c := range cr.Content {
94 -
		if c.Text != "" {
95 -
			text = c.Text
96 -
			break
97 -
		}
98 -
	}
99 -
	if text == "" {
100 -
		return nil, fmt.Errorf("No text in response")
101 -
	}
102 -
	text = strings.TrimSpace(text)
103 -
	if i := strings.Index(text, "{"); i >= 0 {
104 -
		if j := strings.LastIndex(text, "}"); j > i {
105 -
			text = text[i : j+1]
106 -
		}
107 -
	}
108 -
	var result AnalyzeResult
109 -
	if err := json.Unmarshal([]byte(text), &result); err != nil {
110 -
		return nil, fmt.Errorf("Failed to parse JSON: %w", err)
111 -
	}
112 -
	return &result, nil
113 -
}
apps/cellar/handlers_admin.go +6 −6
61 61
}
62 62
63 63
func (a *App) newWineGet(w http.ResponseWriter, r *http.Request) {
64 -
	a.renderPage(w, "wine_form.html", wineFormPageData{Error: r.URL.Query().Get("error"), HasAnthropicKey: a.AnthropicAPIKey != ""})
64 +
	a.renderPage(w, "wine_form.html", wineFormPageData{Error: r.URL.Query().Get("error"), HasOpenrouterKey: a.OpenrouterAPIKey != ""})
65 65
}
66 66
67 67
func (a *App) editWineGet(w http.ResponseWriter, r *http.Request) {
75 75
		http.Error(w, "Wine not found", http.StatusNotFound)
76 76
		return
77 77
	}
78 -
	a.renderPage(w, "wine_form.html", wineFormPageData{Wine: wine, Error: r.URL.Query().Get("error"), HasAnthropicKey: a.AnthropicAPIKey != ""})
78 +
	a.renderPage(w, "wine_form.html", wineFormPageData{Wine: wine, Error: r.URL.Query().Get("error"), HasOpenrouterKey: a.OpenrouterAPIKey != ""})
79 79
}
80 80
81 81
func (a *App) newWinePost(w http.ResponseWriter, r *http.Request) {
129 129
}
130 130
131 131
func (a *App) newWishlistGet(w http.ResponseWriter, r *http.Request) {
132 -
	a.renderPage(w, "wishlist_form.html", wineFormPageData{Error: r.URL.Query().Get("error"), HasAnthropicKey: a.AnthropicAPIKey != ""})
132 +
	a.renderPage(w, "wishlist_form.html", wineFormPageData{Error: r.URL.Query().Get("error"), HasOpenrouterKey: a.OpenrouterAPIKey != ""})
133 133
}
134 134
135 135
func (a *App) editWishlistGet(w http.ResponseWriter, r *http.Request) {
142 142
		http.Error(w, "Wine not found", http.StatusNotFound)
143 143
		return
144 144
	}
145 -
	a.renderPage(w, "wishlist_form.html", wineFormPageData{Wine: wine, Error: r.URL.Query().Get("error"), HasAnthropicKey: a.AnthropicAPIKey != ""})
145 +
	a.renderPage(w, "wishlist_form.html", wineFormPageData{Wine: wine, Error: r.URL.Query().Get("error"), HasOpenrouterKey: a.OpenrouterAPIKey != ""})
146 146
}
147 147
148 148
func (a *App) newWishlistPost(w http.ResponseWriter, r *http.Request) {
206 206
}
207 207
208 208
func (a *App) analyzeImage(w http.ResponseWriter, r *http.Request) {
209 -
	if a.AnthropicAPIKey == "" {
209 +
	if a.OpenrouterAPIKey == "" {
210 210
		web.WriteError(w, http.StatusBadRequest, "No API key configured")
211 211
		return
212 212
	}
230 230
	if header != nil && header.Header.Get("Content-Type") != "" {
231 231
		mediaType = header.Header.Get("Content-Type")
232 232
	}
233 -
	result, err := analyzeWineImage(r.Context(), a.AnthropicAPIKey, raw, mediaType)
233 +
	result, err := analyzeWineImage(r.Context(), a.OpenrouterAPIKey, raw, mediaType)
234 234
	if err != nil {
235 235
		a.Log.Error("Claude analysis failed", "err", err)
236 236
		web.WriteError(w, http.StatusInternalServerError, err.Error())
apps/cellar/main.go +1 −1
46 46
		Sessions:        sessions,
47 47
		AppPassword:     password,
48 48
		CookieSecure:    sessions.CookieSecure,
49 -
		AnthropicAPIKey: os.Getenv("ANTHROPIC_API_KEY"),
49 +
		OpenrouterAPIKey: os.Getenv("OPENROUTER_API_KEY"),
50 50
		SiteURL:         strings.TrimRight(config.Getenv("SITE_URL", "http://localhost:3000"), "/"),
51 51
		SiteTitle:       config.Getenv("SITE_TITLE", "Cellar"),
52 52
		SiteDescription: config.Getenv("SITE_DESCRIPTION", "Personal wine tasting log"),
apps/cellar/openrouter.go (added) +133 −0
1 +
package main
2 +
3 +
import (
4 +
	"bytes"
5 +
	"context"
6 +
	"encoding/base64"
7 +
	"encoding/json"
8 +
	"fmt"
9 +
	"io"
10 +
	"net/http"
11 +
	"strings"
12 +
	"time"
13 +
)
14 +
15 +
type AnalyzeResult struct {
16 +
	Name       string `json:"name"`
17 +
	Origin     string `json:"origin"`
18 +
	Grape      string `json:"grape"`
19 +
	Background string `json:"background"`
20 +
}
21 +
22 +
type openrouterImageURL struct {
23 +
	URL    string `json:"url"`
24 +
	Detail string `json:"detail,omitempty"`
25 +
}
26 +
27 +
type openrouterContent struct {
28 +
	Type     string              `json:"type"`
29 +
	Text     string              `json:"text,omitempty"`
30 +
	ImageURL *openrouterImageURL `json:"image_url,omitempty"`
31 +
}
32 +
33 +
type openrouterMessage struct {
34 +
	Role    string              `json:"role"`
35 +
	Content []openrouterContent `json:"content"`
36 +
}
37 +
38 +
type openrouterResponseFormat struct {
39 +
	Type string `json:"type"`
40 +
}
41 +
42 +
type openrouterRequest struct {
43 +
	Model          string                    `json:"model"`
44 +
	MaxTokens      int                       `json:"max_tokens"`
45 +
	Messages       []openrouterMessage       `json:"messages"`
46 +
	ResponseFormat *openrouterResponseFormat `json:"response_format,omitempty"`
47 +
}
48 +
49 +
type openrouterResponse struct {
50 +
	Choices []struct {
51 +
		Message struct {
52 +
			Content string `json:"content"`
53 +
		} `json:"message"`
54 +
		Error *struct {
55 +
			Code    int    `json:"code"`
56 +
			Message string `json:"message"`
57 +
		} `json:"error"`
58 +
	} `json:"choices"`
59 +
}
60 +
61 +
const (
62 +
	openrouterModel  = "z-ai/glm-5.3-flash"
63 +
	openrouterPrompt = `Look at this wine bottle label. Return a JSON object with exactly these fields: {"name": "the full wine name", "origin": "region and/or country", "grape": "grape variety or blend", "background": "brief background about the wine and the winery, including any notable history or interesting facts"}. If you cannot determine a field, use an empty string. Respond with ONLY the JSON, no other text.`
64 +
)
65 +
66 +
func normalizeMediaType(mediaType string) string {
67 +
	if !strings.HasPrefix(mediaType, "image/") {
68 +
		return "image/" + mediaType
69 +
	}
70 +
	return mediaType
71 +
}
72 +
73 +
func analyzeWineImage(ctx context.Context, apiKey string, imageBytes []byte, mediaType string) (*AnalyzeResult, error) {
74 +
	dataURI := fmt.Sprintf("data:%s;base64,%s",
75 +
		normalizeMediaType(mediaType), base64.StdEncoding.EncodeToString(imageBytes))
76 +
77 +
	req := openrouterRequest{
78 +
		Model:     openrouterModel,
79 +
		MaxTokens: 1024,
80 +
		Messages: []openrouterMessage{{
81 +
			Role: "user",
82 +
			Content: []openrouterContent{
83 +
				{Type: "text", Text: openrouterPrompt},
84 +
				{Type: "image_url", ImageURL: &openrouterImageURL{URL: dataURI}},
85 +
			},
86 +
		}},
87 +
		ResponseFormat: &openrouterResponseFormat{Type: "json_object"},
88 +
	}
89 +
	body, err := json.Marshal(req)
90 +
	if err != nil {
91 +
		return nil, err
92 +
	}
93 +
	client := &http.Client{Timeout: 60 * time.Second}
94 +
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
95 +
	if err != nil {
96 +
		return nil, err
97 +
	}
98 +
	httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
99 +
	httpReq.Header.Set("Content-Type", "application/json")
100 +
	resp, err := client.Do(httpReq)
101 +
	if err != nil {
102 +
		return nil, fmt.Errorf("Request failed: %w", err)
103 +
	}
104 +
	defer resp.Body.Close()
105 +
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
106 +
		buf, _ := io.ReadAll(resp.Body)
107 +
		return nil, fmt.Errorf("API error %s: %s", resp.Status, string(buf))
108 +
	}
109 +
	var cr openrouterResponse
110 +
	if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil {
111 +
		return nil, fmt.Errorf("Failed to parse response: %w", err)
112 +
	}
113 +
	if len(cr.Choices) == 0 {
114 +
		return nil, fmt.Errorf("No choices in response")
115 +
	}
116 +
	if cr.Choices[0].Error != nil {
117 +
		return nil, fmt.Errorf("API error %d: %s", cr.Choices[0].Error.Code, cr.Choices[0].Error.Message)
118 +
	}
119 +
	text := strings.TrimSpace(cr.Choices[0].Message.Content)
120 +
	if text == "" {
121 +
		return nil, fmt.Errorf("No text in response")
122 +
	}
123 +
	if i := strings.Index(text, "{"); i >= 0 {
124 +
		if j := strings.LastIndex(text, "}"); j > i {
125 +
			text = text[i : j+1]
126 +
		}
127 +
	}
128 +
	var result AnalyzeResult
129 +
	if err := json.Unmarshal([]byte(text), &result); err != nil {
130 +
		return nil, fmt.Errorf("Failed to parse JSON: %w", err)
131 +
	}
132 +
	return &result, nil
133 +
}
apps/cellar/templates/wine_form.html +2 −2
10 10
    <label for="image">image</label>
11 11
    <div class="image-upload-row">
12 12
      <input type="file" id="image" name="image" accept="image/*">
13 -
      {{if .HasAnthropicKey}}<button type="button" id="analyze-btn" onclick="analyzeImage()">analyze</button>{{end}}
13 +
      {{if .HasOpenrouterKey}}<button type="button" id="analyze-btn" onclick="analyzeImage()">analyze</button>{{end}}
14 14
    </div>
15 15
16 16
    <label for="name">name</label>
92 92
      });
93 93
    });
94 94
95 -
    {{if .HasAnthropicKey}}
95 +
    {{if .HasOpenrouterKey}}
96 96
    async function analyzeImage() {
97 97
      var fileInput = document.getElementById('image');
98 98
      if (!fileInput.files.length) return;
apps/cellar/templates/wishlist_form.html +2 −2
10 10
    <label for="image">image</label>
11 11
    <div class="image-upload-row">
12 12
      <input type="file" id="image" name="image" accept="image/*">
13 -
      {{if .HasAnthropicKey}}<button type="button" id="analyze-btn" onclick="analyzeImage()">analyze</button>{{end}}
13 +
      {{if .HasOpenrouterKey}}<button type="button" id="analyze-btn" onclick="analyzeImage()">analyze</button>{{end}}
14 14
    </div>
15 15
16 16
    <label for="name">name</label>
32 32
  </form>
33 33
34 34
  <script>
35 -
    {{if .HasAnthropicKey}}
35 +
    {{if .HasOpenrouterKey}}
36 36
    async function analyzeImage() {
37 37
      var fileInput = document.getElementById('image');
38 38
      if (!fileInput.files.length) return;