package ai import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "log" "net/http" "os" "strings" "time" ) const openaiTimeout = 30 * time.Second type openaiRequest struct { Model string `json:"model"` Messages []openaiMessage `json:"messages"` Temperature float64 `json:"temperature"` } type openaiMessage struct { Role string `json:"role"` Content []openaiContent `json:"content"` } type openaiContent struct { Type string `json:"type"` Text string `json:"text,omitempty"` ImageURL *openaiImage `json:"image_url,omitempty"` } type openaiImage struct { URL string `json:"url"` } type openaiResponse struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` Error *struct { Message string `json:"message"` } `json:"error,omitempty"` } type openaiProvider struct{} func (p *openaiProvider) ExtractReceipt(imagePath string) (*ReceiptData, error) { imageData, err := readFile(imagePath) if err != nil { return &ReceiptData{}, fmt.Errorf("read file: %w", err) } mimeType := detectMimeType(imageData) if mimeType == "" { mimeType = "image/jpeg" } apiKey := os.Getenv("OPENAI_API_KEY") if apiKey == "" { return &ReceiptData{}, errors.New("OPENAI_API_KEY environment variable not set") } baseURL := os.Getenv("AI_BASE_URL") if baseURL == "" { baseURL = "https://api.openai.com/v1" } baseURL = strings.TrimRight(baseURL, "/") model := os.Getenv("AI_MODEL") if model == "" { model = "gpt-4o-mini" } b64Data := base64.StdEncoding.EncodeToString(imageData) dataURL := fmt.Sprintf("data:%s;base64,%s", mimeType, b64Data) payload := openaiRequest{ Model: model, Temperature: 0.1, Messages: []openaiMessage{{ Role: "user", Content: []openaiContent{ {Type: "text", Text: "Analyze this receipt image. Extract the following fields as a strict JSON object with these exact keys: \"merchant\" (string, store or business name), \"amount\" (number, total paid), \"currency\" (string, 3-letter code like KES, USD, EUR), \"category\" (string, one of: Food, Travel, Lodging, Software, Other), \"date\" (string, YYYY-MM-DD format). Return ONLY valid JSON. No markdown, no explanation, no code fences."}, {Type: "image_url", ImageURL: &openaiImage{URL: dataURL}}, }, }}, } body, _ := json.Marshal(payload) apiURL := baseURL + "/chat/completions" req, _ := http.NewRequest(http.MethodPost, apiURL, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+apiKey) client := &http.Client{Timeout: openaiTimeout} resp, err := client.Do(req) if err != nil { return &ReceiptData{}, fmt.Errorf("API request: %w", err) } defer resp.Body.Close() respBody, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusOK { return &ReceiptData{}, fmt.Errorf("API status %d: %s", resp.StatusCode, string(respBody)) } var apiResp openaiResponse json.Unmarshal(respBody, &apiResp) if apiResp.Error != nil { return &ReceiptData{}, fmt.Errorf("API error: %s", apiResp.Error.Message) } if len(apiResp.Choices) == 0 { return &ReceiptData{}, errors.New("no response choices") } contentStr := stripMarkdownFences(apiResp.Choices[0].Message.Content) var receipt ReceiptData if err := json.Unmarshal([]byte(contentStr), &receipt); err != nil { return &ReceiptData{}, fmt.Errorf("parse JSON: %w (content: %s)", err, contentStr) } log.Printf("ExtractReceipt [openai-%s]: merchant=%q amount=%.2f %s", model, receipt.Merchant, receipt.Amount, receipt.Currency) return &receipt, nil }