apps/cellar/openrouter.go 4.0 K raw
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
}