|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/mmcdole/gofeed" |
| 9 | + openai "github.com/sashabaranov/go-openai" |
| 10 | + "github.com/spf13/viper" |
| 11 | +) |
| 12 | + |
| 13 | +const defaultLimit = 20 // default number of articles per feed for analysis |
| 14 | +var model = openai.GPT4o |
| 15 | + |
| 16 | +func generateAnalysis(fp *gofeed.Parser, writer Writer) { |
| 17 | + if !viper.IsSet("analyst_feeds") || !viper.IsSet("analyst_prompt") { |
| 18 | + return |
| 19 | + } |
| 20 | + |
| 21 | + analystFeeds := viper.GetStringSlice("analyst_feeds") |
| 22 | + analystPrompt := viper.GetString("analyst_prompt") |
| 23 | + analystModel := viper.GetString("analyst_model") |
| 24 | + |
| 25 | + var articleTitles []string |
| 26 | + for _, feedURL := range analystFeeds { |
| 27 | + parsedFeed := parseFeed(fp, feedURL, defaultLimit) |
| 28 | + if parsedFeed == nil { |
| 29 | + continue |
| 30 | + } |
| 31 | + for _, item := range parsedFeed.Items { |
| 32 | + articleTitles = append(articleTitles, item.Title+": "+item.Description) // add also description for better context |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + if len(articleTitles) == 0 { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + prompt := fmt.Sprintf("%s\n\n%s", analystPrompt, strings.Join(articleTitles, "\n")) |
| 41 | + analysis := getLLMAnalysis(prompt, analystModel) |
| 42 | + |
| 43 | + if analysis != "" { |
| 44 | + writer.write("\n## Daily Analysis:\n") |
| 45 | + writer.write(analysis + "\n") |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func getLLMAnalysis(prompt string, analystModel string) string { |
| 50 | + clientConfig := openai.DefaultConfig(openaiApiKey) |
| 51 | + if openaiBaseURL != "" { |
| 52 | + clientConfig.BaseURL = openaiBaseURL |
| 53 | + } |
| 54 | + if analystModel != "" { |
| 55 | + model = analystModel |
| 56 | + } |
| 57 | + client := openai.NewClientWithConfig(clientConfig) |
| 58 | + |
| 59 | + resp, err := client.CreateChatCompletion( |
| 60 | + context.Background(), |
| 61 | + openai.ChatCompletionRequest{ |
| 62 | + Model: model, |
| 63 | + Messages: []openai.ChatCompletionMessage{ |
| 64 | + { |
| 65 | + Role: openai.ChatMessageRoleUser, |
| 66 | + Content: prompt, |
| 67 | + }, |
| 68 | + }, |
| 69 | + }, |
| 70 | + ) |
| 71 | + |
| 72 | + if err != nil { |
| 73 | + fmt.Printf("ChatCompletion error: %v\n", err) |
| 74 | + return "" |
| 75 | + } |
| 76 | + |
| 77 | + return resp.Choices[0].Message.Content |
| 78 | +} |
0 commit comments