-
Notifications
You must be signed in to change notification settings - Fork 23
/
summarize.go
65 lines (56 loc) · 1.39 KB
/
summarize.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"context"
"fmt"
"time"
readability "github.com/go-shiori/go-readability"
openai "github.com/sashabaranov/go-openai"
)
func getSummaryFromLink(url string) string {
article, err := readability.FromURL(url, 30*time.Second)
if err != nil {
fmt.Printf("Failed to parse %s, %v\n", url, err)
}
return summarize(article.TextContent)
}
func summarize(text string) string {
// Not sending everything to preserve Openai tokens in case the article is too long
maxCharactersToSummarize := 5000
if len(text) > maxCharactersToSummarize {
text = text[:maxCharactersToSummarize]
}
// Dont summarize if the article is too short
if len(text) < 200 {
return ""
}
clientConfig := openai.DefaultConfig(openaiApiKey)
if openaiBaseURL != "" {
clientConfig.BaseURL = openaiBaseURL
}
model := openai.GPT3Dot5Turbo
if openaiModel != "" {
model = openaiModel
}
client := openai.NewClientWithConfig(clientConfig)
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: model,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleAssistant,
Content: "Summarize the following text:",
},
{
Role: openai.ChatMessageRoleUser,
Content: text,
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return ""
}
return resp.Choices[0].Message.Content
}