Working event handler

This commit is contained in:
Adrien Bouvais 2024-05-16 00:35:09 +02:00
parent a30a2f2ccd
commit aa41e35cb1
11 changed files with 62 additions and 87 deletions

View File

@ -19,16 +19,12 @@ func ChatPageHandler(c *fiber.Ctx) error {
edgeClient = edgeClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": authCookie}) edgeClient = edgeClient.WithGlobals(map[string]interface{}{"ext::auth::client_token": authCookie})
} }
fmt.Println("Current User: ", getCurrentUser(), " - ", checkIfLogin())
return c.Render("chat", fiber.Map{"IsLogin": checkIfLogin(), "HaveKey": checkIfHaveKey()}, "layouts/main") return c.Render("chat", fiber.Map{"IsLogin": checkIfLogin(), "HaveKey": checkIfHaveKey()}, "layouts/main")
} }
func DeleteMessageHandler(c *fiber.Ctx) error { func DeleteMessageHandler(c *fiber.Ctx) error {
messageId := c.FormValue("id") messageId := c.FormValue("id")
fmt.Println("Deleting message: " + messageId)
messageUUID, err := edgedb.ParseUUID(messageId) messageUUID, err := edgedb.ParseUUID(messageId)
if err != nil { if err != nil {
fmt.Println("Error in uuid.FromString: in DeleteMessageHandler") fmt.Println("Error in uuid.FromString: in DeleteMessageHandler")
@ -141,7 +137,8 @@ func GetMessageContentHandler(c *fiber.Ctx) error {
content, content,
llm : { llm : {
modelInfo : { modelInfo : {
modelID modelID,
name,
} }
} }
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"log" "log"
"strings"
"sync" "sync"
"time" "time"
@ -12,7 +13,9 @@ import (
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
) )
func GenerateMultipleMessagesHandler(c *fiber.Ctx) error { var lastSelectedLLMs []LLM
func GeneratePlaceholderHandler(c *fiber.Ctx) error {
message := c.FormValue("message", "") message := c.FormValue("message", "")
selectedLLMIds := []string{"1e5a07c4-12fe-11ef-8da6-67d29b408c53"} // TODO Hanle in the UI selectedLLMIds := []string{"1e5a07c4-12fe-11ef-8da6-67d29b408c53"} // TODO Hanle in the UI
@ -44,8 +47,7 @@ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error {
} }
selectedLLMs = append(selectedLLMs, selectedLLM) selectedLLMs = append(selectedLLMs, selectedLLM)
} }
lastSelectedLLMs = selectedLLMs
fmt.Println("Selected LLMs: ", selectedLLMs)
_, position := insertArea() _, position := insertArea()
messageID := insertUserMessage(message) messageID := insertUserMessage(message)
@ -57,13 +59,12 @@ func GenerateMultipleMessagesHandler(c *fiber.Ctx) error {
messageOut, _ = botTmpl.Execute(pongo2.Context{"IsPlaceholder": true, "SelectedLLMs": selectedLLMs, "ConversationAreaId": position + 1}) messageOut, _ = botTmpl.Execute(pongo2.Context{"IsPlaceholder": true, "SelectedLLMs": selectedLLMs, "ConversationAreaId": position + 1})
out += messageOut out += messageOut
go HandleGenerateMultipleMessages(selectedLLMs)
return c.SendString(out) return c.SendString(out)
} }
func HandleGenerateMultipleMessages(selectedLLMs []LLM) { func GenerateMultipleMessagesHandler(c *fiber.Ctx) error {
insertArea() insertArea()
selectedLLMs := lastSelectedLLMs
// Create a wait group to synchronize the goroutines // Create a wait group to synchronize the goroutines
var wg sync.WaitGroup var wg sync.WaitGroup
@ -99,12 +100,8 @@ func HandleGenerateMultipleMessages(selectedLLMs []LLM) {
var messageID edgedb.UUID var messageID edgedb.UUID
if addMessageFunc != nil { if addMessageFunc != nil {
messageID = addMessageFunc(selectedLLMs[idx], idx == 0) messageID = addMessageFunc(selectedLLMs[idx], idx == 0)
} else {
fmt.Println("Invalid model: ", selectedLLMs[idx].Model.Company.Name)
} }
fmt.Println("Message ID: ", messageID)
var message Message var message Message
err := edgeClient.QuerySingle(edgeCtx, ` err := edgeClient.QuerySingle(edgeCtx, `
SELECT Message { SELECT Message {
@ -116,7 +113,11 @@ func HandleGenerateMultipleMessages(selectedLLMs []LLM) {
}, },
llm : { llm : {
modelInfo : { modelInfo : {
modelID modelID,
name,
company : {
icon,
}
} }
} }
} }
@ -157,15 +158,15 @@ func HandleGenerateMultipleMessages(selectedLLMs []LLM) {
out += " </ct>" out += " </ct>"
out += "</div>" out += "</div>"
go func() {
// Send Content event // Send Content event
sseChanel.SendEvent( sseChanel.SendEvent(
"swapContent-"+fmt.Sprintf("%d", message.Area.Position), "swapContent-"+fmt.Sprintf("%d", message.Area.Position),
out, out,
) )
fmt.Println(templateMessage) out, err := selectBtnTmpl.Execute(map[string]interface{}{
out, err := modelSelecBtnTmpl.Execute(map[string]interface{}{
"message": templateMessage, "message": templateMessage,
"ConversationAreaId": message.Area.Position, "ConversationAreaId": message.Area.Position,
}) })
@ -174,34 +175,26 @@ func HandleGenerateMultipleMessages(selectedLLMs []LLM) {
log.Fatal(err) log.Fatal(err)
} }
fmt.Println("Sending event: swapSelectionBtn-" + selectedLLMs[idx].ID.String()) // Replace newline characters to prevent premature termination
fmt.Println(out) out = strings.ReplaceAll(out, "\n", "")
// Send Content event // Send Content event
sseChanel.SendEvent( sseChanel.SendEvent(
"swapSelectionBtn-"+templateMessage.ModelID, "swapSelectionBtn-"+selectedLLMs[idx].ID.String(),
out, out,
) )
// Send Icon Swap event // Send Icon Swap event
sseChanel.SendEvent( sseChanel.SendEvent(
"swapIcon-"+fmt.Sprintf("%d", message.Area.Position), "swapIcon-"+fmt.Sprintf("%d", message.Area.Position),
`<img src="icons/`+selectedLLMs[idx].Model.Company.Name+`.png" alt="User Image">`, `<img src="`+selectedLLMs[idx].Model.Company.Icon+`" alt="User Image">`,
) )
}()
default: default:
out, err := modelSelecBtnTmpl.Execute(map[string]interface{}{
"message": templateMessage,
"ConversationAreaId": message.Area.Position,
})
if err != nil {
fmt.Println("Error in modelSelecBtnTmpl.Execute: in HandleGenerateMultipleMessages 4")
log.Fatal(err)
}
// Send Content event // Send Content event
sseChanel.SendEvent( sseChanel.SendEvent(
"swapSelectionBtn-"+templateMessage.ModelID, "swapSelectionBtn-"+templateMessage.ModelID,
out, "New button",
) )
} }
} }
@ -210,4 +203,6 @@ func HandleGenerateMultipleMessages(selectedLLMs []LLM) {
// Wait for all goroutines to finish // Wait for all goroutines to finish
wg.Wait() wg.Wait()
return c.SendString("")
} }

View File

@ -44,7 +44,6 @@ func addGroqMessage(llm LLM, selected bool) edgedb.UUID {
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
} else if len(chatCompletion.Choices) == 0 { } else if len(chatCompletion.Choices) == 0 {
fmt.Println(chatCompletion)
fmt.Println("No response from Groq") fmt.Println("No response from Groq")
id := insertBotMessage("No response from Groq", selected, llm.ID) id := insertBotMessage("No response from Groq", selected, llm.ID)
return id return id
@ -100,7 +99,6 @@ func TestGroqKey(apiKey string) bool {
var chatCompletionResponse GroqChatCompletionResponse var chatCompletionResponse GroqChatCompletionResponse
err = json.Unmarshal(body, &chatCompletionResponse) err = json.Unmarshal(body, &chatCompletionResponse)
fmt.Println(chatCompletionResponse)
if err != nil { if err != nil {
return false return false
} }
@ -125,8 +123,6 @@ func RequestGroq(model string, messages []Message, temperature float64) (GroqCha
return GroqChatCompletionResponse{}, fmt.Errorf("error getting Groq API key: %w", err) return GroqChatCompletionResponse{}, fmt.Errorf("error getting Groq API key: %w", err)
} }
fmt.Println("API key:", apiKey)
url := "https://api.groq.com/openai/v1/chat/completions" url := "https://api.groq.com/openai/v1/chat/completions"
requestBody := GroqChatCompletionRequest{ requestBody := GroqChatCompletionRequest{
@ -135,8 +131,6 @@ func RequestGroq(model string, messages []Message, temperature float64) (GroqCha
Temperature: temperature, Temperature: temperature,
} }
fmt.Println(requestBody)
jsonBody, err := json.Marshal(requestBody) jsonBody, err := json.Marshal(requestBody)
if err != nil { if err != nil {
return GroqChatCompletionResponse{}, fmt.Errorf("error marshaling JSON: %w", err) return GroqChatCompletionResponse{}, fmt.Errorf("error marshaling JSON: %w", err)

View File

@ -43,7 +43,6 @@ func addMistralMessage(llm LLM, selected bool) edgedb.UUID {
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
} else if len(chatCompletion.Choices) == 0 { } else if len(chatCompletion.Choices) == 0 {
fmt.Println(chatCompletion)
fmt.Println("No response from Mistral") fmt.Println("No response from Mistral")
id := insertBotMessage("No response from Mistral", selected, llm.ID) id := insertBotMessage("No response from Mistral", selected, llm.ID)
return id return id
@ -104,7 +103,6 @@ func TestMistralKey(apiKey string) bool {
var chatCompletionResponse MistralChatCompletionResponse var chatCompletionResponse MistralChatCompletionResponse
err = json.Unmarshal(body, &chatCompletionResponse) err = json.Unmarshal(body, &chatCompletionResponse)
fmt.Println(chatCompletionResponse)
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
return false return false

View File

@ -45,7 +45,6 @@ func addOpenaiMessage(llm LLM, selected bool) edgedb.UUID {
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
} else if len(chatCompletion.Choices) == 0 { } else if len(chatCompletion.Choices) == 0 {
fmt.Println(chatCompletion)
fmt.Println("No response from OpenAI") fmt.Println("No response from OpenAI")
id := insertBotMessage("No response from OpenAI", selected, llm.ID) id := insertBotMessage("No response from OpenAI", selected, llm.ID)
return id return id
@ -101,7 +100,6 @@ func TestOpenaiKey(apiKey string) bool {
var chatCompletionResponse OpenaiChatCompletionResponse var chatCompletionResponse OpenaiChatCompletionResponse
err = json.Unmarshal(body, &chatCompletionResponse) err = json.Unmarshal(body, &chatCompletionResponse)
fmt.Println(chatCompletionResponse)
if err != nil { if err != nil {
return false return false
} }

View File

@ -116,15 +116,6 @@ func getLastArea() edgedb.UUID {
return inserted.id return inserted.id
} }
func getCurrentUser() User {
var result User
err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser LIMIT 1;", &result)
if err != nil {
return User{}
}
return result
}
func checkIfLogin() bool { func checkIfLogin() bool {
var result User var result User
err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser LIMIT 1;", &result) err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser LIMIT 1;", &result)
@ -292,6 +283,7 @@ func getAllMessages() []Message {
llm : { llm : {
modelInfo : { modelInfo : {
modelID, modelID,
name,
company : { company : {
icon icon
} }

View File

@ -12,13 +12,13 @@ import (
var userTmpl *pongo2.Template var userTmpl *pongo2.Template
var botTmpl *pongo2.Template var botTmpl *pongo2.Template
var modelSelecBtnTmpl *pongo2.Template var selectBtnTmpl *pongo2.Template
var sseChanel *ssefiber.FiberSSEChannel var sseChanel *ssefiber.FiberSSEChannel
func main() { func main() {
botTmpl = pongo2.Must(pongo2.FromFile("views/partials/message-bot.html")) botTmpl = pongo2.Must(pongo2.FromFile("views/partials/message-bot.html"))
userTmpl = pongo2.Must(pongo2.FromFile("views/partials/message-user.html")) userTmpl = pongo2.Must(pongo2.FromFile("views/partials/message-user.html"))
modelSelecBtnTmpl = pongo2.Must(pongo2.FromFile("views/partials/model-selection-btn.html")) selectBtnTmpl = pongo2.Must(pongo2.FromFile("views/partials/model-selection-btn.html"))
// Import HTML using django engine/template // Import HTML using django engine/template
engine := django.New("./views", ".html") engine := django.New("./views", ".html")
@ -44,6 +44,7 @@ func main() {
// Chat routes // Chat routes
app.Post("/deleteMessage", DeleteMessageHandler) app.Post("/deleteMessage", DeleteMessageHandler)
app.Get("/generatePlaceholder", GeneratePlaceholderHandler)
app.Get("/generateMultipleMessages", GenerateMultipleMessagesHandler) app.Get("/generateMultipleMessages", GenerateMultipleMessagesHandler)
app.Get("/messageContent", GetMessageContentHandler) app.Get("/messageContent", GetMessageContentHandler)
app.Get("/editMessageForm", GetEditMessageFormHandler) app.Get("/editMessageForm", GetEditMessageFormHandler)
@ -67,10 +68,6 @@ func main() {
app.Get("/test", func(c *fiber.Ctx) error { app.Get("/test", func(c *fiber.Ctx) error {
fmt.Println("Hello from test") fmt.Println("Hello from test")
go sseChanel.SendEvent(
"swapIcon-1",
`<img src="icons/groq.png" alt="User Image">`,
)
return c.SendString("") return c.SendString("")
}) })

View File

@ -24,7 +24,7 @@
</span> </span>
</button> </button>
<button disabled type="submit" class="send-button button is-primary is-small" <button disabled type="submit" class="send-button button is-primary is-small"
hx-get="/generateMultipleMessages" hx-swap="beforeend settle:200ms" hx-target="#chat-messages" hx-get="/generatePlaceholder" hx-swap="beforeend settle:200ms" hx-target="#chat-messages"
id="chat-input-send-btn" class="chat-input" hx-include="[name='message']" onclick="clearTextArea()"> id="chat-input-send-btn" class="chat-input" hx-include="[name='message']" onclick="clearTextArea()">
<span class="icon"> <span class="icon">
<i class="fa-solid fa-chevron-right"></i> <i class="fa-solid fa-chevron-right"></i>

View File

@ -23,7 +23,7 @@
<script> <script>
function updateIcon(icon, ConversationAreaId) { function updateIcon(icon, ConversationAreaId) {
var selectedIcon = document.getElementById('selectedIcon-' + ConversationAreaId); var selectedIcon = document.getElementById('selectedIcon-' + ConversationAreaId);
selectedIcon.src = 'icons/' + icon + '.png'; selectedIcon.src = icon;
} }
</script> </script>

View File

@ -13,9 +13,8 @@
{% for message in Messages %} {% for message in Messages %}
{% if not message.Hidden %} {% if not message.Hidden %}
<figure class="image is-48x48" style="flex-shrink: 0;" id="selectedIcon-{{ ConversationAreaId }}" <figure class="image is-48x48" style="flex-shrink: 0;" id="selectedIcon-{{ ConversationAreaId }}">
sse-swap="swapIcon-{{ ConversationAreaId }}"> <img src="{{ message.Icon }}" alt="User Image">
<img src="icons/{{ message.Icon }}.png" alt="User Image">
</figure> </figure>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
@ -26,8 +25,7 @@
<div class="column" id="content-column"> <div class="column" id="content-column">
{% if not IsPlaceholder %} {% if not IsPlaceholder %}
<div class="is-flex is-align-items-start"> <div class="is-flex is-align-items-start">
<div class="message-content" id="content-{{ ConversationAreaId }}" <div class="message-content" id="content-{{ ConversationAreaId }}">
sse-swap="swapContent-{{ ConversationAreaId }}">
{% for message in Messages %} {% for message in Messages %}
{% if not message.Hidden %} {% if not message.Hidden %}
<div class="message-header"> <div class="message-header">
@ -58,7 +56,7 @@
hx-get="/messageContent?id={{ message.Id }}" hx-target="#content-{{ ConversationAreaId }}" hx-get="/messageContent?id={{ message.Id }}" hx-target="#content-{{ ConversationAreaId }}"
onclick="updateIcon('{{ message.Icon }}', '{{ ConversationAreaId }}')" title="{{ message.Name }}"> onclick="updateIcon('{{ message.Icon }}', '{{ ConversationAreaId }}')" title="{{ message.Name }}">
<span class="icon is-small"> <span class="icon is-small">
<img src="icons/{{ message.Icon }}.png" alt="{{ message.Name }}" <img src="{{ message.Icon }}" alt="{{ message.Name }}"
style="max-height: 100%; max-width: 100%;"> style="max-height: 100%; max-width: 100%;">
</span> </span>
</button> </button>
@ -70,6 +68,12 @@
<div class="is-flex is-align-items-start"> <div class="is-flex is-align-items-start">
<div class="message-content" id="content-{{ ConversationAreaId }}" <div class="message-content" id="content-{{ ConversationAreaId }}"
sse-swap="swapContent-{{ ConversationAreaId }}"> sse-swap="swapContent-{{ ConversationAreaId }}">
<hx hx-trigger="load" hx-get="/generateMultipleMessages"></hx>
<div class='message-header'>
<p>
Waiting...
</p>
</div>
<div class="message-body"> <div class="message-body">
<div class="content"> <div class="content">
<img src="/puff.svg" /> <img src="/puff.svg" />
@ -81,7 +85,7 @@
<div class="is-flex is-justify-content mt-2"> <div class="is-flex is-justify-content mt-2">
{% for selectedLLM in SelectedLLMs %} {% for selectedLLM in SelectedLLMs %}
<button disable class="button is-small is-primary message-button is-outlined mr-1" <button disable class="button is-small is-primary message-button is-outlined mr-1"
sse-swap="swapSelectionBtn-{{ selectedLLM.ID }}" hx-swap="outerHTML"> sse-swap="swapSelectionBtn-{{ selectedLLM.ID.String() }}" hx-swap="outerHTML" hx-target="this">
<span class="icon is-small"> <span class="icon is-small">
<!--img src="icons/{{ selectedLLM.Company }}.png" alt="{{ selectedLLM.Name }}" <!--img src="icons/{{ selectedLLM.Company }}.png" alt="{{ selectedLLM.Name }}"
style="max-height: 100%; max-width: 100%;"--> style="max-height: 100%; max-width: 100%;"-->

View File

@ -2,6 +2,6 @@
hx-target="#content-{{ ConversationAreaId }}" onclick="updateIcon('{{ message.Icon }}', '{{ ConversationAreaId }}')" hx-target="#content-{{ ConversationAreaId }}" onclick="updateIcon('{{ message.Icon }}', '{{ ConversationAreaId }}')"
title="{{ message.Name }}"> title="{{ message.Name }}">
<span class="icon is-small"> <span class="icon is-small">
<img src="icons/{{ message.Icon }}.png" alt="{{ message.Name }}" style="max-height: 100%; max-width: 100%;"> <img src="{{ message.Icon }}" alt="{{ message.Name }}" style="max-height: 100%; max-width: 100%;">
</span> </span>
</button> </button>