-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
chat_histories.go
317 lines (268 loc) · 9.54 KB
/
chat_histories.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package chathistories
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"text/template"
"time"
"unicode/utf8"
"entgo.io/ent/dialect/sql"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/google/uuid"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
"go.uber.org/fx"
"github.com/nekomeowww/insights-bot/ent"
"github.com/nekomeowww/insights-bot/ent/chathistories"
"github.com/nekomeowww/insights-bot/internal/datastore"
"github.com/nekomeowww/insights-bot/pkg/bots/tgbot"
"github.com/nekomeowww/insights-bot/pkg/logger"
"github.com/nekomeowww/insights-bot/pkg/openai"
"github.com/nekomeowww/insights-bot/pkg/utils"
)
type NewModelParams struct {
fx.In
Logger *logger.Logger
Ent *datastore.Ent
OpenAI *openai.Client
}
type Model struct {
logger *logger.Logger
ent *datastore.Ent
openAI *openai.Client
}
func NewModel() func(NewModelParams) (*Model, error) {
return func(param NewModelParams) (*Model, error) {
return &Model{
logger: param.Logger,
ent: param.Ent,
openAI: param.OpenAI,
}, nil
}
}
func (m *Model) extractTextWithSummarization(message *tgbotapi.Message) (string, error) {
text := tgbot.ExtractTextFromMessage(message)
if text == "" {
return "", nil
}
if utf8.RuneCountInString(text) >= 200 {
resp, err := m.openAI.SummarizeWithOneChatHistory(context.Background(), text)
if err != nil {
return "", err
}
if len(resp.Choices) == 0 {
return "", nil
}
return resp.Choices[0].Message.Content, nil
}
return text, nil
}
func (m *Model) SaveOneTelegramChatHistory(message *tgbotapi.Message) error {
if message.Text == "" && message.Caption == "" {
m.logger.Warn("message text is empty")
return nil
}
telegramChatHistoryCreate := m.ent.ChatHistories.
Create().
SetChatID(message.Chat.ID).
SetMessageID(int64(message.MessageID)).
SetUserID(message.From.ID).
SetUsername(message.From.UserName).
SetFullName(tgbot.FullNameFromFirstAndLastName(message.From.FirstName, message.From.LastName)).
SetChattedAt(time.Unix(int64(message.Date), 0).UnixMilli())
text, err := m.extractTextWithSummarization(message)
if err != nil {
return err
}
if text == "" {
m.logger.Warn("message text is empty")
return nil
}
if message.ForwardFrom != nil {
telegramChatHistoryCreate.SetText(fmt.Sprintf("[forwarded from %s]: %s", tgbot.FullNameFromFirstAndLastName(message.ForwardFrom.FirstName, message.ForwardFrom.LastName), text))
} else if message.ForwardFromChat != nil {
telegramChatHistoryCreate.SetText(fmt.Sprintf("[forwarded from %s]: %s", message.ForwardFromChat.Title, text))
} else {
telegramChatHistoryCreate.SetText(text)
}
if message.ReplyToMessage != nil {
repliedToText, err := m.extractTextWithSummarization(message.ReplyToMessage)
if err != nil {
return err
}
if repliedToText != "" {
telegramChatHistoryCreate.SetRepliedToMessageID(int64(message.ReplyToMessage.MessageID))
telegramChatHistoryCreate.SetRepliedToUserID(message.ReplyToMessage.From.ID)
telegramChatHistoryCreate.SetRepliedToFullName(tgbot.FullNameFromFirstAndLastName(message.ReplyToMessage.From.FirstName, message.ReplyToMessage.From.LastName))
telegramChatHistoryCreate.SetRepliedToUsername(message.ReplyToMessage.From.UserName)
telegramChatHistoryCreate.SetRepliedToText(repliedToText)
}
}
telegramChatHistory, err := telegramChatHistoryCreate.Save(context.TODO())
if err != nil {
return err
}
m.logger.WithFields(logrus.Fields{
"id": telegramChatHistory.ID,
"chat_id": telegramChatHistory.ChatID,
"message_id": telegramChatHistory.MessageID,
"text": strings.ReplaceAll(telegramChatHistory.Text, "\n", " "),
}).Debug("saved one telegram chat history")
return nil
}
func (m *Model) FindLastOneHourChatHistories(chatID int64) ([]*ent.ChatHistories, error) {
return m.FindChatHistoriesByTimeBefore(chatID, time.Hour)
}
func (m *Model) FindLastSixHourChatHistories(chatID int64) ([]*ent.ChatHistories, error) {
return m.FindChatHistoriesByTimeBefore(chatID, 6*time.Hour)
}
func (m *Model) FindChatHistoriesByTimeBefore(chatID int64, before time.Duration) ([]*ent.ChatHistories, error) {
m.logger.Infof("querying chat histories for %d", chatID)
telegramChatHistories, err := m.ent.ChatHistories.
Query().
Where(
chathistories.ChatID(chatID),
chathistories.ChattedAtGT(time.Now().Add(-before).UnixMilli()),
).
Order(
chathistories.ByMessageID(sql.OrderDesc()),
).
All(context.TODO())
if err != nil {
return make([]*ent.ChatHistories, 0), err
}
return telegramChatHistories, nil
}
func formatFullNameAndUsername(fullName, username string) string {
if utf8.RuneCountInString(fullName) >= 10 && username != "" {
return username
}
return strings.ReplaceAll(fullName, "#", "")
}
func formatChatHistoryTextContent(text string) string {
return fmt.Sprintf(`"""%s"""`, text)
}
type RecapOutputTemplateInputs struct {
ChatID string
Recaps []*openai.ChatHistorySummarizationOutputs
}
func formatChatID(chatID int64) string {
chatIDStr := strconv.FormatInt(chatID, 10)
if strings.HasPrefix(chatIDStr, "-100") {
return strings.TrimPrefix(chatIDStr, "-100")
}
return chatIDStr
}
var RecapOutputTemplate = lo.Must(template.
New(uuid.New().String()).
Funcs(template.FuncMap{
"join": strings.Join,
"sub": func(a, b int) int { return a - b },
"add": func(a, b int) int { return a + b },
"escape": tgbot.EscapeHTMLSymbols,
}).
Parse(`{{ $chatID := .ChatID }}{{ $recapLen := len .Recaps }}{{ range $i, $r := .Recaps }}{{ if $r.SinceID }}## <a href="https://t.me/c/{{ $chatID }}/{{ $r.SinceID }}">{{ escape $r.TopicName }}</a>{{ else }}## {{ escape $r.TopicName }}{{ end }}
参与人:{{ join $r.ParticipantsNamesWithoutUsername "," }}
讨论:{{ range $di, $d := $r.Discussion }}
- {{ escape $d.Point }}{{ if len $d.CriticalIDs }} {{ range $cIndex, $c := $d.CriticalIDs }}<a href="https://t.me/c/{{ $chatID }}/{{ $c }}">[{{ add $cIndex 1 }}]</a>{{ if not (eq $cIndex (sub (len $d.CriticalIDs) 1)) }} {{ end }}{{ end }}{{ end }}{{ end }}{{ if $r.Conclusion }}
结论:{{ escape $r.Conclusion }}{{ end }}{{ if eq $i (sub $recapLen 1) }}{{ else }}
{{ end }}{{ end }}`))
func (m *Model) summarizeChatHistoriesSlice(s string) ([]*openai.ChatHistorySummarizationOutputs, error) {
m.logger.Infof("✍️ summarizing last one hour chat histories:\n%s", s)
resp, err := m.openAI.SummarizeWithChatHistories(context.Background(), s)
if err != nil {
return nil, err
}
if len(resp.Choices) == 0 {
return nil, nil
}
m.logger.WithFields(logrus.Fields{
"prompt_token_usage": resp.Usage.PromptTokens,
"completion_token_usage": resp.Usage.CompletionTokens,
"total_token_usage": resp.Usage.TotalTokens,
}).Info("✅ summarized last one hour chat histories")
if resp.Choices[0].Message.Content == "" {
return nil, nil
}
var outputs []*openai.ChatHistorySummarizationOutputs
err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &outputs)
if err != nil {
m.logger.Errorf("failed to unmarshal chat history summarization output: %s", resp.Choices[0].Message.Content)
return nil, err
}
m.logger.Infof("✅ unmarshaled chat history summarization output: %s", utils.SprintJSON(outputs))
return outputs, nil
}
func (m *Model) SummarizeChatHistories(chatID int64, histories []*ent.ChatHistories) (string, error) {
historiesLLMFriendly := make([]string, 0, len(histories))
for _, message := range histories {
if message.RepliedToMessageID == 0 {
historiesLLMFriendly = append(historiesLLMFriendly, fmt.Sprintf(
"msgId:%d: %s sent: %s",
message.MessageID,
formatFullNameAndUsername(message.FullName, message.Username),
formatChatHistoryTextContent(message.Text),
))
} else {
repliedToPartialContextMessage := fmt.Sprintf(
"%s sent msgId:%d",
formatFullNameAndUsername(message.RepliedToFullName, message.RepliedToUsername),
message.RepliedToMessageID,
)
historiesLLMFriendly = append(historiesLLMFriendly, fmt.Sprintf(
"msgId:%d: %s replying to [%s]: %s",
message.MessageID,
formatFullNameAndUsername(message.FullName, message.Username),
repliedToPartialContextMessage,
formatChatHistoryTextContent(message.Text),
))
}
}
chatHistories := strings.Join(historiesLLMFriendly, "\n")
chatHistoriesSlices := m.openAI.SplitContentBasedByTokenLimitations(chatHistories, 2800)
chatHistoriesSummarizations := make([]*openai.ChatHistorySummarizationOutputs, 0, len(chatHistoriesSlices))
for _, s := range chatHistoriesSlices {
var outputs []*openai.ChatHistorySummarizationOutputs
_, _, err := lo.AttemptWithDelay(3, time.Second, func(tried int, delay time.Duration) error {
o, err := m.summarizeChatHistoriesSlice(s)
if err != nil {
m.logger.Errorf("failed to summarize chat histories slice: %s, tried %d...", s, tried)
return err
}
outputs = o
return nil
})
if err != nil {
return "", err
}
if outputs == nil {
continue
}
for _, o := range outputs {
for _, d := range o.Discussion {
d.CriticalIDs = lo.UniqBy(d.CriticalIDs, func(item int64) int64 {
return item
})
d.CriticalIDs = lo.Filter(d.CriticalIDs, func(item int64, _ int) bool {
return item != 0
})
if len(d.CriticalIDs) > 5 {
d.CriticalIDs = d.CriticalIDs[:5]
}
}
}
chatHistoriesSummarizations = append(chatHistoriesSummarizations, outputs...)
}
sb := new(strings.Builder)
err := RecapOutputTemplate.Execute(sb, RecapOutputTemplateInputs{
ChatID: formatChatID(chatID),
Recaps: chatHistoriesSummarizations,
})
if err != nil {
return "", err
}
m.logger.Infof("✅ summarized chat histories: %s", sb.String())
return sb.String(), nil
}