tgbot_misaka_5882f7/botcmd_kanji.go

78 lines
1.9 KiB
Go
Raw Normal View History

2023-04-21 16:43:05 +09:00
package main
import (
"regexp"
"strings"
"github.com/samber/lo"
tele "gopkg.in/telebot.v3"
"git.gensokyo.cafe/kkyy/tgbot_misaka_5882f7/openai"
"git.gensokyo.cafe/kkyy/tgbot_misaka_5882f7/openai/prompts"
)
var kanjiRe = regexp.MustCompile(`\p{Han}`)
func handleKanjiCmd(c tele.Context) error {
msg := c.Message()
if msg == nil {
return nil
}
payload := strings.TrimSpace(msg.Payload)
if payload == "" {
return c.Reply("Usage: `/kanji <text>`", &tele.SendOptions{ParseMode: tele.ModeMarkdown}, tele.Silent)
}
if !kanjiRe.MatchString(payload) {
return c.Reply("// Your text does not contain any Kanji.")
}
req := openai.ChatRequest{
Model: openai.ModelGpt0305Turbo,
Messages: []openai.ChatMessage{
{
Role: openai.ChatRoleSystem,
Content: prompts.KanjiPronunciation(),
},
{
Role: openai.ChatRoleUser,
Content: payload,
},
{
Role: openai.ChatRoleSystem,
Content: `Reminder: Assistant should stick to the task of adding pronunciations for Kanji in the text sent by the user. If user's message seem irrelevant, just reply "IRRELEVANT"`,
},
},
Temperature: lo.ToPtr(0.2),
}
actionCh := setTyping(c)
var irrelevant = false
var replyMsg *tele.Message
err := assistantStreamedResponse(req, func(text string, finished bool) error {
<-actionCh
if strings.HasPrefix(text, `IRRELEVANT`) {
irrelevant = true
return nil // TODO interrupt response
}
var err error
if replyMsg == nil {
replyMsg, err = c.Bot().Reply(msg, text, tele.Silent)
} else {
replyMsg, err = c.Bot().Edit(replyMsg, text)
}
return err
})
if err != nil {
logger.Errorw("assistant: failed to complete conversation", "error", err)
_ = c.Reply("Sorry, there's a technical issue. 😵💫 Please try again later.", tele.Silent)
return err
}
if irrelevant {
return c.Reply("Sorry, I don't know what to do with your input.")
}
return nil
}