Files
sugarr/internal/client/llm.go
2026-04-22 18:23:19 +02:00

151 lines
4.0 KiB
Go

package client
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/fjurmanovic/sugarr/internal/model"
"github.com/fjurmanovic/sugarr/internal/utl/configs"
)
type LLMClient struct {
baseURL string
apiKey string
model string
http *http.Client
}
func NewLLMClient(cfg *configs.Config) *LLMClient {
return &LLMClient{
baseURL: cfg.LLMBaseURL,
apiKey: cfg.LLMAPIKey,
model: cfg.LLMModel,
http: &http.Client{},
}
}
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
}
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatResponse struct {
Choices []struct {
Message chatMessage `json:"message"`
} `json:"choices"`
}
func (c *LLMClient) Recommend(prompt string) ([]model.MovieSuggestion, error) {
payload := chatRequest{
Model: c.model,
Messages: []chatMessage{{Role: "user", Content: prompt}},
}
body, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, c.baseURL+"/chat/completions", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if c.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("llm request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("llm returned status %d", resp.StatusCode)
}
var chatResp chatResponse
if err := json.NewDecoder(resp.Body).Decode(&chatResp); err != nil {
return nil, fmt.Errorf("decoding llm response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, fmt.Errorf("llm returned no choices")
}
return parseMovieSuggestions(chatResp.Choices[0].Message.Content)
}
// parseMovieSuggestions extracts a JSON array from LLM output,
// handling markdown code fences and surrounding prose.
func parseMovieSuggestions(content string) ([]model.MovieSuggestion, error) {
content = strings.TrimSpace(content)
// Strip markdown fences
if idx := strings.Index(content, "```"); idx != -1 {
content = content[idx:]
content = strings.TrimPrefix(content, "```json")
content = strings.TrimPrefix(content, "```")
if end := strings.Index(content, "```"); end != -1 {
content = content[:end]
}
content = strings.TrimSpace(content)
}
// Find JSON array boundaries
start := strings.Index(content, "[")
end := strings.LastIndex(content, "]")
if start == -1 || end == -1 || end <= start {
return nil, fmt.Errorf("no JSON array found in llm response: %s", content)
}
var suggestions []model.MovieSuggestion
if err := json.Unmarshal([]byte(content[start:end+1]), &suggestions); err != nil {
return nil, fmt.Errorf("parsing llm json: %w", err)
}
return suggestions, nil
}
// BuildPrompt constructs the recommendation prompt sent to the LLM.
func BuildPrompt(favorites, watched, library []model.Movie, count int) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf(
"You are a movie recommendation engine. Based on the user's favorite and recently watched movies below, suggest exactly %d movies they would enjoy.\n\n"+
"IMPORTANT:\n"+
"- Do NOT suggest any movie from the \"Already In Library\" list.\n"+
"- Return ONLY a JSON array, no other text.\n"+
"- Each entry: {\"title\": \"Movie Title\", \"year\": 2024, \"reason\": \"brief reason\"}\n\n"+
"User's favorite movies:\n", count))
if len(favorites) == 0 {
sb.WriteString("(none)\n")
} else {
for _, m := range favorites {
sb.WriteString(fmt.Sprintf("- %s (%d)\n", m.Name, m.Year))
}
}
sb.WriteString("\nUser's recently watched movies:\n")
if len(watched) == 0 {
sb.WriteString("(none)\n")
} else {
for _, m := range watched {
sb.WriteString(fmt.Sprintf("- %s (%d)\n", m.Name, m.Year))
}
}
sb.WriteString("\nAlready in library (DO NOT suggest these):\n")
for _, m := range library {
sb.WriteString(fmt.Sprintf("- %s (%d)\n", m.Name, m.Year))
}
return sb.String()
}