We need to modify it:
first of all lets figure out a way to handle voice messages and what we return from there better. Right now we can only return TODOs, but we will have more options (a new reminder or a note).
Also I want to implement a way to send back inline keyboard with todos on each row and it will also have edit and delete button for said todo
Assistant
To achieve your goals, we'll need to make several modifications to your existing code:
Expand the capabilities of your bot to handle multiple types of content from voice messages (To-Do, Reminder, Note).
Implement an inline keyboard to display To-Dos with edit and delete buttons.
Below, I'll guide you through the necessary steps, providing code snippets and explanations for each modification.
1. Expanding Voice Message Handling
a. Update the System Prompt
First, we need to modify the system prompt to instruct the AI assistant to handle multiple types of content. Update the SPEECH_TO_TEXT_SYSTEM_PROMPT in prompt.go to include instructions for creating reminders and notes:
go
const SPEECH_TO_TEXT_SYSTEM_PROMPT = `
You are an AI assistant helping the user manage tasks.
You can create To-Dos, Reminders, and Notes based on the user's input.
Analyze the user's voice message and determine the appropriate action.
If the user wants to create a To-Do, Reminder, or Note, use the corresponding function call.
If you cannot understand the user's request, reply with "I do not understand you."
`
b. Define New Tools
Update tool.go to include new functions for creating reminders and notes:
go
type Reminder struct {
Time string `json:"time"`
Message string `json:"message"`
}
type Note struct {
Title string `json:"title"`
Content string `json:"content"`
}
// Function to create a new Reminder
func createNewReminder(args string) (Reminder, error) {
var reminder Reminder
if err := json.Unmarshal([]byte(args), &reminder); err != nil {
logger.Log.Errorf("Error parsing reminder arguments: %v", err)
return Reminder{}, err
}
// Add logic to store the reminder
return reminder, nil
}
// Function to create a new Note
func createNewNote(args string) (Note, error) {
var note Note
if err := json.Unmarshal([]byte(args), ¬e); err != nil {
logger.Log.Errorf("Error parsing note arguments: %v", err)
return Note{}, err
}
// Add logic to store the note
return note, nil
}
// Update available tools
var availableTools = []llms.Tool{
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createNewToDo",
Description: "Create a new To-Do List.",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{
"type": "string",
"description": "Name of the To-Do",
},
"todos": map[string]interface{}{
"type": "string",
"description": "Comma-separated list of todos to add",
},
},
"required": []string{"name", "todos"},
},
},
},
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createNewReminder",
Description: "Create a new Reminder.",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"time": map[string]interface{}{
"type": "string",
"description": "Time for the reminder (e.g., 'tomorrow at 5pm')",
},
"message": map[string]interface{}{
"type": "string",
"description": "Reminder message",
},
},
"required": []string{"time", "message"},
},
},
},
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createNewNote",
Description: "Create a new Note.",
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"title": map[string]interface{}{
"type": "string",
"description": "Title of the note",
},
"content": map[string]interface{}{
"type": "string",
"description": "Content of the note",
},
},
"required": []string{"title", "content"},
},
},
},
}
c. Update LLM Processor to Handle Multiple Function Calls
Modify the ProcessAudio function in your LLM processor (e.g., googleai_processor.go) to handle different function calls returned by the LLM:
go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte) (string, error) {
// ... (existing code)
// Check if there are function calls in the response
if answer.Choices[0].ToolCalls != nil && len(answer.Choices[0].ToolCalls) > 0 {
functionCall := answer.Choices[0].ToolCalls[0].FunctionCall
args := functionCall.Arguments
switch functionCall.Name {
case "createNewToDo":
todo, err := createToDo(args)
if err != nil {
return "", err
}
// Store the To-Do and prepare a response
// TODO: Implement storage logic
response := fmt.Sprintf("Created To-Do: %s with items %v", todo.Name, todo.Items)
return response, nil
case "createNewReminder":
reminder, err := createNewReminder(args)
if err != nil {
return "", err
}
// Store the Reminder and prepare a response
// TODO: Implement storage logic
response := fmt.Sprintf("Created Reminder for %s: %s", reminder.Time, reminder.Message)
return response, nil
case "createNewNote":
note, err := createNewNote(args)
if err != nil {
return "", err
}
// Store the Note and prepare a response
// TODO: Implement storage logic
response := fmt.Sprintf("Created Note titled '%s'", note.Title)
return response, nil
default:
logger.Log.Warnf("Unknown function call: %s", functionCall.Name)
}
}
// If no function call, return the LLM's content
return answer.Choices[0].Content, nil
}
Make similar modifications in openai_processor.go if you're using OpenAI.
d. Implement Data Storage
For simplicity, we'll store To-Dos, Reminders, and Notes in memory using a global variable. In a production environment, you should use a database.
Create a new file storage.go in the internal/ directory:
go
package storage
import "sync"
type ToDo struct {
ID int
Name string
Items []string
}
type Reminder struct {
ID int
Time string
Message string
}
type Note struct {
ID int
Title string
Content string
}
var (
toDoList []ToDo
reminderList []Reminder
noteList []Note
toDoIDCounter int
reminderIDCounter int
noteIDCounter int
mu sync.Mutex
)
// Functions to add, edit, and delete To-Dos, Reminders, and Notes
func AddToDo(todo ToDo) {
mu.Lock()
defer mu.Unlock()
toDoIDCounter++
todo.ID = toDoIDCounter
toDoList = append(toDoList, todo)
}
func GetToDos() []ToDo {
mu.Lock()
defer mu.Unlock()
return toDoList
}
// Implement similar functions for Reminders and Notes
Update your functions like createToDo, createNewReminder, and createNewNote to use these storage functions.
e. Update the Handler
Modify your message handler in handler.go to respond appropriately based on the LLM's output.
2. Implementing the Inline Keyboard
a. Update the Keyboard Package
We'll modify the keyboard package to generate an inline keyboard dynamically based on the To-Do list.
Update todo.go in the internal/keyboard/ directory:
go
package keyboard
import (
"context"
"strconv"
"github.com/go-telegram/bot"
tgmodels "github.com/go-telegram/bot/models"
"github.com/rakett1337/tg_assistant_bot/internal/storage"
)
func GenerateToDoKeyboard(b *bot.Bot) *tgmodels.InlineKeyboardMarkup {
toDos := storage.GetToDos()
var rows [][]tgmodels.InlineKeyboardButton
for _, todo := range toDos {
// Each To-Do item as a button
todoButton := tgmodels.InlineKeyboardButton{
Text: todo.Name,
CallbackData: "view_todo_" + strconv.Itoa(todo.ID),
}
// Edit and Delete buttons
editButton := tgmodels.InlineKeyboardButton{
Text: "Edit",
CallbackData: "edit_todo_" + strconv.Itoa(todo.ID),
}
deleteButton := tgmodels.InlineKeyboardButton{
Text: "Delete",
CallbackData: "delete_todo_" + strconv.Itoa(todo.ID),
}
row := []tgmodels.InlineKeyboardButton{todoButton, editButton, deleteButton}
rows = append(rows, row)
}
keyboard := &tgmodels.InlineKeyboardMarkup{
InlineKeyboard: rows,
}
return keyboard
}
b. Handle Callback Queries
In handler.go, add a handler for callback queries:
go
func CallbackQueryHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
callbackQuery := update.CallbackQuery
data := callbackQuery.Data
// Split the callback data to get action and ID
parts := strings.Split(data, "_")
if len(parts) < 3 {
return
}
action := parts[0] + "_" + parts[1]
idStr := parts[2]
id, err := strconv.Atoi(idStr)
if err != nil {
return
}
switch action {
case "view_todo":
// Display the To-Do items
todo := storage.GetToDoByID(id)
if todo != nil {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: callbackQuery.Message.Chat.ID,
Text: fmt.Sprintf("To-Do: %s\nItems:\n%s", todo.Name, strings.Join(todo.Items, "\n")),
})
}
case "edit_todo":
// Implement the edit functionality
// TODO: Add code to handle editing
case "delete_todo":
// Delete the To-Do
storage.DeleteToDoByID(id)
// Update the message with the new keyboard
b.EditMessageReplyMarkup(ctx, &bot.EditMessageReplyMarkupParams{
ChatID: callbackQuery.Message.Chat.ID,
MessageID: callbackQuery.Message.MessageID,
ReplyMarkup: GenerateToDoKeyboard(b),
})
}
// Acknowledge the callback
b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
CallbackQueryID: callbackQuery.ID,
})
}
c. Register the Callback Handler
In your main.go, register the callback query handler:
When responding to the user (e.g., after creating a new To-Do), send the inline keyboard:
go
// In your handler after processing the LLM output
keyboard := keyboard.GenerateToDoKeyboard(b)
_, err = b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Here are your To-Dos:",
ReplyMarkup: keyboard,
})
Putting It All Together
By following these steps, you'll have a bot that:
Can create To-Dos, Reminders, and Notes from voice messages.
Stores them in an in-memory data structure.
Sends an inline keyboard displaying the To-Dos with options to edit or delete.
Note: For the edit functionality, you'll need to implement additional logic to handle user input for the updated To-Do. This may involve tracking the state of conversations with users.
Additional Considerations
Data Persistence: In-memory storage will be lost when the bot restarts. Consider using a database like SQLite, PostgreSQL, or a cloud-based solution to persist data.
Concurrency Safety: Ensure that your storage functions are thread-safe (we used a mutex in storage.go).
User Context: Currently, the bot does not distinguish between different users. You'll need to modify the storage functions to associate To-Dos, Reminders, and Notes with specific users.
Error Handling: Improve error handling and user feedback throughout the code.
Testing: Rigorously test each new feature to ensure it works as expected.
Example of Updated LLM Function Call Handling
Here's how the ProcessAudio function in googleai_processor.go might look after modifications:
go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte) (string, error) {
// ... (code to send audio to LLM and get response)
if len(answer.Choices) > 0 {
choice := answer.Choices[0]
if len(choice.ToolCalls) > 0 {
functionCall := choice.ToolCalls[0].FunctionCall
args := functionCall.Arguments
switch functionCall.Name {
case "createNewToDo":
todo, err := createToDo(args)
if err != nil {
return "", err
}
storage.AddToDo(*todo)
response := fmt.Sprintf("Created To-Do: %s", todo.Name)
return response, nil
case "createNewReminder":
reminder, err := createNewReminder(args)
if err != nil {
return "", err
}
storage.AddReminder(reminder)
response := fmt.Sprintf("Created Reminder for %s", reminder.Time)
return response, nil
case "createNewNote":
note, err := createNewNote(args)
if err != nil {
return "", err
}
storage.AddNote(note)
response := fmt.Sprintf("Created Note titled '%s'", note.Title)
return response, nil
default:
logger.Log.Warnf("Unknown function call: %s", functionCall.Name)
}
} else {
// No function call; return the content
return choice.Content, nil
}
}
return "", errors.New("No valid response from LLM")
}
Final Thoughts
By carefully integrating these changes, you'll enhance your bot's functionality and provide a richer experience for users. Remember to test each part thoroughly and consider edge cases, such as handling invalid user input or network errors.
If you have any questions or need further assistance with specific parts of the code, feel free to ask!