62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package plugins
|
|
|
|
import (
|
|
"strings"
|
|
"ymgb/database"
|
|
"ymgb/database/mdb"
|
|
"ymgb/database/red"
|
|
"ymgb/utils/ai"
|
|
|
|
"git.nix13.pw/scuroneko/laniakea"
|
|
)
|
|
|
|
func RegisterAi() *laniakea.Plugin[database.Context] {
|
|
p := laniakea.NewPlugin[database.Context]("AI")
|
|
p.AddCommand(p.NewCommand(gpt, "gpt").SkipCommandAutoGen())
|
|
return p
|
|
}
|
|
|
|
func gpt(ctx *laniakea.MsgContext, db *database.Context) {
|
|
q := strings.Join(ctx.Args, " ")
|
|
api := ai.NewOpenAIAPI(ai.GPTBaseUrl, "", "anthropic/claude-sonnet-4")
|
|
defer api.Close()
|
|
|
|
aiRedisRep := red.NewAiRepository(db)
|
|
chatId, err := aiRedisRep.GetOrCreateChatId(ctx.FromID)
|
|
if err != nil {
|
|
ctx.Error(err)
|
|
return
|
|
}
|
|
history, err := mdb.GetGptChatHistory(db, chatId)
|
|
if err != nil {
|
|
ctx.Error(err)
|
|
return
|
|
}
|
|
aiHistory := make([]ai.Message, len(history))
|
|
for _, m := range history {
|
|
aiHistory = append(aiHistory, ai.Message{
|
|
Role: m.Role,
|
|
Content: m.Message,
|
|
})
|
|
}
|
|
|
|
m := ctx.Answer("Генерация запущена...")
|
|
res, err := api.CreateCompletion(aiHistory, q, 1.0)
|
|
if err != nil {
|
|
ctx.Error(err)
|
|
return
|
|
}
|
|
answer := res.Choices[0].Message.Content
|
|
m.Delete()
|
|
err = mdb.UpdateGptChatHistory(db, chatId, "user", q)
|
|
if err != nil {
|
|
ctx.Error(err)
|
|
}
|
|
err = mdb.UpdateGptChatHistory(db, chatId, "assistant", answer)
|
|
if err != nil {
|
|
ctx.Error(err)
|
|
}
|
|
|
|
ctx.Answer(answer)
|
|
}
|