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})
}
fmt.Println("Current User: ", getCurrentUser(), " - ", checkIfLogin())
return c.Render("chat", fiber.Map{"IsLogin": checkIfLogin(), "HaveKey": checkIfHaveKey()}, "layouts/main")
}
func DeleteMessageHandler(c *fiber.Ctx) error {
messageId := c.FormValue("id")
fmt.Println("Deleting message: " + messageId)
messageUUID, err := edgedb.ParseUUID(messageId)
if err != nil {
fmt.Println("Error in uuid.FromString: in DeleteMessageHandler")
@ -141,7 +137,8 @@ func GetMessageContentHandler(c *fiber.Ctx) error {
content,
llm : {
modelInfo : {
modelID
modelID,
name,
}
}
}

View File

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

View File

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

View File

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

View File

@ -116,15 +116,6 @@ func getLastArea() edgedb.UUID {
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 {
var result User
err := edgeClient.QuerySingle(edgeCtx, "SELECT global currentUser LIMIT 1;", &result)
@ -292,6 +283,7 @@ func getAllMessages() []Message {
llm : {
modelInfo : {
modelID,
name,
company : {
icon
}

View File

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

View File

@ -24,7 +24,7 @@
</span>
</button>
<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()">
<span class="icon">
<i class="fa-solid fa-chevron-right"></i>

View File

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

View File

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

View File

@ -2,6 +2,6 @@
hx-target="#content-{{ ConversationAreaId }}" onclick="updateIcon('{{ message.Icon }}', '{{ ConversationAreaId }}')"
title="{{ message.Name }}">
<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>
</button>