Compare commits
No commits in common. "main" and "0.2.3" have entirely different histories.
|
@ -13,11 +13,4 @@ WORKDIR /app
|
||||||
|
|
||||||
COPY --from=builder /build/app .
|
COPY --from=builder /build/app .
|
||||||
|
|
||||||
# Do not forget "/v1" in the end
|
|
||||||
ENV OPENAI_API_BASE_URL="" \
|
|
||||||
OPENAI_API_TOKEN="" \
|
|
||||||
TELEGRAM_TOKEN="" \
|
|
||||||
MODEL_TEXT_REQUEST="llama3.1:8b-instruct-q6_K" \
|
|
||||||
MODEL_SUMMARIZE_REQUEST="llama3.1:8b-instruct-q6_K"
|
|
||||||
|
|
||||||
CMD ["/app/app"]
|
CMD ["/app/app"]
|
||||||
|
|
|
@ -8,10 +8,8 @@
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
docker run \
|
docker run \
|
||||||
-e OPENAI_API_TOKEN=123 \
|
-e OLLAMA_TOKEN=123 \
|
||||||
-e OPENAI_API_BASE_URL=http://ollama.localhost:11434/v1 \
|
-e OLLAMA_BASE_URL=http://ollama.localhost:11434/v1 \
|
||||||
-e TELEGRAM_TOKEN=12345 \
|
-e TELEGRAM_TOKEN=12345 \
|
||||||
-e MODEL_TEXT_REQUEST=llama3.1:8b-instruct-q6_K
|
|
||||||
-e MODEL_SUMMARIZE_REQUEST=mistral-nemo:12b-instruct-2407-q4_K_M
|
|
||||||
skobkin/telegram-llm-bot
|
skobkin/telegram-llm-bot
|
||||||
```
|
```
|
||||||
|
|
158
bot/bot.go
158
bot/bot.go
|
@ -6,6 +6,7 @@ import (
|
||||||
th "github.com/mymmrac/telego/telegohandler"
|
th "github.com/mymmrac/telego/telegohandler"
|
||||||
tu "github.com/mymmrac/telego/telegoutil"
|
tu "github.com/mymmrac/telego/telegoutil"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"telegram-ollama-reply-bot/extractor"
|
"telegram-ollama-reply-bot/extractor"
|
||||||
"telegram-ollama-reply-bot/llm"
|
"telegram-ollama-reply-bot/llm"
|
||||||
|
@ -18,38 +19,21 @@ var (
|
||||||
ErrHandlerInit = errors.New("cannot initialize handler")
|
ErrHandlerInit = errors.New("cannot initialize handler")
|
||||||
)
|
)
|
||||||
|
|
||||||
type BotInfo struct {
|
|
||||||
Id int64
|
|
||||||
Username string
|
|
||||||
Name string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Bot struct {
|
type Bot struct {
|
||||||
api *telego.Bot
|
api *telego.Bot
|
||||||
llm *llm.LlmConnector
|
llm *llm.LlmConnector
|
||||||
extractor *extractor.Extractor
|
extractor *extractor.Extractor
|
||||||
stats *stats.Stats
|
stats *stats.Stats
|
||||||
models ModelSelection
|
|
||||||
history map[int64]*MessageRingBuffer
|
|
||||||
profile BotInfo
|
|
||||||
|
|
||||||
markdownV1Replacer *strings.Replacer
|
markdownV1Replacer *strings.Replacer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBot(
|
func NewBot(api *telego.Bot, llm *llm.LlmConnector, extractor *extractor.Extractor) *Bot {
|
||||||
api *telego.Bot,
|
|
||||||
llm *llm.LlmConnector,
|
|
||||||
extractor *extractor.Extractor,
|
|
||||||
models ModelSelection,
|
|
||||||
) *Bot {
|
|
||||||
return &Bot{
|
return &Bot{
|
||||||
api: api,
|
api: api,
|
||||||
llm: llm,
|
llm: llm,
|
||||||
extractor: extractor,
|
extractor: extractor,
|
||||||
stats: stats.NewStats(),
|
stats: stats.NewStats(),
|
||||||
models: models,
|
|
||||||
history: make(map[int64]*MessageRingBuffer),
|
|
||||||
profile: BotInfo{0, "", ""},
|
|
||||||
|
|
||||||
markdownV1Replacer: strings.NewReplacer(
|
markdownV1Replacer: strings.NewReplacer(
|
||||||
// https://core.telegram.org/bots/api#markdown-style
|
// https://core.telegram.org/bots/api#markdown-style
|
||||||
|
@ -71,12 +55,6 @@ func (b *Bot) Run() error {
|
||||||
|
|
||||||
slog.Info("Running api as", "id", botUser.ID, "username", botUser.Username, "name", botUser.FirstName, "is_bot", botUser.IsBot)
|
slog.Info("Running api as", "id", botUser.ID, "username", botUser.Username, "name", botUser.FirstName, "is_bot", botUser.IsBot)
|
||||||
|
|
||||||
b.profile = BotInfo{
|
|
||||||
Id: botUser.ID,
|
|
||||||
Username: botUser.Username,
|
|
||||||
Name: botUser.FirstName,
|
|
||||||
}
|
|
||||||
|
|
||||||
updates, err := b.api.UpdatesViaLongPolling(nil)
|
updates, err := b.api.UpdatesViaLongPolling(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Cannot get update channel", "error", err)
|
slog.Error("Cannot get update channel", "error", err)
|
||||||
|
@ -95,60 +73,42 @@ func (b *Bot) Run() error {
|
||||||
defer b.api.StopLongPolling()
|
defer b.api.StopLongPolling()
|
||||||
|
|
||||||
// Middlewares
|
// Middlewares
|
||||||
bh.Use(b.chatHistory)
|
|
||||||
bh.Use(b.chatTypeStatsCounter)
|
bh.Use(b.chatTypeStatsCounter)
|
||||||
|
|
||||||
// Command handlers
|
// Handlers
|
||||||
bh.Handle(b.startHandler, th.CommandEqual("start"))
|
bh.Handle(b.startHandler, th.CommandEqual("start"))
|
||||||
bh.Handle(b.summarizeHandler, th.Or(th.CommandEqual("summarize"), th.CommandEqual("s")))
|
bh.Handle(b.heyHandler, th.CommandEqual("hey"))
|
||||||
|
bh.Handle(b.summarizeHandler, th.CommandEqual("summarize"))
|
||||||
bh.Handle(b.statsHandler, th.CommandEqual("stats"))
|
bh.Handle(b.statsHandler, th.CommandEqual("stats"))
|
||||||
bh.Handle(b.helpHandler, th.CommandEqual("help"))
|
bh.Handle(b.helpHandler, th.CommandEqual("help"))
|
||||||
bh.Handle(b.textMessageHandler, th.AnyMessageWithText())
|
|
||||||
|
|
||||||
bh.Start()
|
bh.Start()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) textMessageHandler(bot *telego.Bot, update telego.Update) {
|
func (b *Bot) heyHandler(bot *telego.Bot, update telego.Update) {
|
||||||
slog.Debug("/any-message")
|
slog.Info("/hey", "message-text", update.Message.Text)
|
||||||
|
|
||||||
message := update.Message
|
b.stats.HeyRequest()
|
||||||
|
|
||||||
switch {
|
parts := strings.SplitN(update.Message.Text, " ", 2)
|
||||||
// Mentions
|
userMessage := "Hey!"
|
||||||
case b.isMentionOfMe(update):
|
if len(parts) == 2 {
|
||||||
slog.Info("/any-message", "type", "mention")
|
userMessage = parts[1]
|
||||||
b.processMention(message)
|
|
||||||
// Replies
|
|
||||||
case b.isReplyToMe(update):
|
|
||||||
slog.Info("/any-message", "type", "reply")
|
|
||||||
b.processMention(message)
|
|
||||||
// Private chat
|
|
||||||
case b.isPrivateWithMe(update):
|
|
||||||
slog.Info("/any-message", "type", "private")
|
|
||||||
b.processMention(message)
|
|
||||||
default:
|
|
||||||
slog.Debug("/any-message", "info", "Message is not mention, reply or private chat. Skipping.")
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) processMention(message *telego.Message) {
|
chatID := tu.ID(update.Message.Chat.ID)
|
||||||
b.stats.Mention()
|
|
||||||
|
|
||||||
slog.Info("/mention", "chat", message.Chat.ID)
|
|
||||||
|
|
||||||
chatID := tu.ID(message.Chat.ID)
|
|
||||||
|
|
||||||
b.sendTyping(chatID)
|
b.sendTyping(chatID)
|
||||||
|
|
||||||
requestContext := b.createLlmRequestContextFromMessage(message)
|
requestContext := b.createLlmRequestContext(update)
|
||||||
|
|
||||||
llmReply, err := b.llm.HandleChatMessage(message.Text, b.models.TextRequestModel, requestContext)
|
llmReply, err := b.llm.HandleSingleRequest(userMessage, llm.ModelMistralUncensored, requestContext)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Cannot get reply from LLM connector")
|
slog.Error("Cannot get reply from LLM connector")
|
||||||
|
|
||||||
_, _ = b.api.SendMessage(b.reply(message, tu.Message(
|
_, _ = b.api.SendMessage(b.reply(update.Message, tu.Message(
|
||||||
chatID,
|
chatID,
|
||||||
"LLM request error. Try again later.",
|
"LLM request error. Try again later.",
|
||||||
)))
|
)))
|
||||||
|
@ -156,23 +116,19 @@ func (b *Bot) processMention(message *telego.Message) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
slog.Debug("Got completion. Going to send.", "llm-completion", llmReply)
|
slog.Debug("Got completion. Going to send.", "llm-reply", llmReply)
|
||||||
|
|
||||||
reply := tu.Message(
|
message := tu.Message(
|
||||||
chatID,
|
chatID,
|
||||||
b.escapeMarkdownV1Symbols(llmReply),
|
b.escapeMarkdownV1Symbols(llmReply),
|
||||||
).WithParseMode("Markdown")
|
).WithParseMode("Markdown")
|
||||||
|
|
||||||
_, err = b.api.SendMessage(b.reply(message, reply))
|
_, err = bot.SendMessage(b.reply(update.Message, message))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Can't send reply message", "error", err)
|
slog.Error("Can't send reply message", "error", err)
|
||||||
|
|
||||||
b.trySendReplyError(message)
|
b.trySendReplyError(update.Message)
|
||||||
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
b.saveBotReplyToHistory(message, llmReply)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
||||||
|
@ -184,7 +140,7 @@ func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
||||||
|
|
||||||
b.sendTyping(chatID)
|
b.sendTyping(chatID)
|
||||||
|
|
||||||
args := strings.SplitN(update.Message.Text, " ", 2)
|
args := strings.Split(update.Message.Text, " ")
|
||||||
|
|
||||||
if len(args) < 2 {
|
if len(args) < 2 {
|
||||||
_, _ = bot.SendMessage(tu.Message(
|
_, _ = bot.SendMessage(tu.Message(
|
||||||
|
@ -197,8 +153,9 @@ func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !isValidAndAllowedUrl(args[1]) {
|
_, err := url.ParseRequestURI(args[1])
|
||||||
slog.Error("Provided text is not a valid URL", "text", args[1])
|
if err != nil {
|
||||||
|
slog.Error("Provided URL is not valid", "url", args[1])
|
||||||
|
|
||||||
_, _ = b.api.SendMessage(b.reply(update.Message, tu.Message(
|
_, _ = b.api.SendMessage(b.reply(update.Message, tu.Message(
|
||||||
chatID,
|
chatID,
|
||||||
|
@ -213,7 +170,7 @@ func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
||||||
slog.Error("Cannot retrieve an article using extractor", "error", err)
|
slog.Error("Cannot retrieve an article using extractor", "error", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
llmReply, err := b.llm.Summarize(article.Text, b.models.SummarizeModel)
|
llmReply, err := b.llm.Summarize(article.Text, llm.ModelMistralUncensored)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Cannot get reply from LLM connector")
|
slog.Error("Cannot get reply from LLM connector")
|
||||||
|
|
||||||
|
@ -225,7 +182,7 @@ func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
slog.Debug("Got completion. Going to send.", "llm-completion", llmReply)
|
slog.Debug("Got completion. Going to send.", "llm-reply", llmReply)
|
||||||
|
|
||||||
message := tu.Message(
|
message := tu.Message(
|
||||||
chatID,
|
chatID,
|
||||||
|
@ -253,9 +210,7 @@ func (b *Bot) helpHandler(bot *telego.Bot, update telego.Update) {
|
||||||
"Instructions:\r\n"+
|
"Instructions:\r\n"+
|
||||||
"/hey <text> - Ask something from LLM\r\n"+
|
"/hey <text> - Ask something from LLM\r\n"+
|
||||||
"/summarize <link> - Summarize text from the provided link\r\n"+
|
"/summarize <link> - Summarize text from the provided link\r\n"+
|
||||||
"/s <link> - Shorter version\r\n"+
|
"/help - Show this help",
|
||||||
"/help - Show this help\r\n\r\n"+
|
|
||||||
"Mention bot or reply to it's message to communicate with it",
|
|
||||||
)))
|
)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Cannot send a message", "error", err)
|
slog.Error("Cannot send a message", "error", err)
|
||||||
|
@ -304,6 +259,65 @@ func (b *Bot) statsHandler(bot *telego.Bot, update telego.Update) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Bot) createLlmRequestContext(update telego.Update) llm.RequestContext {
|
||||||
|
message := update.Message
|
||||||
|
|
||||||
|
rc := llm.RequestContext{}
|
||||||
|
|
||||||
|
if message == nil {
|
||||||
|
slog.Debug("request context creation problem: no message provided. returning empty context.", "request-context", rc)
|
||||||
|
|
||||||
|
return rc
|
||||||
|
}
|
||||||
|
|
||||||
|
user := message.From
|
||||||
|
if user != nil {
|
||||||
|
rc.User = llm.UserContext{
|
||||||
|
Username: user.Username,
|
||||||
|
FirstName: user.FirstName,
|
||||||
|
LastName: user.LastName,
|
||||||
|
IsPremium: user.IsPremium,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := message.Chat
|
||||||
|
rc.Chat = llm.ChatContext{
|
||||||
|
Title: chat.Title,
|
||||||
|
Description: chat.Description,
|
||||||
|
Type: chat.Type,
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Debug("request context created", "request-context", rc)
|
||||||
|
|
||||||
|
return rc
|
||||||
|
}
|
||||||
|
|
||||||
func (b *Bot) escapeMarkdownV1Symbols(input string) string {
|
func (b *Bot) escapeMarkdownV1Symbols(input string) string {
|
||||||
return b.markdownV1Replacer.Replace(input)
|
return b.markdownV1Replacer.Replace(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Bot) reply(originalMessage *telego.Message, newMessage *telego.SendMessageParams) *telego.SendMessageParams {
|
||||||
|
return newMessage.WithReplyParameters(&telego.ReplyParameters{
|
||||||
|
MessageID: originalMessage.MessageID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) sendTyping(chatId telego.ChatID) {
|
||||||
|
slog.Debug("Setting 'typing' chat action")
|
||||||
|
|
||||||
|
err := b.api.SendChatAction(tu.ChatAction(chatId, "typing"))
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Cannot set chat action", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bot) trySendReplyError(message *telego.Message) {
|
||||||
|
if message == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = b.api.SendMessage(b.reply(message, tu.Message(
|
||||||
|
tu.ID(message.Chat.ID),
|
||||||
|
"Error occurred while trying to send reply.",
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
|
@ -1,93 +0,0 @@
|
||||||
package bot
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/mymmrac/telego"
|
|
||||||
tu "github.com/mymmrac/telego/telegoutil"
|
|
||||||
"log/slog"
|
|
||||||
"net/url"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
allowedUrlSchemes = []string{"http", "https"}
|
|
||||||
)
|
|
||||||
|
|
||||||
func (b *Bot) reply(originalMessage *telego.Message, newMessage *telego.SendMessageParams) *telego.SendMessageParams {
|
|
||||||
return newMessage.WithReplyParameters(&telego.ReplyParameters{
|
|
||||||
MessageID: originalMessage.MessageID,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) sendTyping(chatId telego.ChatID) {
|
|
||||||
slog.Debug("Setting 'typing' chat action")
|
|
||||||
|
|
||||||
err := b.api.SendChatAction(tu.ChatAction(chatId, "typing"))
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("Cannot set chat action", "error", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) trySendReplyError(message *telego.Message) {
|
|
||||||
if message == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _ = b.api.SendMessage(b.reply(message, tu.Message(
|
|
||||||
tu.ID(message.Chat.ID),
|
|
||||||
"Error occurred while trying to send reply.",
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) isMentionOfMe(update telego.Update) bool {
|
|
||||||
if update.Message == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.Contains(update.Message.Text, "@"+b.profile.Username)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) isReplyToMe(update telego.Update) bool {
|
|
||||||
message := update.Message
|
|
||||||
|
|
||||||
if message == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if message.ReplyToMessage == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if message.ReplyToMessage.From == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
replyToMessage := message.ReplyToMessage
|
|
||||||
|
|
||||||
return replyToMessage != nil && replyToMessage.From.ID == b.profile.Id
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) isPrivateWithMe(update telego.Update) bool {
|
|
||||||
message := update.Message
|
|
||||||
|
|
||||||
if message == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return message.Chat.Type == telego.ChatTypePrivate
|
|
||||||
}
|
|
||||||
|
|
||||||
func isValidAndAllowedUrl(text string) bool {
|
|
||||||
u, err := url.ParseRequestURI(text)
|
|
||||||
if err != nil {
|
|
||||||
slog.Debug("Provided text is not an URL", "text", text)
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if !slices.Contains(allowedUrlSchemes, strings.ToLower(u.Scheme)) {
|
|
||||||
slog.Debug("Provided URL has disallowed scheme", "scheme", u.Scheme, "allowed-schemes", allowedUrlSchemes)
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
|
@ -1,93 +0,0 @@
|
||||||
package bot
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/mymmrac/telego"
|
|
||||||
"log/slog"
|
|
||||||
)
|
|
||||||
|
|
||||||
const HistoryLength = 150
|
|
||||||
|
|
||||||
type Message struct {
|
|
||||||
Name string
|
|
||||||
Text string
|
|
||||||
IsMe bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type MessageRingBuffer struct {
|
|
||||||
messages []Message
|
|
||||||
capacity int
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMessageBuffer(capacity int) *MessageRingBuffer {
|
|
||||||
return &MessageRingBuffer{
|
|
||||||
messages: make([]Message, 0, capacity),
|
|
||||||
capacity: capacity,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *MessageRingBuffer) Push(element Message) {
|
|
||||||
if len(b.messages) >= b.capacity {
|
|
||||||
b.messages = b.messages[1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
b.messages = append(b.messages, element)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *MessageRingBuffer) GetAll() []Message {
|
|
||||||
return b.messages
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) saveChatMessageToHistory(message *telego.Message) {
|
|
||||||
chatId := message.Chat.ID
|
|
||||||
|
|
||||||
slog.Info(
|
|
||||||
"history-message-save",
|
|
||||||
"chat", chatId,
|
|
||||||
"from_id", message.From.ID,
|
|
||||||
"from_name", message.From.FirstName,
|
|
||||||
"text", message.Text,
|
|
||||||
)
|
|
||||||
|
|
||||||
_, ok := b.history[chatId]
|
|
||||||
if !ok {
|
|
||||||
b.history[chatId] = NewMessageBuffer(HistoryLength)
|
|
||||||
}
|
|
||||||
|
|
||||||
b.history[chatId].Push(Message{
|
|
||||||
Name: message.From.FirstName,
|
|
||||||
Text: message.Text,
|
|
||||||
IsMe: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) saveBotReplyToHistory(message *telego.Message, reply string) {
|
|
||||||
chatId := message.Chat.ID
|
|
||||||
|
|
||||||
slog.Info(
|
|
||||||
"history-reply-save",
|
|
||||||
"chat", chatId,
|
|
||||||
"to_id", message.From.ID,
|
|
||||||
"to_name", message.From.FirstName,
|
|
||||||
"text", reply,
|
|
||||||
)
|
|
||||||
|
|
||||||
_, ok := b.history[chatId]
|
|
||||||
if !ok {
|
|
||||||
b.history[chatId] = NewMessageBuffer(HistoryLength)
|
|
||||||
}
|
|
||||||
|
|
||||||
b.history[chatId].Push(Message{
|
|
||||||
Name: b.profile.Username,
|
|
||||||
Text: reply,
|
|
||||||
IsMe: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Bot) getChatHistory(chatId int64) []Message {
|
|
||||||
_, ok := b.history[chatId]
|
|
||||||
if !ok {
|
|
||||||
return make([]Message, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
return b.history[chatId].GetAll()
|
|
||||||
}
|
|
|
@ -10,41 +10,21 @@ func (b *Bot) chatTypeStatsCounter(bot *telego.Bot, update telego.Update, next t
|
||||||
message := update.Message
|
message := update.Message
|
||||||
|
|
||||||
if message == nil {
|
if message == nil {
|
||||||
slog.Info("stats-middleware: update has no message. skipping.")
|
slog.Info("chat-type-middleware: update has no message. skipping.")
|
||||||
|
|
||||||
next(bot, update)
|
next(bot, update)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
slog.Info("chat-type-middleware: counting message chat type in stats", "type", message.Chat.Type)
|
||||||
|
|
||||||
switch message.Chat.Type {
|
switch message.Chat.Type {
|
||||||
case telego.ChatTypeGroup, telego.ChatTypeSupergroup:
|
case telego.ChatTypeGroup, telego.ChatTypeSupergroup:
|
||||||
if b.isMentionOfMe(update) || b.isReplyToMe(update) {
|
b.stats.GroupRequest()
|
||||||
slog.Info("stats-middleware: counting message chat type in stats", "type", message.Chat.Type)
|
|
||||||
b.stats.GroupRequest()
|
|
||||||
}
|
|
||||||
case telego.ChatTypePrivate:
|
case telego.ChatTypePrivate:
|
||||||
slog.Info("stats-middleware: counting message chat type in stats", "type", message.Chat.Type)
|
|
||||||
b.stats.PrivateRequest()
|
b.stats.PrivateRequest()
|
||||||
}
|
}
|
||||||
|
|
||||||
next(bot, update)
|
next(bot, update)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Bot) chatHistory(bot *telego.Bot, update telego.Update, next telegohandler.Handler) {
|
|
||||||
message := update.Message
|
|
||||||
|
|
||||||
if message == nil {
|
|
||||||
slog.Info("chat-history-middleware: update has no message. skipping.")
|
|
||||||
|
|
||||||
next(bot, update)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("chat-history-middleware: saving message to history for", "chat_id", message.Chat.ID)
|
|
||||||
|
|
||||||
b.saveChatMessageToHistory(message)
|
|
||||||
|
|
||||||
next(bot, update)
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,6 +0,0 @@
|
||||||
package bot
|
|
||||||
|
|
||||||
type ModelSelection struct {
|
|
||||||
TextRequestModel string
|
|
||||||
SummarizeModel string
|
|
||||||
}
|
|
|
@ -1,68 +0,0 @@
|
||||||
package bot
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/mymmrac/telego"
|
|
||||||
"log/slog"
|
|
||||||
"telegram-ollama-reply-bot/llm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (b *Bot) createLlmRequestContextFromMessage(message *telego.Message) llm.RequestContext {
|
|
||||||
rc := llm.RequestContext{
|
|
||||||
Empty: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
if message == nil {
|
|
||||||
slog.Debug("request context creation problem: no message provided. returning empty context.", "request-context", rc)
|
|
||||||
|
|
||||||
return rc
|
|
||||||
}
|
|
||||||
|
|
||||||
rc.Empty = false
|
|
||||||
|
|
||||||
user := message.From
|
|
||||||
|
|
||||||
if user != nil {
|
|
||||||
rc.User = llm.UserContext{
|
|
||||||
Username: user.Username,
|
|
||||||
FirstName: user.FirstName,
|
|
||||||
LastName: user.LastName,
|
|
||||||
IsPremium: user.IsPremium,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: implement retrieval of chat description
|
|
||||||
chat := message.Chat
|
|
||||||
|
|
||||||
history := b.getChatHistory(chat.ID)
|
|
||||||
|
|
||||||
rc.Chat = llm.ChatContext{
|
|
||||||
Title: chat.Title,
|
|
||||||
// TODO: fill when ChatFullInfo retrieved
|
|
||||||
//Description: chat.Description,
|
|
||||||
Type: chat.Type,
|
|
||||||
History: historyToLlmMessages(history),
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Debug("request context created", "request-context", rc)
|
|
||||||
|
|
||||||
return rc
|
|
||||||
}
|
|
||||||
|
|
||||||
func historyToLlmMessages(history []Message) []llm.ChatMessage {
|
|
||||||
length := len(history)
|
|
||||||
|
|
||||||
if length > 0 {
|
|
||||||
result := make([]llm.ChatMessage, 0, length)
|
|
||||||
|
|
||||||
for _, msg := range history {
|
|
||||||
result = append(result, llm.ChatMessage{
|
|
||||||
Name: msg.Name,
|
|
||||||
Text: msg.Text,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
return make([]llm.ChatMessage, 0)
|
|
||||||
}
|
|
86
llm/llm.go
86
llm/llm.go
|
@ -5,13 +5,13 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/sashabaranov/go-openai"
|
"github.com/sashabaranov/go-openai"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrLlmBackendRequestFailed = errors.New("llm back-end request failed")
|
ErrLlmBackendRequestFailed = errors.New("llm back-end request failed")
|
||||||
ErrNoChoices = errors.New("no choices in LLM response")
|
ErrNoChoices = errors.New("no choices in LLM response")
|
||||||
|
|
||||||
|
ModelMistralUncensored = "dolphin-mistral"
|
||||||
)
|
)
|
||||||
|
|
||||||
type LlmConnector struct {
|
type LlmConnector struct {
|
||||||
|
@ -29,47 +29,20 @@ func NewConnector(baseUrl string, token string) *LlmConnector {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LlmConnector) HandleChatMessage(text string, model string, requestContext RequestContext) (string, error) {
|
func (l *LlmConnector) HandleSingleRequest(text string, model string, requestContext RequestContext) (string, error) {
|
||||||
systemPrompt := "You're a bot in the Telegram chat.\n" +
|
|
||||||
"You're using a free model called \"" + model + "\".\n\n" +
|
|
||||||
requestContext.Prompt()
|
|
||||||
|
|
||||||
historyLength := len(requestContext.Chat.History)
|
|
||||||
|
|
||||||
if historyLength > 0 {
|
|
||||||
systemPrompt += "\nYou have access to last " + strconv.Itoa(historyLength) + "messages in this chat."
|
|
||||||
}
|
|
||||||
|
|
||||||
req := openai.ChatCompletionRequest{
|
req := openai.ChatCompletionRequest{
|
||||||
Model: model,
|
Model: model,
|
||||||
Messages: []openai.ChatCompletionMessage{
|
Messages: []openai.ChatCompletionMessage{
|
||||||
{
|
{
|
||||||
Role: openai.ChatMessageRoleSystem,
|
Role: openai.ChatMessageRoleSystem,
|
||||||
Content: systemPrompt,
|
Content: "You're a bot in the Telegram chat. " +
|
||||||
|
"You're using a free model called \"" + model + "\". " +
|
||||||
|
"You see only messages addressed to you using commands due to privacy settings. " +
|
||||||
|
requestContext.Prompt(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if historyLength > 0 {
|
|
||||||
for _, msg := range requestContext.Chat.History {
|
|
||||||
var msgRole string
|
|
||||||
var msgText string
|
|
||||||
|
|
||||||
if msg.IsMe {
|
|
||||||
msgRole = openai.ChatMessageRoleAssistant
|
|
||||||
msgText = msg.Text
|
|
||||||
} else {
|
|
||||||
msgRole = openai.ChatMessageRoleSystem
|
|
||||||
msgText = "User " + msg.Name + " said:\n" + msg.Text
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Messages = append(req.Messages, openai.ChatCompletionMessage{
|
|
||||||
Role: msgRole,
|
|
||||||
Content: msgText,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
req.Messages = append(req.Messages, openai.ChatCompletionMessage{
|
req.Messages = append(req.Messages, openai.ChatCompletionMessage{
|
||||||
Role: openai.ChatMessageRoleUser,
|
Role: openai.ChatMessageRoleUser,
|
||||||
Content: text,
|
Content: text,
|
||||||
|
@ -100,10 +73,9 @@ func (l *LlmConnector) Summarize(text string, model string) (string, error) {
|
||||||
{
|
{
|
||||||
Role: openai.ChatMessageRoleSystem,
|
Role: openai.ChatMessageRoleSystem,
|
||||||
Content: "You're a text shortener. Give a very brief summary of the main facts " +
|
Content: "You're a text shortener. Give a very brief summary of the main facts " +
|
||||||
"point by point. Format them as a list of bullet points each starting with \"-\". " +
|
"point by point. Format them as a list of bullet points. " +
|
||||||
"Avoid any commentaries and value judgement on the matter. " +
|
"Avoid any commentaries and value judgement on the matter. " +
|
||||||
"If possible, respond in the same language as the original text." +
|
"If possible, use the same language as the original text.",
|
||||||
"Do not use any non-ASCII characters.",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
@ -130,41 +102,3 @@ func (l *LlmConnector) Summarize(text string, model string) (string, error) {
|
||||||
|
|
||||||
return resp.Choices[0].Message.Content, nil
|
return resp.Choices[0].Message.Content, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LlmConnector) GetModels() []string {
|
|
||||||
var result []string
|
|
||||||
|
|
||||||
models, err := l.client.ListModels(context.Background())
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("llm: Model list request failed", "error", err)
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("Model list retrieved", "models", models)
|
|
||||||
|
|
||||||
for _, model := range models.Models {
|
|
||||||
result = append(result, model.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LlmConnector) HasModel(id string) bool {
|
|
||||||
model, err := l.client.GetModel(context.Background(), id)
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("llm: Model request failed", "error", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Debug("llm: Returned model", "model", model)
|
|
||||||
|
|
||||||
if model.ID != "" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func quoteMessage(text string) string {
|
|
||||||
return "> " + strings.ReplaceAll(text, "\n", "\n> ")
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,9 +1,8 @@
|
||||||
package llm
|
package llm
|
||||||
|
|
||||||
type RequestContext struct {
|
type RequestContext struct {
|
||||||
Empty bool
|
User UserContext
|
||||||
User UserContext
|
Chat ChatContext
|
||||||
Chat ChatContext
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserContext struct {
|
type UserContext struct {
|
||||||
|
@ -17,48 +16,28 @@ type ChatContext struct {
|
||||||
Title string
|
Title string
|
||||||
Description string
|
Description string
|
||||||
Type string
|
Type string
|
||||||
History []ChatMessage
|
|
||||||
}
|
|
||||||
|
|
||||||
type ChatMessage struct {
|
|
||||||
Name string
|
|
||||||
Text string
|
|
||||||
IsMe bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c RequestContext) Prompt() string {
|
func (c RequestContext) Prompt() string {
|
||||||
if c.Empty {
|
prompt := "The type of chat you're in is \"" + c.Chat.Type + "\". "
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
prompt := ""
|
|
||||||
|
|
||||||
prompt += "The type of chat you're in is \"" + c.Chat.Type + "\". "
|
|
||||||
|
|
||||||
if c.Chat.Type == "group" || c.Chat.Type == "supergroup" {
|
|
||||||
prompt += "Please consider that there are several users in this chat type who may discuss several unrelated " +
|
|
||||||
"topics. Try to respond only about the topic you were asked about and only to the user who asked you, " +
|
|
||||||
"but keep in mind another chat history. "
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Chat.Title != "" {
|
if c.Chat.Title != "" {
|
||||||
prompt += "\nChat is called \"" + c.Chat.Title + "\". "
|
prompt += "Chat is called \"" + c.Chat.Title + "\". "
|
||||||
}
|
}
|
||||||
if c.Chat.Description != "" {
|
if c.Chat.Description != "" {
|
||||||
prompt += "Chat description is \"" + c.Chat.Description + "\". "
|
prompt += "Chat description is \"" + c.Chat.Description + "\". "
|
||||||
}
|
}
|
||||||
|
|
||||||
prompt += "\nProfile of the user who mentioned you in the chat:" +
|
prompt += "According to their profile, first name of the user who wrote you is \"" + c.User.FirstName + "\". "
|
||||||
"First name: \"" + c.User.FirstName + "\"\n"
|
|
||||||
if c.User.Username != "" {
|
if c.User.Username != "" {
|
||||||
prompt += "Username: @" + c.User.Username + ".\n"
|
prompt += "Their username is @" + c.User.Username + ". "
|
||||||
}
|
}
|
||||||
if c.User.LastName != "" {
|
if c.User.LastName != "" {
|
||||||
prompt += "Last name: \"" + c.User.LastName + "\"\n"
|
prompt += "Their last name is \"" + c.User.LastName + "\". "
|
||||||
|
}
|
||||||
|
if c.User.IsPremium {
|
||||||
|
prompt += "They have Telegram Premium subscription. "
|
||||||
}
|
}
|
||||||
//if c.User.IsPremium {
|
|
||||||
// prompt += "Telegram Premium subscription: active."
|
|
||||||
//}
|
|
||||||
|
|
||||||
return prompt
|
return prompt
|
||||||
}
|
}
|
||||||
|
|
27
main.go
27
main.go
|
@ -12,31 +12,12 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
apiToken := os.Getenv("OPENAI_API_TOKEN")
|
ollamaToken := os.Getenv("OLLAMA_TOKEN")
|
||||||
apiBaseUrl := os.Getenv("OPENAI_API_BASE_URL")
|
ollamaBaseUrl := os.Getenv("OLLAMA_BASE_URL")
|
||||||
|
|
||||||
models := bot.ModelSelection{
|
|
||||||
TextRequestModel: os.Getenv("MODEL_TEXT_REQUEST"),
|
|
||||||
SummarizeModel: os.Getenv("MODEL_SUMMARIZE_REQUEST"),
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("Selected", "models", models)
|
|
||||||
|
|
||||||
telegramToken := os.Getenv("TELEGRAM_TOKEN")
|
telegramToken := os.Getenv("TELEGRAM_TOKEN")
|
||||||
|
|
||||||
llmc := llm.NewConnector(apiBaseUrl, apiToken)
|
llmc := llm.NewConnector(ollamaBaseUrl, ollamaToken)
|
||||||
|
|
||||||
slog.Info("Checking models availability")
|
|
||||||
|
|
||||||
for _, model := range []string{models.TextRequestModel, models.SummarizeModel} {
|
|
||||||
if !llmc.HasModel(model) {
|
|
||||||
slog.Error("Model not unavailable", "model", model)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("All needed models are available")
|
|
||||||
|
|
||||||
ext := extractor.NewExtractor()
|
ext := extractor.NewExtractor()
|
||||||
|
|
||||||
telegramApi, err := tg.NewBot(telegramToken, tg.WithLogger(bot.NewLogger("telego: ")))
|
telegramApi, err := tg.NewBot(telegramToken, tg.WithLogger(bot.NewLogger("telego: ")))
|
||||||
|
@ -45,7 +26,7 @@ func main() {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
botService := bot.NewBot(telegramApi, llmc, ext, models)
|
botService := bot.NewBot(telegramApi, llmc, ext)
|
||||||
|
|
||||||
err = botService.Run()
|
err = botService.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -13,9 +13,8 @@ type Stats struct {
|
||||||
|
|
||||||
GroupRequests uint64
|
GroupRequests uint64
|
||||||
PrivateRequests uint64
|
PrivateRequests uint64
|
||||||
InlineQueries uint64
|
|
||||||
|
|
||||||
Mentions uint64
|
HeyRequests uint64
|
||||||
SummarizeRequests uint64
|
SummarizeRequests uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,9 +24,8 @@ func NewStats() *Stats {
|
||||||
|
|
||||||
GroupRequests: 0,
|
GroupRequests: 0,
|
||||||
PrivateRequests: 0,
|
PrivateRequests: 0,
|
||||||
InlineQueries: 0,
|
|
||||||
|
|
||||||
Mentions: 0,
|
HeyRequests: 0,
|
||||||
SummarizeRequests: 0,
|
SummarizeRequests: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -38,18 +36,16 @@ func (s *Stats) MarshalJSON() ([]byte, error) {
|
||||||
|
|
||||||
GroupRequests uint64 `json:"group_requests"`
|
GroupRequests uint64 `json:"group_requests"`
|
||||||
PrivateRequests uint64 `json:"private_requests"`
|
PrivateRequests uint64 `json:"private_requests"`
|
||||||
InlineQueries uint64 `json:"inline_queries"`
|
|
||||||
|
|
||||||
Mentions uint64 `json:"mentions"`
|
HeyRequests uint64 `json:"hey_requests"`
|
||||||
SummarizeRequests uint64 `json:"summarize_requests"`
|
SummarizeRequests uint64 `json:"summarize_requests"`
|
||||||
}{
|
}{
|
||||||
Uptime: time.Now().Sub(s.RunningSince).String(),
|
Uptime: time.Now().Sub(s.RunningSince).String(),
|
||||||
|
|
||||||
GroupRequests: s.GroupRequests,
|
GroupRequests: s.GroupRequests,
|
||||||
PrivateRequests: s.PrivateRequests,
|
PrivateRequests: s.PrivateRequests,
|
||||||
InlineQueries: s.InlineQueries,
|
|
||||||
|
|
||||||
Mentions: s.Mentions,
|
HeyRequests: s.HeyRequests,
|
||||||
SummarizeRequests: s.SummarizeRequests,
|
SummarizeRequests: s.SummarizeRequests,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -63,12 +59,6 @@ func (s *Stats) String() string {
|
||||||
return string(data)
|
return string(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Stats) InlineQuery() {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
s.InlineQueries++
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Stats) GroupRequest() {
|
func (s *Stats) GroupRequest() {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
|
@ -81,10 +71,10 @@ func (s *Stats) PrivateRequest() {
|
||||||
s.PrivateRequests++
|
s.PrivateRequests++
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Stats) Mention() {
|
func (s *Stats) HeyRequest() {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
s.Mentions++
|
s.HeyRequests++
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Stats) SummarizeRequest() {
|
func (s *Stats) SummarizeRequest() {
|
||||||
|
|
Loading…
Reference in a new issue